Merge remote-tracking branch 'origin/main' into fix/the-forge-tools-never-weaken-protection

# Conflicts:
#	modules/gitea/client.ts
This commit is contained in:
jochen
2026-10-09 13:41:02 +02:00
28 changed files with 865 additions and 48 deletions
+5 -5
View File
@@ -94,8 +94,8 @@ another node. So these tools refuse, and say why and how it is done instead:
- `claude_code_hook_register`, `claude_code_settings_set`, `claude_code_permission_add`, `claude_code_permission_remove`:
the operator sets hooks, permission rules and every other managed setting in this module's `managed_settings`
setting, `mesh-controller settings set claude-code '{"managed_settings": {…}}' [--node <node>]`, typed at the
controller's terminal. The controller refuses `managed_settings`, `mcp_servers` and `role` through any verb: a
setting, `mesh-cli settings set claude-code '{"managed_settings": {…}}' [--node <node>]`, typed at the
controller's terminal (`mesh-cli`, or `nox`, on the control-node; hq ADR 0272). The controller refuses `managed_settings`, `mcp_servers` and `role` through any verb: a
mergeable file asks for every key its own content names;
- `claude_code_mcp_register`: the operator sets tool servers in the `mcp_servers` setting the same way;
- a skill, subagent or command that would run something by itself: a shell line the agent runs when it loads one
@@ -117,7 +117,7 @@ decision of 2026-10-09; a surface of the operator's own may update it later). In
skills, commands and subagents at the `mesh` or `node` scope are refused through the tools, and the import tool is
refused. They are keys of this module's settings, each text a list of its lines, because a setting holds no line
break: `instructions`, `output_styles`, `commands` and `agents` map a name to its text; `skills` maps a name to its
files, each a list of lines. For example `mesh-controller settings set claude-code '{"instructions": {"conventions":
files, each a list of lines. For example `mesh-cli settings set claude-code '{"instructions": {"conventions":
["Commit in the imperative.", "", "Test before pushing."]}}'`. They land where a registration did, laid over what was
registered before; what the operator writes there is not judged, but an item that is not well formed is left out and
said in the render's answer. What was registered before is still rendered and may be unregistered.
@@ -156,8 +156,8 @@ A new session takes a change; a running one at `/reload-plugins`.
## Settings
Per node or for the whole mesh, at the controller's terminal alone: `mesh-controller settings set claude-code '<json>'
[--node <node>]`. The controller refuses all three keys through any verb, `mesh-controller.settings` included, because
Per node or for the whole mesh, at the controller's terminal alone: `mesh-cli settings set claude-code '<json>'
[--node <node>]` on the control-node (in zsh, `nox`; hq ADR 0272). The controller refuses all three keys through any verb, `mesh-controller.settings` included, because
each reaches every session on the node and a verb's caller may be an agent (hq issue 340). Reading them through the
verb still answers.
@@ -86,8 +86,8 @@ var nodeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
// AtTheTerminal is how a hook, a permission rule or any other managed setting is set now (novox/hq issue 340):
// in this module's `managed_settings` setting, at the controller's terminal, which refuses it through a verb.
const AtTheTerminal = "mesh-controller settings set claude-code '{\"managed_settings\": {...}}' [--node <node>], " +
"typed by the operator at the controller's terminal"
const AtTheTerminal = "mesh-cli settings set claude-code '{\"managed_settings\": {...}}' [--node <node>], " +
"typed by the operator at the controller's terminal: mesh-cli (nox) on the control-node (novox/hq ADR 0272)"
// RunsInASession says why a kind is never registered through this module: what it holds runs in, or is obeyed
// by, every session it reaches, as whoever starts that session (novox/hq issue 340).
@@ -935,7 +935,7 @@ func SharedTextAtTheTerminal(kind string) string {
KindOutputStyle: "output_styles", KindInstructions: "instructions"}[kind]
return "a " + kind + " for every node or some reaches every session there as the mesh's own word, and this tool " +
"cannot tell an agent from the operator. It is set at the controller's terminal only, under `" + key +
"` in this module's settings, its text as a list of lines: mesh-controller settings set claude-code " +
"` in this module's settings, its text as a list of lines, on the control-node: mesh-cli settings set claude-code " +
"'{\"" + key + "\": {\"<name>\": [\"line\", …]}}' [--node <node>] (novox/hq issue 340). The home scope, " +
"one account's own directory, is still registered here. Nothing was registered"
}
+1 -1
View File
@@ -604,7 +604,7 @@ func OnServerChange(v *ServerView, c ServerChange, p Paths, write WriteManaged)
const ServerAtTheTerminal = "a tool server is started, or handed what the agent asks it, by every session on the nodes it " +
"reaches, as whoever starts that session — the operator, whose account holds root — and the tool runner is not " +
"told who called it, so an agent on another node could register one. It is set at the controller's terminal " +
"only, in this module's mcp_servers setting: mesh-controller settings set claude-code '{\"mcp_servers\": {...}}' " +
"only, in this module's mcp_servers setting, on the control-node: mesh-cli settings set claude-code '{\"mcp_servers\": {...}}' " +
"[--node <node>] (novox/hq issue 340). Nothing was registered"
// RegisterServer unregisters a server: a delete per scope in the `servers` state, taken into this node's view at
@@ -130,7 +130,7 @@ func TestWhatASessionRunsIsRefusedThroughEveryTool(t *testing.T) {
// The settings and the tool server refusals name the terminal's line.
text, _ := s.call(t, "claude_code_settings_set", map[string]any{"settings": map[string]any{"model": "x"}})
if !strings.Contains(text, "mesh-controller settings set claude-code") {
if !strings.Contains(text, "mesh-cli settings set claude-code") {
t.Errorf("the refusal does not say how it is done: %s", text)
}
text, _ = s.call(t, "claude_code_mcp_register", map[string]any{"name": "x", "url": "https://x.example"})
+20
View File
@@ -4,6 +4,26 @@ The forge, and the mesh's npm package registry: it claims the `git` and `npm-pac
Its tools, its events and the provisioner of registry accounts are the TypeScript bundle (`index.ts`,
`tools/`, `provisioner/`). This README covers the Go bundle beside it.
## Announcing pull requests to the merge check (novox/hq to-be 45 §9, issue 347)
Every new head of an open pull request is announced as `pull.updated`, once, and the controller has it checked.
- **Which repositories a pass looks at.** Each that moved since the last pass, less a minute's margin (issue 250);
each holding a pull request updated since then, found by the forge's own search — opening, reopening or
retargeting a pull request moves its own update time and not its repository's, and a pull request opened more
than a minute after its push was never announced (issue 347); and every repository on a sweep, every ten
minutes, or when the search fails.
- **A pull request nobody checks is said — by the delivery's owner, not here.** `gitea_open_pulls` answers every
open pull request from the forge itself, with the statuses its base requires and the ones its head has. The
`mesh-delivery` module asks it every five minutes, and a head on a base requiring `mesh/merge-gate` or
`mesh/repo-check` with neither for ten minutes since it first saw it so is a delivery held past its bound
(`delivery.<id>.stalled`, state `unannounced`), which the controller raises like any other (issue 347).
- **How to see it work.** A pull request opened more than a minute after its branch was pushed — this fix's own
was one, and the announcer it fixes never saw it — has `mesh/merge-gate` pending within a pass of the next sweep
at the latest, and `mesh-controller.conditions` names none for it.
- **A pull request or issue number that is not one is refused** before the forge is asked: a tool called with a
misnamed argument sent `pulls/NaN`.
## The package registry's retention (novox/hq ADR 0251 §4, to-be 51)
Every publish adds a version to the registry, and until this nothing removed one. The Go bundle
+110 -30
View File
@@ -9,6 +9,12 @@ import { protectionBody, type BranchProtection, type ProtectionWanted } from "./
import { Refused, checkSentPath, pathSegment, pathSegments } from "./guard.js";
import { isCommit } from "./checks.js";
/** A repository's path on the forge, its owner and name each one segment (guard.ts pathSegment): uniform for every
* call, whether the names came from a caller or from the forge's own answer. */
function repoPath(owner: unknown, repo: unknown): string {
return `/repos/${pathSegment("repository owner", owner)}/${pathSegment("repository name", repo)}`;
}
/** A commit, by its sha or the start of one, as it goes in a path: anything else is refused before it is sent. */
function commitSegment(sha: unknown): string {
const v = String(sha ?? "");
@@ -63,6 +69,20 @@ export interface GiteaPull {
body?: string;
}
/** An open pull request with what its base requires and what its head has: what gitea_open_pulls answers. */
export interface OpenPull {
owner: string;
repo: string;
number: number;
base: string;
head_sha: string;
html_url?: string;
/** The contexts the base branch's protection requires; none when it requires none, or cannot be read. */
required: string[];
/** The contexts the head has a status of, in any state. */
statuses: string[];
}
/** A commit status, as the forge keeps it: what a pull request shows beside its head commit. */
export interface CommitStatus {
state: "pending" | "success" | "error" | "failure" | "warning";
@@ -192,19 +212,20 @@ export class GiteaClient {
}
async deleteRepo(owner: string, repo: string): Promise<void> {
await this.request(`/repos/${owner}/${repo}`, { method: "DELETE" });
await this.request(`${repoPath(owner, repo)}`, { method: "DELETE" });
}
// ---- Issues ----
async listIssues(owner: string, repo: string, params: Record<string, string> = {}): Promise<GiteaIssue[]> {
const qs = new URLSearchParams({ type: "issues", ...params }).toString();
const issues = await this.request<any[]>(`/repos/${owner}/${repo}/issues?${qs}`);
const issues = await this.request<any[]>(`${repoPath(owner, repo)}/issues?${qs}`);
return (issues ?? []).map(GiteaClient.mapIssue);
}
async getIssue(owner: string, repo: string, index: number): Promise<GiteaIssue> {
return GiteaClient.mapIssue(await this.request<any>(`/repos/${owner}/${repo}/issues/${index}`));
indexOf(index);
return GiteaClient.mapIssue(await this.request<any>(`${repoPath(owner, repo)}/issues/${index}`));
}
async createIssue(
@@ -213,14 +234,15 @@ export class GiteaClient {
data: { title: string; body?: string; labels?: number[] },
): Promise<GiteaIssue> {
return GiteaClient.mapIssue(
await this.request<any>(`/repos/${owner}/${repo}/issues`, { method: "POST", body: JSON.stringify(data) }),
await this.request<any>(`${repoPath(owner, repo)}/issues`, { method: "POST", body: JSON.stringify(data) }),
);
}
/** Patch an issue's state — the one edit the close tool needs. */
async setIssueState(owner: string, repo: string, index: number, state: "open" | "closed"): Promise<GiteaIssue> {
indexOf(index);
return GiteaClient.mapIssue(
await this.request<any>(`/repos/${owner}/${repo}/issues/${index}`, {
await this.request<any>(`${repoPath(owner, repo)}/issues/${index}`, {
method: "PATCH",
body: JSON.stringify({ state }),
}),
@@ -228,7 +250,8 @@ export class GiteaClient {
}
async addComment(owner: string, repo: string, index: number, body: string): Promise<{ id: number; html_url: string }> {
const c = await this.request<any>(`/repos/${owner}/${repo}/issues/${index}/comments`, {
indexOf(index);
const c = await this.request<any>(`${repoPath(owner, repo)}/issues/${index}/comments`, {
method: "POST",
body: JSON.stringify({ body }),
});
@@ -238,7 +261,7 @@ export class GiteaClient {
// ---- Labels ----
async listLabels(owner: string, repo: string): Promise<GiteaLabel[]> {
const labels = await this.request<any[]>(`/repos/${owner}/${repo}/labels`);
const labels = await this.request<any[]>(`${repoPath(owner, repo)}/labels`);
return (labels ?? []).map((l: any) => ({ id: l.id, name: l.name }));
}
@@ -247,7 +270,7 @@ export class GiteaClient {
repo: string,
data: { name: string; color: string; description?: string },
): Promise<GiteaLabel> {
const l = await this.request<any>(`/repos/${owner}/${repo}/labels`, { method: "POST", body: JSON.stringify(data) });
const l = await this.request<any>(`${repoPath(owner, repo)}/labels`, { method: "POST", body: JSON.stringify(data) });
return { id: l.id, name: l.name };
}
@@ -263,12 +286,53 @@ export class GiteaClient {
async listPullRequests(owner: string, repo: string, params: Record<string, string> = {}): Promise<GiteaPull[]> {
const qs = new URLSearchParams(params).toString();
const prs = await this.request<any[]>(`/repos/${owner}/${repo}/pulls?${qs}`);
const prs = await this.request<any[]>(`${repoPath(owner, repo)}/pulls?${qs}`);
return (prs ?? []).map(GiteaClient.mapPull);
}
/** The open pull requests of every repository the mesh's account sees, updated since a moment when one is given,
* page by page (novox/hq issue 347): each with its repository and its own update time. */
async searchOpenPulls(since?: string): Promise<{ owner: string; name: string; number: number; updated_at?: string }[]> {
const out: { owner: string; name: string; number: number; updated_at?: string }[] = [];
for (let page = 1; page <= 20; page++) {
const qs = new URLSearchParams({ type: "pulls", state: "open", limit: "50", page: String(page) });
if (since) qs.set("since", since);
const found = await this.request<any[]>(`/repos/issues/search?${qs}`);
for (const i of found ?? []) {
const r = i?.repository ?? {};
const [fo, fn] = String(r.full_name ?? "").split("/");
const owner = String(r.owner ?? fo ?? "");
const name = String(r.name ?? fn ?? "");
if (owner && name && i?.number) out.push({ owner, name, number: Number(i.number), updated_at: i.updated_at });
}
if (!found || found.length < 50) break;
}
return out;
}
/** **Every open pull request, from the forge itself** (novox/hq issue 347): with what its base's protection
* requires and the contexts its head has a status of, in any state. What mesh-delivery reads to say a pull
* request the mesh was never asked to check; asked of the forge, never of what the announcer remembers, so a
* fault in the announcer cannot hide itself. Reads only. */
async openPulls(): Promise<OpenPull[]> {
const out: OpenPull[] = [];
const rules = new Map<string, BranchProtection[] | undefined>();
for (const found of await this.searchOpenPulls()) {
const full = `${found.owner}/${found.name}`;
const pull = await this.getPullRequest(found.owner, found.name, found.number);
if (pull.state !== "open" || !pull.head_sha) continue;
if (!rules.has(full)) rules.set(full, await this.branchProtections(found.owner, found.name).catch(() => undefined));
const rule = rules.get(full)?.find((p) => (p.rule_name ?? p.branch_name) === (pull.base || "main"));
const statuses = Object.keys(await this.commitStatuses(found.owner, found.name, pull.head_sha));
out.push({ owner: found.owner, repo: found.name, number: pull.number, base: pull.base ?? "", head_sha: pull.head_sha,
html_url: pull.html_url, required: rule?.enable_status_check ? (rule.status_check_contexts ?? []) : [], statuses });
}
return out;
}
async getPullRequest(owner: string, repo: string, index: number): Promise<GiteaPull> {
return GiteaClient.mapPull(await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`));
indexOf(index);
return GiteaClient.mapPull(await this.request<any>(`${repoPath(owner, repo)}/pulls/${index}`));
}
/** The files a merged pull request changed, as paths from the repository's root.
@@ -285,11 +349,12 @@ export class GiteaClient {
* deleted is gone from its source, and the mesh forgets it rather than asking its build (novox/hq ADR
* 0236). The forge says `deleted`; `removed` is read the same. */
async listPullFiles(owner: string, repo: string, index: number, most = 3000): Promise<{ paths: string[]; removed: string[]; truncated: boolean }> {
indexOf(index);
const paths: string[] = [];
const removed: string[] = [];
let pageSize = 0;
for (let page = 1; ; page++) {
const files = (await this.request<any[]>(`/repos/${owner}/${repo}/pulls/${index}/files?limit=50&page=${page}`)) ?? [];
const files = (await this.request<any[]>(`${repoPath(owner, repo)}/pulls/${index}/files?limit=50&page=${page}`)) ?? [];
if (page === 1) pageSize = files.length;
for (const f of files) {
const name = String(f?.filename ?? "");
@@ -318,7 +383,7 @@ export class GiteaClient {
if (dirs.length > most) return null;
const out: string[] = [];
for (const dir of dirs) {
if (await this.exists(`/repos/${owner}/${repo}/contents/${encodePath(dir + "/module.json")}?ref=${encodeURIComponent(sha)}`)) {
if (await this.exists(`${repoPath(owner, repo)}/contents/${encodePath(dir + "/module.json")}?ref=${encodeURIComponent(sha)}`)) {
out.push(dir);
}
}
@@ -327,7 +392,7 @@ export class GiteaClient {
/** Whether a repository holds a file at a commit: true, false for a 404, thrown when the forge cannot say. */
async holdsFile(owner: string, repo: string, sha: string, file: string): Promise<boolean> {
return this.exists(`/repos/${owner}/${repo}/contents/${encodePath(file)}?ref=${encodeURIComponent(sha)}`);
return this.exists(`${repoPath(owner, repo)}/contents/${encodePath(file)}?ref=${encodeURIComponent(sha)}`);
}
/** Whether the forge has something at a path: true for an answer, false for a 404, thrown otherwise. */
@@ -347,12 +412,12 @@ export class GiteaClient {
/** Set a commit's status — what a pull request whose head it is shows beside it (novox/hq to-be 45 §9).
* The forge keeps one per context, the newest, so setting it again replaces it. */
async setCommitStatus(owner: string, repo: string, sha: string, status: CommitStatus): Promise<void> {
await this.request(`/repos/${owner}/${repo}/statuses/${commitSegment(sha)}`, { method: "POST", body: JSON.stringify(status) });
await this.request(`${repoPath(owner, repo)}/statuses/${commitSegment(sha)}`, { method: "POST", body: JSON.stringify(status) });
}
/** A commit's statuses by context, the newest of each: what a merge's head was checked as (novox/hq ADR 0239). */
async commitStatuses(owner: string, repo: string, sha: string): Promise<Record<string, string>> {
const raw = await this.request<any>(`/repos/${owner}/${repo}/commits/${commitSegment(sha)}/status`);
const raw = await this.request<any>(`${repoPath(owner, repo)}/commits/${commitSegment(sha)}/status`);
const out: Record<string, string> = {};
for (const s of raw?.statuses ?? []) if (s?.context && !out[s.context]) out[s.context] = String(s.status ?? s.state ?? "");
return out;
@@ -361,19 +426,19 @@ export class GiteaClient {
/** A commit's statuses whole, as the forge combines them for a ref (a sha, or the start of one): the commit
* it resolved to and every status with its description, link, times and setter (novox/hq ADR 0239). */
async combinedStatus(owner: string, repo: string, ref: string): Promise<{ sha: string; state: string; statuses: unknown[] }> {
const raw = await this.request<any>(`/repos/${owner}/${repo}/commits/${pathSegment("commit or branch", ref)}/status?limit=50`);
const raw = await this.request<any>(`${repoPath(owner, repo)}/commits/${pathSegment("commit or branch", ref)}/status?limit=50`);
return { sha: String(raw?.sha ?? ""), state: String(raw?.state ?? ""), statuses: Array.isArray(raw?.statuses) ? raw.statuses : [] };
}
/** The forge's compare of two commits, `base...head`: the commits on head that base lacks, and how many
* (novox/hq ADR 0270). Reads only. */
async compare(owner: string, repo: string, base: string, head: string): Promise<unknown> {
return this.request<unknown>(`/repos/${owner}/${repo}/compare/${commitSegment(base)}...${commitSegment(head)}`);
return this.request<unknown>(`${repoPath(owner, repo)}/compare/${commitSegment(base)}...${commitSegment(head)}`);
}
/** Replace a comment's body: the delivery's view, kept current in place (novox/hq ADR 0239). */
async editComment(owner: string, repo: string, id: number, body: string): Promise<{ id: number; html_url: string }> {
const c = await this.request<any>(`/repos/${owner}/${repo}/issues/comments/${id}`, { method: "PATCH", body: JSON.stringify({ body }) });
const c = await this.request<any>(`${repoPath(owner, repo)}/issues/comments/${id}`, { method: "PATCH", body: JSON.stringify({ body }) });
return { id: Number(c?.id ?? id), html_url: String(c?.html_url ?? "") };
}
@@ -381,7 +446,7 @@ export class GiteaClient {
/** A repository's branch protection rules. */
async branchProtections(owner: string, repo: string): Promise<BranchProtection[]> {
return (await this.request<BranchProtection[]>(`/repos/${owner}/${repo}/branch_protections`)) ?? [];
return (await this.request<BranchProtection[]>(`${repoPath(owner, repo)}/branch_protections`)) ?? [];
}
/** The rule named for a branch, null when it has none. */
@@ -396,11 +461,11 @@ export class GiteaClient {
const had = await this.branchProtection(owner, repo, branch);
const body = protectionBody(want, !had);
if (had) {
const rule = await this.request<BranchProtection>(`/repos/${owner}/${repo}/branch_protections/${pathSegments("branch", branch)}`,
const rule = await this.request<BranchProtection>(`${repoPath(owner, repo)}/branch_protections/${pathSegments("branch", branch)}`,
{ method: "PATCH", body: JSON.stringify(body) });
return { created: false, rule };
}
const rule = await this.request<BranchProtection>(`/repos/${owner}/${repo}/branch_protections`,
const rule = await this.request<BranchProtection>(`${repoPath(owner, repo)}/branch_protections`,
{ method: "POST", body: JSON.stringify({ rule_name: branch, ...body }) });
return { created: true, rule };
}
@@ -411,33 +476,37 @@ export class GiteaClient {
data: { title: string; body?: string; head: string; base: string },
): Promise<GiteaPull> {
return GiteaClient.mapPull(
await this.request<any>(`/repos/${owner}/${repo}/pulls`, { method: "POST", body: JSON.stringify(data) }),
await this.request<any>(`${repoPath(owner, repo)}/pulls`, { method: "POST", body: JSON.stringify(data) }),
);
}
/** Close or reopen a pull request without merging it. A pull request is an issue to the forge's
* state machine, and the pulls endpoint takes the same `state`. */
async setPullState(owner: string, repo: string, index: number, state: "open" | "closed"): Promise<GiteaPull> {
indexOf(index);
return GiteaClient.mapPull(
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify({ state }) }),
await this.request<any>(`${repoPath(owner, repo)}/pulls/${index}`, { method: "PATCH", body: JSON.stringify({ state }) }),
);
}
/** Change a pull request's title or body; a field left undefined is left alone. */
async updatePullRequest(owner: string, repo: string, index: number, data: { title?: string; body?: string }): Promise<GiteaPull> {
indexOf(index);
return GiteaClient.mapPull(
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify(data) }),
await this.request<any>(`${repoPath(owner, repo)}/pulls/${index}`, { method: "PATCH", body: JSON.stringify(data) }),
);
}
/** The unified diff of a pull request, as text. */
async pullDiff(owner: string, repo: string, index: number): Promise<string> {
return this.requestText(`/repos/${owner}/${repo}/pulls/${index}.diff`);
indexOf(index);
return this.requestText(`${repoPath(owner, repo)}/pulls/${index}.diff`);
}
/** Every comment on an issue or pull request, oldest first. */
async listComments(owner: string, repo: string, index: number): Promise<GiteaComment[]> {
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/issues/${index}/comments`);
indexOf(index);
const raw = await this.request<any[]>(`${repoPath(owner, repo)}/issues/${index}/comments`);
return (raw ?? []).map((c) => ({
id: Number(c?.id ?? 0),
user: c?.user?.login,
@@ -450,19 +519,19 @@ export class GiteaClient {
/** One file's contents at a ref (default the repository's default branch), decoded. */
async getFile(owner: string, repo: string, path: string, ref?: string): Promise<{ path: string; ref?: string; sha: string; size: number; content: string }> {
const qs = ref ? `?ref=${encodeURIComponent(ref)}` : "";
const f = await this.request<any>(`/repos/${owner}/${repo}/contents/${pathSegments("file path", path.replace(/^\/+|\/+$/g, ""))}${qs}`);
const f = await this.request<any>(`${repoPath(owner, repo)}/contents/${pathSegments("file path", path.replace(/^\/+|\/+$/g, ""))}${qs}`);
if (!f || f.type !== "file") throw new Error(`Gitea API: ${path} is not a file`);
const content = f.encoding === "base64" ? Buffer.from(String(f.content ?? ""), "base64").toString("utf8") : String(f.content ?? "");
return { path, ref, sha: String(f.sha ?? ""), size: Number(f.size ?? content.length), content };
}
async listBranches(owner: string, repo: string): Promise<{ name: string; commit: string; protected: boolean }[]> {
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/branches?limit=100`);
const raw = await this.request<any[]>(`${repoPath(owner, repo)}/branches?limit=100`);
return (raw ?? []).map((b) => ({ name: String(b?.name ?? ""), commit: String(b?.commit?.id ?? ""), protected: Boolean(b?.protected) }));
}
async deleteBranch(owner: string, repo: string, branch: string): Promise<void> {
await this.request(`/repos/${owner}/${repo}/branches/${pathSegments("branch", branch)}`, { method: "DELETE" });
await this.request(`${repoPath(owner, repo)}/branches/${pathSegments("branch", branch)}`, { method: "DELETE" });
}
/** A request whose answer is text, not JSON — a diff. Same token handling as request(). */
@@ -477,7 +546,8 @@ export class GiteaClient {
* the forge refuses the merge when the branch moved since (novox/hq ADR 0266). */
async mergePullRequest(owner: string, repo: string, index: number, method = "merge", deleteBranch = false,
headCommit?: string): Promise<void> {
await this.request(`/repos/${owner}/${repo}/pulls/${index}/merge`, {
indexOf(index);
await this.request(`${repoPath(owner, repo)}/pulls/${index}/merge`, {
method: "POST",
body: JSON.stringify({ Do: method, delete_branch_after_merge: deleteBranch, force_merge: false,
...(headCommit ? { head_commit_id: headCommit } : {}) }),
@@ -743,6 +813,16 @@ export class GiteaAdmin {
}
}
/** A pull request's or issue's number, refused unless it is one: a tool asked with a misnamed argument hands over
* `NaN`, and the forge was asked about `pulls/NaN` (novox/hq issue 347). */
export function indexOf(index: number): number {
if (!Number.isInteger(index) || index <= 0) {
throw new Error(`a pull request or issue number is a whole number above 0, and ${String(index)} was given — ` +
"is the argument named \`number\`? Nothing was asked of the forge");
}
return index;
}
/** The repositories that moved at or after a moment: every one when there is no moment yet, and one whose
* update time is not known, so a forge that does not say is asked as before (novox/hq issue 250). */
export function movedSince(repos: GiteaRepo[], floor: string): GiteaRepo[] {
+19 -2
View File
@@ -28,7 +28,7 @@
import { emit, on } from "@novox/mesh-sdk/events";
import { GiteaClient, movedSince } from "./client.js";
import { CHECK_CONTEXT, REPO_CHECK_CONTEXT, commentFor, headsToAnnounce, statusesFor, type Announced, type Checked,
type RepoCheckFacts } from "./pulls.js";
type RepoCheckFacts, reposToLook } from "./pulls.js";
// Without a way to a token — configured, or mintable with the admin account (token.ts) — there is
// nothing to watch; log and stay quiet rather than crash the runtime. With one, the first poll mints
@@ -213,12 +213,29 @@ function keepHeads(): void {
renameSync(tmp, pullsRecord);
}
let lastPullLook = "";
// **A sweep now and then looks at every repository** (novox/hq issue 347), whatever moved: the floor is a
// heuristic, and a heuristic that misses is caught by the next sweep rather than never.
const SWEEP_MS = 10 * 60_000;
let lastSweep = 0;
async function pollPulls(client: GiteaClient): Promise<void> {
const began = new Date().toISOString();
const floor = lastPullLook ? new Date(Date.parse(lastPullLook) - MARGIN_MS).toISOString() : "";
const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString();
let changed = false;
for (const repo of movedSince(await client.listAllRepos(), floor)) {
// A pull request opened, reopened or retargeted moves its own update time and not its repository's: the
// pull requests updated since the floor are found by their own (issue 347). A search that fails is a sweep.
let sweep = Date.now() - lastSweep >= SWEEP_MS;
let updated: { owner: string; name: string; updated_at?: string }[] = [];
if (floor && !sweep) {
try {
updated = await client.searchOpenPulls(floor);
} catch (err) {
console.error(`[gitea] the pull requests updated lately could not be searched, so every repository is looked at — ${err instanceof Error ? err.message : err}`);
sweep = true;
}
}
if (sweep) lastSweep = Date.now();
for (const repo of reposToLook(await client.listAllRepos(), floor, updated, sweep)) {
const open = await client.listPullRequests(repo.owner, repo.name, { state: "open", sort: "recentupdate", limit: "20" });
for (const pull of headsToAnnounce(repo.full_name, open, heads)) {
const key = `${repo.full_name}#${pull.number}`;
+22 -1
View File
@@ -9,7 +9,8 @@
//
// Pure functions here, so they are tested without a forge; index.ts does the asking and the setting.
import type { CommitStatus, GiteaPull } from "./client.js";
import type { CommitStatus, GiteaPull, GiteaRepo } from "./client.js";
import { movedSince } from "./client.js";
/** The status context a merge check's gate is kept under: one per commit, the newest replacing the last. */
export const CHECK_CONTEXT = "mesh/merge-gate";
@@ -92,6 +93,26 @@ export function headsToAnnounce(full: string, pulls: GiteaPull[], announced: Ann
return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[`${full}#${p.number}`] !== p.head_sha);
}
/** A pull request the forge found updated, by its repository: what `searchOpenPulls` answers. */
export interface PullSeen {
owner: string;
name: string;
updated_at?: string;
}
/** **The repositories a pass looks at** (novox/hq issue 347): every one that moved since the floor, every one
* holding a pull request updated since the floor — opening, reopening or retargeting a pull request moves its own
* update time and not its repository's — and every one on a sweep or the first pass. */
export function reposToLook(repos: GiteaRepo[], floor: string, pulls: PullSeen[], sweep: boolean): GiteaRepo[] {
if (sweep || !floor) return repos;
const moved = new Set(movedSince(repos, floor).map((r) => r.full_name));
const at = Date.parse(floor);
for (const p of pulls) {
if (!p.updated_at || !(Date.parse(p.updated_at) < at)) moved.add(`${p.owner}/${p.name}`);
}
return repos.filter((r) => moved.has(r.full_name));
}
// **A required status is success or it blocks** (novox/hq issue 293). The forge combines `warning` as a
// failure, and a branch whose protection requires mesh/merge-gate or mesh/repo-check — with no
// administrator override — will not merge past one. So the controller's `warning`, a note and never a
+91
View File
@@ -0,0 +1,91 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createServer } from "node:http";
// **A pull request opened after its push is still checked** (novox/hq issue 347). The announcer read only the
// repositories whose update time moved since its last pass, less a minute's margin; opening, reopening or
// retargeting a pull request does not move a repository's update time, so a pull request opened more than a
// minute or so after its push was never announced, never checked, and nothing said so.
const repo = (full: string, updated: string) => {
const [owner, name] = full.split("/");
return { full_name: full, owner, name, private: false, html_url: "", updated_at: updated };
};
test("a pull request opened after the margin is looked at, by its own update time", async () => {
const { reposToLook } = await import("../pulls.ts");
const pushed = "2026-10-09T10:00:00Z"; // the branch pushed: the repository's update time
// The pull request opened two minutes later; the last pass was at 10:02:30, so the floor is 10:01:30.
const floor = "2026-10-09T10:01:30Z";
const repos = [repo("novox/mesh-sdk", pushed), repo("novox/hq", "2026-10-09T09:00:00Z")];
const opened = [{ owner: "novox", name: "mesh-sdk", updated_at: "2026-10-09T10:02:00Z" }];
assert.deepEqual(reposToLook(repos, floor, opened, false).map((r) => r.full_name), ["novox/mesh-sdk"],
"the repository of a pull request updated since the floor, though the repository itself did not move");
assert.deepEqual(reposToLook(repos, floor, [], false).map((r) => r.full_name), [],
"without the pull request's own time nothing is looked at — the fault");
assert.deepEqual(reposToLook(repos, floor, [], true).map((r) => r.full_name).sort(), ["novox/hq", "novox/mesh-sdk"],
"a sweep looks at every repository");
assert.deepEqual(reposToLook(repos, "", [], false).length, 2, "the first pass looks at every repository");
});
test("every open pull request is read with what its base requires and what its head has (gitea_open_pulls)", async () => {
const { GiteaClient } = await import("../client.ts");
const asked: string[] = [];
const server = createServer((req, res) => {
asked.push(req.url ?? "");
const url = req.url ?? "";
const send = (v: unknown) => res.end(JSON.stringify(v));
if (url.startsWith("/api/v1/repos/issues/search")) {
return send(url.includes("page=1") ? [
{ number: 243, repository: { owner: "novox", name: "hq", full_name: "novox/hq" }, updated_at: "2026-10-09T11:00:00Z" },
{ number: 14, repository: { owner: "novox", name: "mesh-sdk", full_name: "novox/mesh-sdk" } },
] : []);
}
if (url.startsWith("/api/v1/repos/novox/hq/pulls/243")) {
return send({ number: 243, state: "open", base: { ref: "main" }, head: { ref: "x", sha: "aaa111" }, html_url: "h" });
}
if (url.startsWith("/api/v1/repos/novox/mesh-sdk/pulls/14")) {
return send({ number: 14, state: "open", base: { ref: "main" }, head: { ref: "y", sha: "bbb222" }, html_url: "s" });
}
if (url.startsWith("/api/v1/repos/novox/hq/branch_protections")) {
return send([{ rule_name: "main", enable_status_check: true, status_check_contexts: ["mesh/repo-check"] }]);
}
if (url.startsWith("/api/v1/repos/novox/mesh-sdk/branch_protections")) {
return send([{ rule_name: "main", enable_status_check: true, status_check_contexts: ["mesh/merge-gate", "mesh/repo-check"] }]);
}
if (url.includes("/commits/aaa111/status")) return send({ statuses: [] });
if (url.includes("/commits/bbb222/status")) return send({ statuses: [{ context: "mesh/merge-gate", status: "pending" }] });
res.statusCode = 404;
res.end("{}");
});
await new Promise<void>((r) => server.listen(0, r));
const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t");
try {
const open = await client.openPulls();
assert.deepEqual(open.map((p) => [p.owner, p.repo, p.number, p.base, p.head_sha, p.required, p.statuses]), [
["novox", "hq", 243, "main", "aaa111", ["mesh/repo-check"], []],
["novox", "mesh-sdk", 14, "main", "bbb222", ["mesh/merge-gate", "mesh/repo-check"], ["mesh/merge-gate"]],
]);
} finally {
server.close();
}
});
test("a pull request or issue number that is not one is refused before the forge is asked", async () => {
const { GiteaClient } = await import("../client.ts");
let asked = 0;
const server = createServer((_req, res) => {
asked++;
res.end("{}");
});
await new Promise<void>((r) => server.listen(0, r));
const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t");
try {
await assert.rejects(client.getPullRequest("novox", "hq", Number(undefined)), /whole number/);
await assert.rejects(client.addComment("novox", "hq", 0, "x"), /whole number/);
await assert.rejects(client.listPullFiles("novox", "hq", 1.5), /whole number/);
assert.equal(asked, 0, "the forge was asked about pulls/NaN");
} finally {
server.close();
}
});
+1 -1
View File
@@ -426,7 +426,7 @@ test("the tools register once there is a way to a token, and the first call mint
"gitea_list_branches",
"gitea_delete_branch",
"gitea_branch_protection_get", "gitea_branch_protection_set",
"gitea_note_append", "gitea_delivery_view", "gitea_commit_statuses", "gitea_contains", "gitea_commit_status",
"gitea_note_append", "gitea_delivery_view", "gitea_commit_statuses", "gitea_open_pulls", "gitea_contains", "gitea_commit_status",
"gitea_list_labels", "gitea_create_label",
"gitea_api",
],
+6
View File
@@ -553,6 +553,12 @@ function allGiteaTools(gitea: GiteaClient): ToolDefinition[] {
merge: mergeableUnder(base, rule, statuses, unreadable) };
},
},
{
name: "gitea_open_pulls",
description: "Every open pull request of every repository, from the forge itself: its head, its base, the statuses the base's protection requires and the ones its head has, in any state. What mesh-delivery reads to say a pull request the mesh was never asked to check (novox/hq issue 347). Reads only.",
input: {},
run: async () => ({ pulls: await gitea.openPulls() }),
},
{
name: "gitea_contains",
description: "Whether a commit is contained in another — an ancestor of it, or the same — from the forge's compare of the two: what mesh-delivery reads before it says a held merge is covered by a later one (novox/hq ADR 0270). Commits only, by sha or the start of one. Reads only.",
+64
View File
@@ -0,0 +1,64 @@
# mesh-cli
The operator's command on every node (novox/hq ADR 0272): `mesh-cli <command line>` asks the controller to run one
of its command lines, from wherever the operator is. In interactive zsh it is also `nox`.
```
nox status
nox settings show zsh --node <node>
nox settings set zsh '{"execute":"withhold"}' --node <node>
```
## What it places
| What | Where | How |
|---|---|---|
| the program | `/usr/local/bin/mesh-cli` | the `program` bundle, unpacked by an `archive` resource: the node-engine moves the one file in, refuses to write over a file it did not place, and takes out only that file when the module goes |
| the alias `nox` | the zsh module's mesh block in `~/.zshrc` | a `shell` contribution in the `normal` slot (ADR 0204) |
No link and no second copy. `/usr/local/bin` is on every account's `PATH` already, so the module contributes no
environment. The alias is interactive zsh only: a script, `sudo`, a cron line and any document meant to work
everywhere say `mesh-cli`. In interactive zsh the alias hides any other `nox` (Arch's `python-nox` installs
`/usr/bin/nox`); `command nox` still reaches it.
## How it is answered
`mesh-cli` holds no credential and reads no file of the mesh. It writes one request to the node-engine's socket
(the SDK's `go/cli`: the line, as words) and prints the one answer.
1. The node-engine reads which account is asking from the kernel, never from the program, and asks the controller
on its own node's subject.
2. The controller judges (ADR 0272 §4):
- **the controller's terminal**: the node's operator account, on the control-node. The line runs as the
operator typed it there.
- **an ordinary call**: the node's operator account on any other node, where agents may run as that account.
It meets every refusal of the generic `command` verb, and a change made at the terminal alone is refused with
the reason.
- **refused**: any other account, root included. Run it as yourself, not under `sudo`.
3. A line still running after ten seconds is followed by its call until it ends. `mesh-cli` prints standard
output and standard error as the command wrote them, says why a line was not the terminal or was refused, says
when the output was cut to fit one bus message, and exits with the command's status. When no answer comes in
time it says the line may have run and names its call; "nothing ran" is said only of a line no controller
took.
A process that runs for a verb (it carries `MESH_VERB`) is refused before anything is asked: a verb is never the
operator.
## What it does not do yet
- **No standard input.** A command that reads one gets nothing, and fails saying so.
- **No local files.** A path in a line names a file where the controller runs, read by the controller's account.
Give settings inline: `nox settings set <module> "$(cat settings.json)" --node <node>`.
- **No streaming.** The answer arrives when the command ends, within the controller's bound on a call (five
minutes). Interrupting `mesh-cli` stops the wait, not the command.
- **The `MESH_VERB` refusal is a courtesy.** A verb's process is refused before asking, but the gate is the
controller: it judges the account the node-engine vouches for, whatever the program says.
- **No other node is the terminal.** Phase 2 of ADR 0272 adds a node whose agents run under an account of their
own (ADR 0266), judged unable to become root.
## Tests
`go test ./...`: the module places exactly one file (one archive resource, one Go bundle compiled to the binary
alone); the line is asked as given and the answer printed with its exit; a reason, a refusal, a cut and an outcome not known
are said and a refusal never exits 0; a verb's process is refused before asking; an engine that does not answer
is said.
+86
View File
@@ -0,0 +1,86 @@
// Command mesh-cli is the operator's command on every node (novox/hq ADR 0272): `mesh-cli <command line>` asks the
// controller to run one of its command lines, and prints what it said. In interactive zsh it is also `nox`.
//
// It holds no credential and reads no file of the mesh. It asks the node-engine on this machine over a local
// socket; the engine reads which account is asking from the kernel and asks the controller. The controller decides:
// on the control-node, from the operator's own account, the line runs as the controller's terminal; elsewhere it is
// an ordinary call, and a change made at the terminal alone is refused with the reason; from any other account
// nothing runs.
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"git.novox.be/novox/mesh-sdk/go/cli"
)
// socket is where the node-engine answers; a variable so a test can name its own.
var socket = cli.Socket
const usage = `mesh-cli — the controller's command lines, from this node (novox/hq ADR 0272)
mesh-cli <command line> e.g. mesh-cli status, mesh-cli settings show zsh --node <node>
nox <command line> the same, in interactive zsh
Run it as yourself, never under sudo: the node-engine tells the controller which account asks.
On the control-node, from its operator's account, the line runs as the controller's terminal.
Anywhere else it is an ordinary call, and a terminal-only change is refused with the reason.
'mesh-cli help' asks the controller for its own list of command lines.
`
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
stop()
os.Exit(code)
}
func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
if len(args) == 0 || args[0] == "-h" || args[0] == "--help" {
fmt.Fprint(stderr, usage)
return 2
}
// A verb's own process carries the verb it runs for; a verb is never a person, so it is never the terminal.
if verb := os.Getenv("MESH_VERB"); verb != "" {
fmt.Fprintf(stderr, "mesh-cli: this process runs for the verb %q, and a verb is never the operator. "+
"Nothing was asked\n", verb)
return 1
}
a, err := cli.Ask(ctx, socket, args)
if err != nil {
if errors.Is(ctx.Err(), context.Canceled) {
fmt.Fprintln(stderr, "mesh-cli: stopped waiting; the line may still be running on the controller")
return 130
}
fmt.Fprintf(stderr, "mesh-cli: %v\n", err)
return 1
}
_, _ = stdout.Write(a.Stdout)
_, _ = stderr.Write(a.Stderr)
if a.Cut {
fmt.Fprintln(stderr, "mesh-cli: the output was longer than one bus message, and was cut there")
}
if !a.Terminal && a.Why != "" {
fmt.Fprintln(stderr, "mesh-cli: "+a.Why)
}
if a.Unknown != "" {
// Asked, and what came of it not known: never said as nothing having run.
fmt.Fprintln(stderr, "mesh-cli: "+a.Unknown)
if a.Exit == 0 {
return 1
}
}
if a.Refused != "" {
fmt.Fprintln(stderr, "mesh-cli: "+a.Refused)
if a.Exit == 0 {
return 1
}
}
return a.Exit
}
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"bytes"
"context"
"net"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/cli"
)
// engine answers one connection on a socket of the test's own as the node-engine would, and says what it was asked.
func engine(t *testing.T, answer cli.Answer) <-chan []string {
t.Helper()
path := filepath.Join(t.TempDir(), "cli.sock")
l, err := net.Listen("unix", path)
if err != nil {
t.Skipf("no unix socket here: %v", err)
}
t.Cleanup(func() { l.Close() })
before := socket
socket = path
t.Cleanup(func() { socket = before })
asked := make(chan []string, 1)
go func() {
conn, err := l.Accept()
if err != nil {
return
}
defer conn.Close()
req, err := cli.ReadRequest(conn)
if err != nil {
return
}
asked <- req.Line
_ = cli.WriteAnswer(conn, answer)
}()
return asked
}
// The line is asked as given, what the controller printed is printed, and its exit is mesh-cli's.
func TestTheLineIsAskedAndTheAnswerIsPrinted(t *testing.T) {
t.Setenv("MESH_VERB", "")
asked := engine(t, cli.Answer{Stdout: []byte("out\n"), Stderr: []byte("err\n"), Exit: 3, Terminal: true, Why: "the terminal"})
var out, errOut bytes.Buffer
code := run(context.Background(), []string{"settings", "set", "zsh", `{"execute":"withhold"}`}, &out, &errOut)
if line := <-asked; strings.Join(line, "|") != `settings|set|zsh|{"execute":"withhold"}` {
t.Fatalf("asked %q", line)
}
if code != 3 || out.String() != "out\n" || errOut.String() != "err\n" {
t.Fatalf("exit %d, stdout %q, stderr %q", code, out.String(), errOut.String())
}
}
// Not the terminal, refused, or cut: each is said, and a refusal never exits 0.
func TestWhyARefusalAndACutAreSaid(t *testing.T) {
t.Setenv("MESH_VERB", "")
engine(t, cli.Answer{Why: "not the controller's terminal: agents on laptop may run as operator",
Refused: "set at the controller's terminal only", Cut: true})
var out, errOut bytes.Buffer
code := run(context.Background(), []string{"settings", "set", "x", "{}"}, &out, &errOut)
said := errOut.String()
if code == 0 || !strings.Contains(said, "not the controller's terminal") || !strings.Contains(said, "terminal only") ||
!strings.Contains(said, "cut") {
t.Fatalf("exit %d, said %q", code, said)
}
}
// A verb's own process is never the operator: refused before anything is asked.
func TestAVerbsProcessIsRefusedBeforeAsking(t *testing.T) {
t.Setenv("MESH_VERB", "command")
before := socket
socket = filepath.Join(t.TempDir(), "nothing-listens.sock")
t.Cleanup(func() { socket = before })
var out, errOut bytes.Buffer
if code := run(context.Background(), []string{"status"}, &out, &errOut); code != 1 ||
!strings.Contains(errOut.String(), "never the operator") {
t.Fatalf("exit %d, said %q", code, errOut.String())
}
}
// An engine that does not answer is said, with where it was asked.
func TestAnEngineThatDoesNotAnswerIsSaid(t *testing.T) {
t.Setenv("MESH_VERB", "")
before := socket
socket = filepath.Join(t.TempDir(), "nothing-listens.sock")
t.Cleanup(func() { socket = before })
var out, errOut bytes.Buffer
if code := run(context.Background(), []string{"status"}, &out, &errOut); code != 1 ||
!strings.Contains(errOut.String(), "does not answer") {
t.Fatalf("exit %d, said %q", code, errOut.String())
}
}
// An outcome not known is said as such — the line may have run — and never as nothing having run.
func TestAnOutcomeNotKnownIsSaid(t *testing.T) {
t.Setenv("MESH_VERB", "")
engine(t, cli.NotKnown("call-4", "no answer within 6m0s"))
var out, errOut bytes.Buffer
code := run(context.Background(), []string{"push", "laptop"}, &out, &errOut)
if code == 0 || !strings.Contains(errOut.String(), "may have run") || !strings.Contains(errOut.String(), "call-4") {
t.Fatalf("exit %d, said %q", code, errOut.String())
}
}
@@ -0,0 +1,56 @@
package main
import (
"encoding/json"
"os"
"testing"
)
// **The archive places exactly one file, /usr/local/bin/mesh-cli** (review of novox/hq ADR 0272): one archive
// resource, unpacking one artifact into /usr/local/bin, and that artifact a compiled Go bundle — the builder writes
// such a bundle as its binary alone (`go build -o <out>/<binary>`), named mesh-cli — with nothing the runtime would
// load or put beside it. A second file in the bundle, or a second resource writing there, fails here.
func TestTheArchivePlacesExactlyOneFile(t *testing.T) {
raw, err := os.ReadFile("../../module.json")
if err != nil {
t.Fatal(err)
}
var m struct {
Resources []map[string]any `json:"resources"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
if len(m.Resources) != 1 {
t.Fatalf("the module declares %d resources; it places one file", len(m.Resources))
}
r := m.Resources[0]
if r["type"] != "archive" || r["path"] != "/usr/local/bin" {
t.Fatalf("its resource is %v", r)
}
if len(m.Build.Artifacts) != 1 {
t.Fatalf("it builds %d artifacts", len(m.Build.Artifacts))
}
a := m.Build.Artifacts[0]
if a["name"] != r["artifact"] || a["kind"] != "bundle" || a["language"] != "go" || a["binary"] != "mesh-cli" ||
a["from"] != "cmd/mesh-cli" {
t.Fatalf("its artifact is %v, unpacked as %v", a, r["artifact"])
}
for _, extra := range []string{"loads", "env", "context", "files"} {
if _, has := a[extra]; has {
t.Fatalf("its artifact says %q, which would put more than the binary in the bundle or load it", extra)
}
}
entries, err := os.ReadDir(".")
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.IsDir() {
t.Fatalf("cmd/mesh-cli holds a directory %s, which a build could carry into the bundle", e.Name())
}
}
}
+5
View File
@@ -0,0 +1,5 @@
module mesh-cli
go 1.22
require git.novox.be/novox/mesh-sdk/go v0.1.8-0.20261009103748-a5a040c9049b
+2
View File
@@ -0,0 +1,2 @@
git.novox.be/novox/mesh-sdk/go v0.1.8-0.20261009103748-a5a040c9049b h1:HmasScQ02QeFlAFDnmRCOEserbtDJJtutK+acBmGlNs=
git.novox.be/novox/mesh-sdk/go v0.1.8-0.20261009103748-a5a040c9049b/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
+31
View File
@@ -0,0 +1,31 @@
{
"module": "mesh-cli",
"version": "1",
"resources": [
{
"id": "program",
"type": "archive",
"artifact": "program",
"path": "/usr/local/bin"
}
],
"shell": [
{
"for": "zsh",
"slot": "normal",
"code": "# The operator's command (module mesh-cli, novox/hq ADR 0272): nox is mesh-cli, in interactive zsh only.\n# A script, sudo and a document meant to work everywhere say mesh-cli.\nalias nox=mesh-cli\n"
}
],
"build": {
"artifacts": [
{
"name": "program",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/mesh-cli",
"binary": "mesh-cli"
}
]
}
}
@@ -239,6 +239,18 @@ type fakeForge struct {
contains map[string]bool
containsDown bool
containsAsks []string
// open is what OpenPulls answers; openDown a forge that cannot say.
open []OpenPull
openDown bool
}
func (f *fakeForge) OpenPulls() ([]OpenPull, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.openDown {
return nil, errors.New("the forge is away")
}
return append([]OpenPull(nil), f.open...), nil
}
func newFakeForge() *fakeForge {
@@ -41,6 +41,8 @@ type Holder struct {
// askTried is when a check this owner asks was last tried and could not be asked: tried again a minute on.
askTried map[string]time.Time
refusals []string
// unchecked are the open pull requests' heads seen without a merge check (unchecked.go).
unchecked map[string]unchecked
}
// unmatched is a walk no delivery is known for yet: its merge not heard, or merged before this owner held.
@@ -80,6 +82,7 @@ func (h *Holder) init() {
h.dirtyGroup = map[string]bool{}
h.unmatched = map[string]unmatched{}
h.askTried = map[string]time.Time{}
h.unchecked = map[string]unchecked{}
h.started = h.Now()
}
@@ -68,7 +68,7 @@ func run(h *Holder, l *listening) {
go func() {
tick := time.NewTicker(10 * time.Second)
defer tick.Stop()
last := time.Now()
last, looked := time.Now(), time.Time{}
for now := range tick.C {
if now.Sub(last) >= 30*time.Second {
last = now
@@ -76,6 +76,11 @@ func run(h *Holder, l *listening) {
logf("[mesh-delivery] the controller's walks cannot be read: %v", err)
}
}
// Every open pull request, from the forge itself, every five minutes (novox/hq issue 347).
if now.Sub(looked) >= 5*time.Minute {
looked = now
h.SeeOpenPulls()
}
h.Tick()
h.Flush()
}
@@ -65,7 +65,7 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
want = append(want, "seat:"+ControllerSeat+"."+v)
}
want = append(want, "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status",
"gitea.gitea_commit_statuses", "gitea.gitea_contains")
"gitea.gitea_commit_statuses", "gitea.gitea_contains", "gitea.gitea_open_pulls")
if !reflect.DeepEqual(m.Invokes, want) {
t.Fatalf("invokes %v, wanted %v", m.Invokes, want)
}
@@ -78,6 +78,9 @@ type Forge interface {
Statuses(owner, repo string, number int, commit, base string) (*ForgeChecks, error)
// Contains is whether a commit is contained in another — an ancestor of it, or it. Reads only.
Contains(owner, repo, commit, in string) (bool, error)
// OpenPulls is every open pull request, with what its base requires and what its head has (novox/hq issue
// 347). Reads only.
OpenPulls() ([]OpenPull, error)
}
// ForgeChecks is what the forge says of a commit's checks (the gitea module's gitea_commit_statuses).
@@ -339,6 +342,24 @@ func (f toolForge) Statuses(owner, repo string, number int, commit, base string)
return &c, nil
}
func (f toolForge) OpenPulls() ([]OpenPull, error) {
raw, err := f.ask("gitea.gitea_open_pulls", map[string]any{})
if err != nil {
return nil, err
}
answer, output, ok := answerOf(raw)
if !ok {
return nil, fmt.Errorf("the forge refused gitea_open_pulls: %s", lastLine(output))
}
var open struct {
Pulls []OpenPull `json:"pulls"`
}
if err := json.Unmarshal(answer, &open); err != nil || open.Pulls == nil {
return nil, fmt.Errorf("the forge's gitea_open_pulls is not readable: %s", clip(string(answer), 200))
}
return open.Pulls, nil
}
func (f toolForge) Contains(owner, repo, commit, in string) (bool, error) {
raw, err := f.ask("gitea.gitea_contains", map[string]any{"owner": owner, "repo": repo, "commit": commit, "in": in})
if err != nil {
@@ -0,0 +1,112 @@
package main
import (
"fmt"
"slices"
"time"
)
// A pull request the mesh was never asked to check (novox/hq issue 347).
//
// The forge's announcer is the only way the mesh hears of a pull request's head, and on 2026-10-09 it missed one: a
// pull request opened after its push moved nothing the announcer read, and waited unchecked, unable to merge, with
// nothing saying so. This owner asks the forge itself for every open pull request every few minutes, and one whose
// base requires the merge check — mesh/merge-gate or mesh/repo-check — with neither on its head for UncheckedAfter
// since this owner first saw it so is said as a delivery held: a `stalled` line in the state Unannounced, which the
// controller raises as `delivery.<id>.stalled` (D14) like any other delivery past its bound. The delivery domain's own
// word, so no second condition and no second judge: the id is the one its delivery will have once announced.
// Unannounced is a pull request's head the forge never announced: not a state of the table — no delivery exists —
// only what a stalled line says.
const Unannounced State = "unannounced"
// UncheckedAfter is how long a head may go without a merge check before it is said: the announcer passes every half
// minute and the check is asked at once, so ten minutes is a fault, never a queue.
const UncheckedAfter = 10 * time.Minute
// mergeChecks are the statuses that are the mesh's merge check (novox/hq ADR 0237): a base requiring either is
// one the mesh is meant to check.
var mergeChecks = []string{"mesh/merge-gate", "mesh/repo-check"}
// OpenPull is an open pull request as the forge says it (the gitea module's gitea_open_pulls): its head, its base,
// the contexts the base's protection requires, and the contexts its head has a status of, in any state.
type OpenPull struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
Base string `json:"base"`
HeadSHA string `json:"head_sha"`
HTMLURL string `json:"html_url,omitempty"`
Required []string `json:"required"`
Statuses []string `json:"statuses"`
}
// unchecked is a head seen without a merge check, and when this owner first saw it so — its own time, since the
// forge's update time moves on every comment.
type unchecked struct {
pull OpenPull
first time.Time
}
// wantsACheck is whether the base requires the mesh's merge check and the head has none of it.
func (p OpenPull) wantsACheck() bool {
required := slices.ContainsFunc(mergeChecks, func(c string) bool { return slices.Contains(p.Required, c) })
checked := slices.ContainsFunc(mergeChecks, func(c string) bool { return slices.Contains(p.Statuses, c) })
return required && !checked && p.HeadSHA != ""
}
// SeeOpenPulls asks the forge for every open pull request and keeps the heads that want a check and have none.
// A forge that cannot be asked changes nothing: what was seen stands, and nothing is guessed.
func (h *Holder) SeeOpenPulls() {
open, err := h.Forge.OpenPulls()
if err != nil {
h.Logf("[mesh-delivery] the forge's open pull requests cannot be read: %v", err)
return
}
h.mu.Lock()
defer h.mu.Unlock()
now := h.Now()
seen := map[string]unchecked{}
for _, p := range open {
if !p.wantsACheck() {
continue
}
id := IDOf(p.Owner+"/"+p.Repo, p.HeadSHA)
if h.deliveries[id] != nil {
continue // announced: a delivery with its own bound
}
first := now
if was, ok := h.unchecked[id]; ok {
first = was.first
} else {
h.Logf("[mesh-delivery] %s/%s#%d's head %s has no merge check; said if it has none in %s", p.Owner, p.Repo,
p.Number, short(p.HeadSHA), UncheckedAfter)
}
seen[id] = unchecked{pull: p, first: first}
}
h.unchecked = seen
}
// uncheckedLines are the heads unchecked past UncheckedAfter, as stalled lines; under the lock.
func (h *Holder) uncheckedLines(now time.Time) []StalledLine {
var out []StalledLine
for id, u := range h.unchecked {
if h.deliveries[id] != nil || now.Sub(u.first) < UncheckedAfter {
continue
}
out = append(out, StalledLine{ID: id, State: Unannounced, For: now.Sub(u.first).Round(time.Second).String(),
Bound: UncheckedAfter.String(),
H2: "none: the forge never announced it, so there is no delivery to close — the operator's",
Says: fmt.Sprintf("%s/%s#%d is open on %s, which requires the merge check, and its head has had no merge "+
"check: the mesh was never asked to check it. A new commit on its branch announces it",
u.pull.Owner, u.pull.Repo, u.pull.Number, u.pull.Base)})
}
return out
}
func short(sha string) string {
if len(sha) > 12 {
return sha[:12]
}
return sha
}
@@ -0,0 +1,77 @@
package main
import (
"strings"
"testing"
"time"
)
// **A pull request the mesh was never asked to check is a delivery held, and said** (novox/hq issue 347): one open
// on a base that requires the merge check — mesh/merge-gate or mesh/repo-check, as hq requires only the second —
// whose head has had neither for ten minutes since this owner first saw it so, is a stalled line: the controller
// raises it as `delivery.<id>.stalled` (D14), the delivery domain's own word for a delivery held past its bound.
func TestAPullRequestNobodyCheckedIsAStalledDelivery(t *testing.T) {
w := newWorld(t)
head := "bfe82315f42c8f4509d0598c32569a202d5eada6"
w.forge.open = []OpenPull{
{Owner: "novox", Repo: "hq", Number: 243, Base: "main", HeadSHA: head, Required: []string{"mesh/repo-check"}},
{Owner: "novox", Repo: "sdk", Number: 14, Base: "main", HeadSHA: "aaaa", Required: []string{"mesh/merge-gate", "mesh/repo-check"},
Statuses: []string{"mesh/merge-gate"}},
{Owner: "novox", Repo: "free", Number: 1, Base: "main", HeadSHA: "bbbb", Required: nil},
}
w.h.SeeOpenPulls()
if lines := w.h.Stalled(); len(lines) != 0 {
t.Fatalf("a head just seen is stalled already: %+v", lines)
}
w.later(6 * time.Minute)
w.h.SeeOpenPulls() // seen again: its own first-seen time stands, whatever the forge's update time says
w.later(5 * time.Minute)
lines := w.h.Stalled()
if len(lines) != 1 || lines[0].ID != IDOf("novox/hq", head) || lines[0].State != Unannounced ||
!strings.Contains(lines[0].Says, "no merge check") || !strings.HasPrefix(lines[0].H2, "none") {
t.Fatalf("an unchecked pull request on a base requiring only mesh/repo-check reads %+v", lines)
}
if lines[0].For != "11m0s" {
t.Fatalf("its time is not counted from when this owner first saw it: %s", lines[0].For)
}
// Announced at last: a delivery of its own, with its own bound — no longer this line.
w.h.PullUpdated(pr("novox/hq", 243, head, "decision/x"))
w.h.SeeOpenPulls()
for _, l := range w.h.Stalled() {
if l.State == Unannounced {
t.Fatalf("an announced pull request is still said unannounced: %+v", l)
}
}
}
// One that gets a check, or closes, is dropped; one the forge cannot be asked about is not guessed.
func TestAnUncheckedPullRequestThatGetsACheckOrClosesIsDropped(t *testing.T) {
w := newWorld(t)
w.forge.open = []OpenPull{{Owner: "novox", Repo: "hq", Number: 1, Base: "main", HeadSHA: "cccc",
Required: []string{"mesh/merge-gate"}}}
w.h.SeeOpenPulls()
w.later(11 * time.Minute)
if len(w.h.Stalled()) != 1 {
t.Fatal("not said")
}
w.forge.open[0].Statuses = []string{"mesh/merge-gate"}
w.h.SeeOpenPulls()
if len(w.h.Stalled()) != 0 {
t.Fatal("a pull request with a check is still said")
}
w.forge.open[0].Statuses = nil
w.h.SeeOpenPulls()
w.later(11 * time.Minute)
w.forge.openDown = true
w.h.SeeOpenPulls() // the forge away: what was seen stands, nothing new is guessed
if len(w.h.Stalled()) != 1 {
t.Fatal("a forge that could not be asked dropped or invented a line")
}
w.forge.openDown = false
w.forge.open = nil
w.h.SeeOpenPulls()
if len(w.h.Stalled()) != 0 {
t.Fatal("a closed pull request is still said")
}
}
@@ -189,6 +189,7 @@ func (h *Holder) Stalled() []StalledLine {
out = append(out, StalledLine{ID: d.ID, State: d.State, For: now.Sub(boundSince(d)).Round(time.Second).String(),
Bound: b.For.String(), H2: h2, Says: b.Says})
}
out = append(out, h.uncheckedLines(now)...)
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
+2 -1
View File
@@ -44,7 +44,8 @@
"gitea.gitea_delivery_view",
"gitea.gitea_commit_status",
"gitea.gitea_commit_statuses",
"gitea.gitea_contains"
"gitea.gitea_contains",
"gitea.gitea_open_pulls"
],
"state": [
"deliveries",
+1 -1
View File
@@ -107,7 +107,7 @@ into the container.
| `machine` | `host.docker.internal` | how the predecessor's proxy reaches this machine |
```
mesh-controller settings set route-adapter settings.json --node <node>
mesh-cli settings set route-adapter "$(cat settings.json)" --node <node>
```
**One thing does not follow the setting yet, and it fails loudly rather than quietly.** The