@staix/agent-hub 0.44.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/README.md +3 -8
- package/docs/agent-notes/adapters.md +2 -2
- package/docs/agent-notes/daemon.md +1 -1
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +1 -1
- package/docs/agent-notes/tasks.md +3 -1
- package/docs/agent-notes/tests.md +3 -2
- package/docs/design/adapters.md +4 -2
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/roadmap.md +75 -2
- package/docs/design/supervision.md +21 -1
- package/docs/design/task-board.md +30 -2
- package/docs/dogfood.md +13 -4
- package/docs/events.md +5 -1
- package/docs/influences.md +7 -0
- package/docs/memory.md +4 -4
- package/docs/operations.md +51 -18
- package/docs/quickstart.md +8 -2
- package/docs/research.md +16 -0
- package/docs/roadmap.json +4 -0
- package/docs/roadmap.md +9 -0
- package/docs/sdlc.md +15 -3
- package/docs/security.md +3 -3
- package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
- package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
- package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
- package/docs/verification/2026-11-21-0.45.0.md +69 -0
- package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
- package/docs/verified.json +32 -26
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +472 -229
- package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
- package/plugins/agent-hub/server.js +513 -258
- package/scripts/check-docs.mjs +9 -1
- package/src/adapters/acp.ts +11 -1
- package/src/adapters/compat.ts +3 -3
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-context.ts +10 -0
- package/src/adapters/jcode.ts +10 -0
- package/src/adapters/local-worker.ts +3 -2
- package/src/adapters/pi.ts +15 -4
- package/src/cli/console-state.ts +3 -1
- package/src/cli/help.ts +3 -1
- package/src/cli/identity.ts +2 -1
- package/src/cli/main.ts +11 -5
- package/src/cli/recovery-package.ts +16 -3
- package/src/cli/roadmap-write.ts +59 -0
- package/src/cli/roadmap.ts +81 -4
- package/src/cli/sdlc-output.ts +4 -0
- package/src/cli/upgrade-runtime.ts +10 -6
- package/src/hub/agent-mem-range.ts +43 -0
- package/src/hub/board.ts +102 -1
- package/src/hub/check-runner.ts +25 -1
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/context-window.ts +1 -1
- package/src/hub/cost-governance.ts +11 -7
- package/src/hub/daemon.ts +253 -30
- package/src/hub/dogfood-read.ts +4 -2
- package/src/hub/edit-guard.ts +100 -0
- package/src/hub/events.ts +79 -8
- package/src/hub/facts.ts +57 -4
- package/src/hub/hub-tools.ts +2 -0
- package/src/hub/lifecycle.ts +6 -1
- package/src/hub/log-rotation.ts +130 -0
- package/src/hub/memory-profile.ts +137 -21
- package/src/hub/no-writes.ts +1 -0
- package/src/hub/operational-authority.ts +3 -2
- package/src/hub/operational-settings.ts +2 -2
- package/src/hub/recovery-store.ts +49 -21
- package/src/hub/research-experiments.ts +132 -0
- package/src/hub/research-quality.ts +8 -2
- package/src/hub/research-record.ts +35 -0
- package/src/hub/research.ts +128 -28
- package/src/hub/roadmap-check.ts +65 -0
- package/src/hub/roadmap-decompose.ts +80 -0
- package/src/hub/roadmap-export.ts +27 -0
- package/src/hub/roadmap-sync.ts +97 -0
- package/src/hub/roadmap.ts +40 -0
- package/src/hub/sdlc-branch-ci.ts +128 -0
- package/src/hub/sdlc-merge.ts +6 -3
- package/src/hub/sdlc-metrics.ts +19 -5
- package/src/hub/sdlc.ts +73 -5
- package/src/hub/settings.ts +1 -0
- package/src/hub/snapshots.ts +13 -1
- package/src/hub/startup-event-seeds.ts +21 -15
- package/src/hub/startup-timing.ts +3 -1
- package/src/hub/supervision-proposals.ts +10 -2
- package/src/hub/supervision-rules.ts +26 -3
- package/src/hub/supervision.ts +7 -0
- package/src/hub/task-pr.ts +47 -0
- package/src/hub/task-worktree.ts +18 -11
- package/src/hub/tasks.ts +502 -34
- package/src/hub/usage-rollup.ts +35 -20
- package/src/local/tools.ts +13 -1
- package/src/memory/client.ts +3 -2
- package/src/pi/extension.ts +15 -3
- package/src/pi/tool-receipts.ts +26 -0
package/src/cli/roadmap.ts
CHANGED
|
@@ -10,33 +10,60 @@ export const ROADMAP_FORMS = {
|
|
|
10
10
|
order: "order <id> <n>", state: "state <id> <proposed|planned|active|done|dropped>",
|
|
11
11
|
unplaced: "unplaced [--repo <owner/name>] [--json]",
|
|
12
12
|
triage: "triage [--repo <owner/name>] [--list] [--json]",
|
|
13
|
+
decompose: "decompose <id> [--accept <part>] [--json]",
|
|
13
14
|
accept: "accept <suggestion>", reject: "reject <suggestion>",
|
|
14
15
|
importGithub: "import-github [--repo <owner/name>] [--apply] [--json]",
|
|
16
|
+
check: "check [--json]", sync: "sync [--apply --confirm <fingerprint>] [--json]",
|
|
17
|
+
export: "export [--write | --issue <n> [--apply --confirm <fingerprint>]] [--json]",
|
|
15
18
|
} as const;
|
|
16
19
|
export const ROADMAP_USAGE = `usage: ${Object.values(ROADMAP_FORMS).map(form => `ahub roadmap ${form}`).join(" | ")}`;
|
|
17
20
|
export interface RoadmapArgs {
|
|
18
|
-
op: "hub_roadmap_list" | "hub_roadmap_show" | "hub_roadmap_edit" | "hub_roadmap_unplaced" | "hub_roadmap_triage" | "roadmap_import_github";
|
|
21
|
+
op: "hub_roadmap_list" | "hub_roadmap_show" | "hub_roadmap_check" | "hub_roadmap_edit" | "hub_roadmap_unplaced" | "hub_roadmap_triage" | "hub_roadmap_decompose" | "roadmap_import_github" | "roadmap_sync" | "roadmap_sync_apply" | "roadmap_export" | "roadmap_export_apply";
|
|
19
22
|
args: Record<string, unknown>;
|
|
20
23
|
json: boolean;
|
|
24
|
+
write?: boolean;
|
|
21
25
|
}
|
|
22
26
|
/** R3 commands: their flags are not milestone fields, so they are parsed apart from new/edit. */
|
|
23
|
-
const R3_COMMANDS = ["unplaced", "triage", "accept", "reject", "import-github"];
|
|
24
|
-
const R3_JSON = ["unplaced", "triage", "import-github"];
|
|
27
|
+
const R3_COMMANDS = ["unplaced", "triage", "decompose", "accept", "reject", "import-github"];
|
|
28
|
+
const R3_JSON = ["unplaced", "triage", "decompose", "import-github"];
|
|
25
29
|
const fieldFlags = ["title", "outcome", "horizon", "order", "target", "parent"];
|
|
26
30
|
const usage = (message: string): never => { throw new Error(`${message}; ${ROADMAP_USAGE}`); };
|
|
31
|
+
|
|
32
|
+
function parseR4(command: string, rest: readonly string[], jsonSeen: boolean): RoadmapArgs {
|
|
33
|
+
let json = jsonSeen, apply = false, write = false, issue: number | undefined, confirm: string | undefined;
|
|
34
|
+
for (let i = 0; i < rest.length; i++) {
|
|
35
|
+
const word = rest[i]!;
|
|
36
|
+
if (word === "--json" && !json) json = true;
|
|
37
|
+
else if (word === "--apply" && !apply && command !== "check") apply = true;
|
|
38
|
+
else if (word === "--write" && !write && command === "export") write = true;
|
|
39
|
+
else if (word === "--issue" && issue === undefined && command === "export") issue = integer(rest[++i]);
|
|
40
|
+
else if (word === "--confirm" && confirm === undefined && command !== "check") { confirm = rest[++i]; if (!confirm || !/^[a-f0-9]{64}$/.test(confirm)) return usage("roadmap confirmation needs a full fingerprint"); }
|
|
41
|
+
else return usage("unknown or duplicate roadmap option");
|
|
42
|
+
}
|
|
43
|
+
if (confirm && !apply || apply && !confirm || write && (apply || issue !== undefined) || command === "export" && apply && issue === undefined) return usage("roadmap apply needs its preview fingerprint and export --write is separate from --issue");
|
|
44
|
+
if (command === "check") return { op: "hub_roadmap_check", args: {}, json };
|
|
45
|
+
if (command === "sync") return { op: apply ? "roadmap_sync_apply" : "roadmap_sync", args: apply ? { apply, confirm } : {}, json };
|
|
46
|
+
return { op: apply ? "roadmap_export_apply" : "roadmap_export", args: { ...(issue === undefined ? {} : { issue }), ...(apply ? { apply, confirm } : {}) }, json, ...(write ? { write } : {}) };
|
|
47
|
+
}
|
|
27
48
|
function integer(value: string | undefined, zero = false): number {
|
|
28
49
|
if (value === undefined || !/^(0|[1-9][0-9]*)$/.test(value)) return usage("roadmap needs a whole-number operand");
|
|
29
50
|
return zero ? milestoneRevision(Number(value)) : milestoneId(Number(value));
|
|
30
51
|
}
|
|
31
52
|
|
|
32
53
|
function parseR3(command: string, rest: readonly string[], jsonSeen: boolean): RoadmapArgs {
|
|
33
|
-
let json = jsonSeen, list = false, apply = false, repo: string | undefined;
|
|
54
|
+
let json = jsonSeen, list = false, apply = false, repo: string | undefined, accept: number | undefined;
|
|
34
55
|
const operands: string[] = [];
|
|
35
56
|
for (let at = 0; at < rest.length; at++) {
|
|
36
57
|
const word = rest[at]!;
|
|
37
58
|
if (word === "--json") { if (json) return usage("duplicate roadmap --json flag"); json = true; continue; }
|
|
38
59
|
if (word === "--list" && command === "triage") { if (list) return usage("duplicate roadmap --list flag"); list = true; continue; }
|
|
39
60
|
if (word === "--apply" && command === "import-github") { if (apply) return usage("duplicate roadmap --apply flag"); apply = true; continue; }
|
|
61
|
+
if ((word === "--accept" || word.startsWith("--accept=")) && command === "decompose") {
|
|
62
|
+
if (accept !== undefined) return usage("duplicate roadmap --accept option");
|
|
63
|
+
const value = word === "--accept" ? rest[++at] : word.slice("--accept=".length);
|
|
64
|
+
accept = integer(value);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
40
67
|
if ((word === "--repo" || word.startsWith("--repo=")) && ["unplaced", "triage", "import-github"].includes(command)) {
|
|
41
68
|
if (repo !== undefined) return usage("duplicate roadmap --repo option");
|
|
42
69
|
const value = word === "--repo" ? rest[++at] : word.slice("--repo=".length);
|
|
@@ -52,6 +79,10 @@ function parseR3(command: string, rest: readonly string[], jsonSeen: boolean): R
|
|
|
52
79
|
if (operands.length !== 1) return usage(`roadmap ${command} needs one suggestion id`);
|
|
53
80
|
return { op: "hub_roadmap_edit", args: { op: command, suggestion: integer(operands[0]) }, json };
|
|
54
81
|
}
|
|
82
|
+
if (command === "decompose") {
|
|
83
|
+
if (operands.length !== 1) return usage("roadmap decompose needs one milestone id");
|
|
84
|
+
return { op: "hub_roadmap_decompose", args: { id: integer(operands[0]), ...(accept === undefined ? {} : { accept }) }, json };
|
|
85
|
+
}
|
|
55
86
|
if (operands.length) return usage(`roadmap ${command} takes no operands`);
|
|
56
87
|
const base = repo === undefined ? {} : { repo };
|
|
57
88
|
if (command === "unplaced") return { op: "hub_roadmap_unplaced", args: base, json };
|
|
@@ -65,6 +96,7 @@ export function parseRoadmapArgs(argv: readonly string[]): RoadmapArgs {
|
|
|
65
96
|
if (argv[index] === "--json") { json = true; index++; }
|
|
66
97
|
const command = argv[index] ?? "list";
|
|
67
98
|
if (argv[index] !== undefined) index++;
|
|
99
|
+
if (["check", "sync", "export"].includes(command)) return parseR4(command, argv.slice(index), json);
|
|
68
100
|
if (!["list", "show", "new", "edit", "link", "unlink", "order", "state", ...R3_COMMANDS].includes(command)) return usage("unknown roadmap command");
|
|
69
101
|
if (R3_COMMANDS.includes(command)) return parseR3(command, argv.slice(index), json);
|
|
70
102
|
const operands: string[] = [], flags = new Map<string, string>();
|
|
@@ -165,6 +197,28 @@ export function renderRoadmap(input: unknown, width = 80): string {
|
|
|
165
197
|
}
|
|
166
198
|
};
|
|
167
199
|
const names = (rows: unknown[], one: (value: Row) => string) => { for (const value of rows) add(one(row(value))); };
|
|
200
|
+
if (Array.isArray(view.findings) && Array.isArray(view.unknown)) {
|
|
201
|
+
add(`Roadmap drift (${view.findings.length} findings)`);
|
|
202
|
+
names(view.findings, finding => ` Rule ${count(finding.rule)}, milestone ${finding.milestone === null ? "none" : count(finding.milestone)}: ${text(finding.cause)}; ${list(finding.items).map(text).join(", ")}. Next: ${text(finding.remedy)}`);
|
|
203
|
+
if (view.unknown.length) add(`Unknown evidence for rules: ${view.unknown.map(count).join(", ")}`);
|
|
204
|
+
if (view.truncated === true) add("More findings exist; narrow the roadmap before relying on this list.");
|
|
205
|
+
return lines.join("\n");
|
|
206
|
+
}
|
|
207
|
+
if (Array.isArray(view.calls) && typeof view.fingerprint === "string") {
|
|
208
|
+
add(`GitHub mirror: ${view.applied ? "applied" : "dry run"}`);
|
|
209
|
+
for (const call of view.calls) if (Array.isArray(call)) add(` gh ${call.map(value => `'${String(value).replaceAll("'", "'\\''")}'`).join(" ")}`);
|
|
210
|
+
for (const binding of list(view.bindings)) { const b = row(binding); add(` Bind local milestone ${count(b.milestone)} to GitHub milestone ${count(b.number)}`); }
|
|
211
|
+
if (!view.applied) add(`Apply this exact preview: ahub roadmap sync --apply --confirm ${text(view.fingerprint)}`);
|
|
212
|
+
return lines.join("\n");
|
|
213
|
+
}
|
|
214
|
+
if (typeof view.markdown === "string" && typeof view.fingerprint === "string") {
|
|
215
|
+
add(view.markdown);
|
|
216
|
+
const endpoint = Array.isArray(view.call) ? view.call[1] : undefined;
|
|
217
|
+
const issue = typeof endpoint === "string" ? /\/issues\/([1-9][0-9]*)$/.exec(endpoint)?.[1] : undefined;
|
|
218
|
+
if (issue && !view.applied) add(`Apply this exact issue preview: ahub roadmap export --issue ${issue} --apply --confirm ${text(view.fingerprint)}`);
|
|
219
|
+
if (view.applied) add("GitHub issue update confirmed.");
|
|
220
|
+
return lines.join("\n");
|
|
221
|
+
}
|
|
168
222
|
if (Array.isArray(view.issues) && Array.isArray(view.tasks) && Array.isArray(view.specs) && view.privateTasks !== undefined) {
|
|
169
223
|
add(`Unplaced work${view.repo ? ` (${text(view.repo)})` : ""}`);
|
|
170
224
|
if (view.partial === true) add("Partial: the GitHub read stopped early or a list was cut, so these lists are a lower bound.");
|
|
@@ -178,6 +232,29 @@ export function renderRoadmap(input: unknown, width = 80): string {
|
|
|
178
232
|
add(`Private tasks counted, not listed: ${count(view.privateTasks)}`);
|
|
179
233
|
return lines.join("\n");
|
|
180
234
|
}
|
|
235
|
+
if (typeof view.part === "number" && typeof view.milestone === "number" && view.task !== undefined && view.task !== null) {
|
|
236
|
+
const task = row(view.task), draft = count(task.id);
|
|
237
|
+
add(`Milestone ${count(view.milestone)} part ${count(view.part)}: ${view.created === true ? "held as intake draft" : "already held as intake draft"} ${draft}`);
|
|
238
|
+
add(` ${text(task.title)} (${text(task.state)})`);
|
|
239
|
+
add(` ${view.intake === "spec" ? "It needs its own spec issue before implementation." : "It goes straight to a task."}`);
|
|
240
|
+
add(` Nothing offers it until the hold is released: ahub intake approve ${draft}`);
|
|
241
|
+
return lines.join("\n");
|
|
242
|
+
}
|
|
243
|
+
if (Array.isArray(view.parts) && typeof view.milestone === "number") {
|
|
244
|
+
add(`Milestone ${count(view.milestone)} decomposition`);
|
|
245
|
+
if (view.unavailable) add(`Decompose unavailable: ${text(view.unavailable)}`);
|
|
246
|
+
const saved = row(view.saved);
|
|
247
|
+
if (view.saved !== null && view.saved !== undefined) add(`${count(view.parts.length)} part${view.parts.length === 1 ? "" : "s"} saved as pending model answer ${count(saved.id)}; nothing is intaken, linked or published.`);
|
|
248
|
+
if (Number(view.dropped) > 0) add(`Dropped ${count(view.dropped)} model part${Number(view.dropped) === 1 ? "" : "s"} that cited nothing it was shown or did not fit the split schema.`);
|
|
249
|
+
for (const value of list(view.parts)) {
|
|
250
|
+
const part = row(value);
|
|
251
|
+
add(` ${text(part.title)} -> ${part.intake === "spec" ? "needs its own spec issue" : "goes straight to a task"} (${text(part.class)})`);
|
|
252
|
+
add(` cites: ${list(part.cites).map(text).join(", ")}`);
|
|
253
|
+
add(` ${text(part.detail)}`);
|
|
254
|
+
}
|
|
255
|
+
if (!list(view.parts).length && !view.unavailable) add("The model proposed no part that cited an id it was shown.");
|
|
256
|
+
return lines.join("\n");
|
|
257
|
+
}
|
|
181
258
|
if (Array.isArray(view.suggestions)) {
|
|
182
259
|
add(`Triage suggestions (${view.suggestions.length})`);
|
|
183
260
|
if (view.unavailable) add(`Triage unavailable: ${text(view.unavailable)}`);
|
package/src/cli/sdlc-output.ts
CHANGED
|
@@ -269,6 +269,7 @@ const SUMMARY_ROWS: [string, string, boolean][] = [
|
|
|
269
269
|
["acceptance_to_plan_ms", "acceptance to plan", true], ["accepted_to_plan_ms", "task acceptance to plan", true], ["acceptance_to_first_review_ms", "acceptance to first review", true], ["acceptance_to_merge_ms", "acceptance to merge", true],
|
|
270
270
|
["rework_rounds", "rework rounds", false], ["same_head_ci_reruns", "same-head CI reruns", false], ["stale_head_re_reviews", "stale-head re-reviews", false],
|
|
271
271
|
["review_rounds_at_merge", "review rounds at merge", false], ["ci_runs_at_merge", "CI runs at merge", false], ["github_reviews_at_merge", "GitHub reviews at merge", false],
|
|
272
|
+
["full_gate_runs", "full gate runs", false], ["successful_gate_runs", "successful gate runs", false], ["failed_gate_runs", "failed gate runs", false], ["cancelled_gate_runs", "cancelled gate runs", false], ["other_gate_runs", "other gate runs", false], ["macos_shard_runs", "macOS shard runs", false],
|
|
272
273
|
];
|
|
273
274
|
const BAND_TONE: Record<string, Tone> = { ok: "success", log: "muted", diagnose: "attention", propose: "failure" };
|
|
274
275
|
/** `ahub sdlc metrics [--since ...]`: times and counts from board history, the two approval rates, stalls and band tiers. */
|
|
@@ -310,6 +311,9 @@ export function renderSdlcCosts(result: unknown, columns?: number, _now = Date.n
|
|
|
310
311
|
out.push(...(out.length > 1 ? [blank] : []), ...wrap(repo, room(columns), 2).map((line): Line => [s(line, "info")]), ...grid(["PR", "ROUNDS", "CI", "RERUNS", "FULL", "DELTA", "REVIEW", "UNK", "OK"], rows.filter(row => String(row.repo) === repo).map(row => [
|
|
311
312
|
s(`#${row.pr}`, "issueRef"), s(count(row.reviewRounds)), s(count(row.ciRuns)), s(count(row.ciReruns)), s(count(row.fullReReviews)), s(count(row.deltaReviews)), s(span(row.reviewMs)),
|
|
312
313
|
s(count(row.unknownReviewScopes), row.unknownReviewScopes ? "attention" : "muted"), s(row.complete ? "yes" : "no", row.complete ? "success" : "attention")]), columns));
|
|
314
|
+
for (const row of rows.filter(row => String(row.repo) === repo && row.fullGateRuns !== undefined)) {
|
|
315
|
+
out.push(...para(`#${row.pr}: full gates ${count(row.fullGateRuns)} (success ${count(row.successfulGateRuns)}, failed ${count(row.failedGateRuns)}, cancelled ${count(row.cancelledGateRuns)}, other ${count(row.otherGateRuns)}); macOS shards ${count(row.macosShardRuns)}`, columns));
|
|
316
|
+
}
|
|
313
317
|
}
|
|
314
318
|
if (c?.truncated) out.push(blank, ...para("truncated: more PRs than one read covers, or a read was incomplete", columns, "attention"));
|
|
315
319
|
if (c?.privateTasks === "withheld") out.push(...para("private tasks are withheld", columns, "muted"));
|
|
@@ -485,7 +485,8 @@ export function preserveSource(plan: UpgradePlan, home = hubHome()): string {
|
|
|
485
485
|
|
|
486
486
|
const unboundRecoveryInspection = inspectRecovery;
|
|
487
487
|
|
|
488
|
-
|
|
488
|
+
/** `clock.waitSliceMs` (#1578) is forwarded to the attachment wait as its poll slice, so a test can poll coarser; production passes nothing and keeps 1 s. */
|
|
489
|
+
export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?: string, clock?: Pick<RecoveryDriver, "now" | "sleep"> & { waitSliceMs?: number }, conductorPeer?: string): RecoveryDriver {
|
|
489
490
|
let authorizedOperation: RecoveryOperation | undefined;
|
|
490
491
|
const recoveryCurrent = async () => { if (conductorPeer) { if (!authorizedOperation) throw new FinalRefusal("conductor recovery authority unavailable"); await authorizeConductorOperation(authorizedOperation, conductorPeer); } };
|
|
491
492
|
const inspectRecovery = (project: Project, features?: readonly string[], purpose?: "cleanup") => unboundRecoveryInspection(project, features, purpose, conductorPeer);
|
|
@@ -640,8 +641,11 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
|
|
|
640
641
|
if (result.manualRequired) throw new Error(`${peer}: closing terminal ${retired.handle} of the stopped target's session was not verified; manual-required`);
|
|
641
642
|
progress.terminals[key] = true; save();
|
|
642
643
|
};
|
|
643
|
-
/** #414: an idle terminal is not an authenticated peer. Keep its receipt while waiting, including on resume.
|
|
644
|
-
|
|
644
|
+
/** #414: an idle terminal is not an authenticated peer. Keep its receipt while waiting, including on resume.
|
|
645
|
+
* #1578: `waitSliceMs` is the poll slice, 1 s in production. It is a parameter with a default, not the enclosing `clock`, because
|
|
646
|
+
* `test/upgrade-timing-failure.test.ts` runs this closure's own source in a sandbox that provides only named ports. Only a test
|
|
647
|
+
* passes a larger slice, so a 600 s deadline costs fewer polls; the last slice is still clamped to the remaining time. */
|
|
648
|
+
const awaitAttachment = async (planned: PlannedProject, progress: ProjectProgress, op: RecoveryOperation, waiting: Extract<RestoreReceipt, { state: "waiting" }>, save: () => void, expectedSession: string | null = waiting.binding.sessionId, waitSliceMs = 1000): Promise<string> => {
|
|
645
649
|
const saveTiming = () => {
|
|
646
650
|
try { save(); }
|
|
647
651
|
catch { console.warn("Recovery timing observation could not be saved; recovery continues"); }
|
|
@@ -686,7 +690,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
|
|
|
686
690
|
else { launchState = "older-instance"; olderHandle = evidence.handle; }
|
|
687
691
|
} else if (evidence.state === "live" && evidence.session) {
|
|
688
692
|
if (now() >= deadline) break;
|
|
689
|
-
await sleep(Math.min(
|
|
693
|
+
await sleep(Math.min(waitSliceMs, deadline - now()));
|
|
690
694
|
continue;
|
|
691
695
|
}
|
|
692
696
|
}
|
|
@@ -704,7 +708,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
|
|
|
704
708
|
throw nativeFailure(planned, binding.peer, "launcher_unverified", `${binding.peer}: the chosen restoration launcher's identity cannot be verified (${launchState}); saved terminal retained; no terminal was created`, { handle: binding.handle, launcherState: launchState });
|
|
705
709
|
}
|
|
706
710
|
if (now() >= deadline) break;
|
|
707
|
-
await sleep(Math.min(
|
|
711
|
+
await sleep(Math.min(waitSliceMs, deadline - now()));
|
|
708
712
|
}
|
|
709
713
|
const terminal: NonNullable<ProjectProgress["attachmentTimeouts"]>[string]["terminal"] = { handle: binding.handle, incarnationId: binding.incarnationId, state: "unknown" };
|
|
710
714
|
try {
|
|
@@ -973,7 +977,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
|
|
|
973
977
|
function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }> & { origin: "pending" }, expected: string | null): Promise<string>;
|
|
974
978
|
function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }>, expected: string | null): Promise<string | undefined>;
|
|
975
979
|
async function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }>, expected: string | null): Promise<string | undefined> {
|
|
976
|
-
try { return await awaitAttachment(planned, progress, op, waiting, save, expected); }
|
|
980
|
+
try { return await awaitAttachment(planned, progress, op, waiting, save, expected, clock?.waitSliceMs); }
|
|
977
981
|
catch (error) {
|
|
978
982
|
if (!(error instanceof AttachmentLauncherGone)) throw error;
|
|
979
983
|
progress.terminals[key] = error.transition.next; save();
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import packageJson from "../../package.json";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* #1611: the first-party memory core is declared as `>=X.Y.Z <M.0.0` (X.Y.Z at or above 0.33.0, M the next major), so a new minor
|
|
5
|
+
* reaches users without a hub release; the host API range below, not the version number, decides whether it is compatible.
|
|
6
|
+
* Legacy `~X.Y.Z` (#1605) declarations still verify in an older recovery package.
|
|
7
|
+
*/
|
|
8
|
+
export const AGENT_MEM_RANGE: string = packageJson.dependencies["@staix/agent-mem"];
|
|
9
|
+
/** The agent-mem host API versions this hub supports, inclusive: [min, max]. A new major host API is a reviewed hub change. */
|
|
10
|
+
export const AGENT_MEM_HOST_API_RANGE: readonly [number, number] = [1, 1];
|
|
11
|
+
/**
|
|
12
|
+
* #1611: the declared form `>=X.Y.Z <M.0.0` with X.Y.Z at or above 0.33.0 and M the next major.
|
|
13
|
+
* ponytail: a copy of scripts/lib/agent-mem-range.mjs, because a preserved source holds no scripts/ directory (the import failed in recovery); test/npm-pin.test.ts pins both to the same answers. Upgrade path: one shared file under src/ that the scripts import.
|
|
14
|
+
*/
|
|
15
|
+
export function isAgentMemFloorRange(value: unknown): boolean {
|
|
16
|
+
const match = /^>=(\d+)\.(\d+)\.(\d+) <(\d+)\.0\.0$/.exec(typeof value === "string" ? value : "");
|
|
17
|
+
if (!match) return false;
|
|
18
|
+
const major = Number(match[1]), minor = Number(match[2]);
|
|
19
|
+
return Number(match[4]) === major + 1 && (major > 0 || minor >= 33);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The host API constants a staged package's src/memory/platform.ts exports, as numbers (undefined when absent). */
|
|
23
|
+
export function readHostApiConstants(source: string): { min: number | undefined; version: number | undefined } {
|
|
24
|
+
const read = (name: string): number | undefined => { const text = new RegExp(`export const ${name} = (\\d+)`).exec(source)?.[1]; return text === undefined ? undefined : Number(text); };
|
|
25
|
+
return { min: read("HOST_API_MIN"), version: read("HOST_API_VERSION") };
|
|
26
|
+
}
|
|
27
|
+
const PATCH_RANGE = /^~\d+\.\d+\.\d+$/;
|
|
28
|
+
const PLAIN_RELEASE = /^\d+\.\d+\.\d+$/;
|
|
29
|
+
|
|
30
|
+
/** Whether `version` is a plain release (no prerelease or build suffix) that satisfies the declared range (floor form, or legacy patch form). */
|
|
31
|
+
export function agentMemVersionInRange(version: unknown, range: string = AGENT_MEM_RANGE): boolean {
|
|
32
|
+
if (typeof version !== "string" || !PLAIN_RELEASE.test(version)) return false;
|
|
33
|
+
if (!PATCH_RANGE.test(range) && !isAgentMemFloorRange(range)) return false;
|
|
34
|
+
return Bun.semver.satisfies(version, range);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const positive = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
38
|
+
|
|
39
|
+
/** Whether the package's host API constants are valid positive integers (MIN <= VERSION) and their range intersects the supported one. */
|
|
40
|
+
export function agentMemHostApiOk(min: unknown, version: unknown, supported: readonly [number, number] = AGENT_MEM_HOST_API_RANGE): boolean {
|
|
41
|
+
const [lowest, highest] = supported;
|
|
42
|
+
return positive(min) && positive(version) && min <= version && min <= highest && version >= lowest;
|
|
43
|
+
}
|
package/src/hub/board.ts
CHANGED
|
@@ -20,7 +20,7 @@ import type { Database } from "./db-schema.ts";
|
|
|
20
20
|
import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts";
|
|
21
21
|
import { controlWriteSpan } from "./control-write-trace.ts";
|
|
22
22
|
import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
|
|
23
|
-
import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState } from "./roadmap.ts";
|
|
23
|
+
import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, githubRepo, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState, type DecomposePart, type DecomposeIntake, type DecompositionState, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
|
|
24
24
|
import { HUB, USER, type PeerId } from "./envelope.ts";
|
|
25
25
|
import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts";
|
|
26
26
|
import type { ReviewFinding } from "./review-findings.ts";
|
|
@@ -72,6 +72,11 @@ const GUIDANCE_VARIANT_SELECT = `SELECT CASE WHEN typeof(id)='text' AND length(C
|
|
|
72
72
|
export const HOST_MERGE_ADOPTION = Symbol("host merge adoption");
|
|
73
73
|
/** Internal publication capability, independent of the person-only acceptance API. */
|
|
74
74
|
export const HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
|
|
75
|
+
/**
|
|
76
|
+
* Internal capability for R2 part 2 (#1480): the draft `roadmapDecomposePart` stages for an accepted part is held exactly like the
|
|
77
|
+
* person's intake draft. A Symbol cannot arrive in a tool argument, so no caller can stage a hidden draft through it.
|
|
78
|
+
*/
|
|
79
|
+
export const HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft");
|
|
75
80
|
export interface SpecAcceptanceCommit { source: number; cancellationRevision: number; acceptance: SpecAcceptance; }
|
|
76
81
|
|
|
77
82
|
export interface ResearchCampaignRecord {
|
|
@@ -593,6 +598,7 @@ export class Board {
|
|
|
593
598
|
this.db.run("CREATE INDEX IF NOT EXISTS tasks_human_reviews ON tasks(id) WHERE state='in_review' AND reviewer='user'");
|
|
594
599
|
// #481 S7: one row per log-tier band breach episode already announced, so a restart never repeats the notice.
|
|
595
600
|
this.db.run("CREATE TABLE IF NOT EXISTS band_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
|
|
601
|
+
this.db.run("CREATE TABLE IF NOT EXISTS roadmap_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
|
|
596
602
|
// #481 S7: one row per scheduled security scan. Counts only (no alert text); `total` is null when a named source could not be read completely.
|
|
597
603
|
this.db.run("CREATE TABLE IF NOT EXISTS security_scans (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, repo TEXT NOT NULL, sources TEXT NOT NULL, counts TEXT NOT NULL, total INTEGER)");
|
|
598
604
|
// #843 AC3: one row per (agent id, installed version, planner) already queued, so a restart never repeats it.
|
|
@@ -647,6 +653,17 @@ export class Board {
|
|
|
647
653
|
this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_suggestions_pending ON milestone_suggestions(kind,ref) WHERE state='pending'");
|
|
648
654
|
this.db.run(`CREATE TABLE IF NOT EXISTS milestone_imports (
|
|
649
655
|
repo TEXT NOT NULL, number INTEGER NOT NULL, milestone INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(repo,number))`);
|
|
656
|
+
// R2 (#1480): model-written decompositions, additive and outside the roadmap integrity digest like a suggestion: a lost
|
|
657
|
+
// answer is asked for again, and one pending answer per milestone is the newest run.
|
|
658
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decompositions (
|
|
659
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, milestone INTEGER NOT NULL, parts TEXT NOT NULL,
|
|
660
|
+
state TEXT NOT NULL, by TEXT NOT NULL, created INTEGER NOT NULL, settled INTEGER, settled_by TEXT)`);
|
|
661
|
+
this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_decompositions_pending ON milestone_decompositions(milestone) WHERE state='pending'");
|
|
662
|
+
// R2 part 2 (#1480): which parts of a pending answer are already held as intake drafts. Keyed by the answer and the part's
|
|
663
|
+
// 1-based position, so accepting the same part twice finds this row instead of making a second draft.
|
|
664
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_accepts (
|
|
665
|
+
decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, task INTEGER NOT NULL,
|
|
666
|
+
intake TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`);
|
|
650
667
|
|
|
651
668
|
this.db.run(`CREATE TABLE IF NOT EXISTS research_campaigns (
|
|
652
669
|
id TEXT NOT NULL, project TEXT NOT NULL, parent_task_id INTEGER NOT NULL, revision INTEGER NOT NULL,
|
|
@@ -2612,6 +2629,15 @@ export class Board {
|
|
|
2612
2629
|
if (!/^[a-z_]{1,64}:#[1-9][0-9]{0,9}:log$/.test(marker)) throw new Error("invalid band notice marker");
|
|
2613
2630
|
return this.db.query("INSERT OR IGNORE INTO band_notices(marker, at) VALUES(?, ?)").run(marker, Date.now()).changes > 0;
|
|
2614
2631
|
}
|
|
2632
|
+
|
|
2633
|
+
hasRoadmapNotice(marker: string): boolean {
|
|
2634
|
+
if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
|
|
2635
|
+
return !!this.db.query("SELECT 1 FROM roadmap_notices WHERE marker=?").get(marker);
|
|
2636
|
+
}
|
|
2637
|
+
recordRoadmapNotice(marker: string): boolean {
|
|
2638
|
+
if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
|
|
2639
|
+
return this.db.query("INSERT OR IGNORE INTO roadmap_notices(marker,at) VALUES(?,?)").run(marker, Date.now()).changes > 0;
|
|
2640
|
+
}
|
|
2615
2641
|
/** True when the (id, version, planner) marker was new and is now recorded; false when it was announced before. */
|
|
2616
2642
|
recordAgentDriftNotice(marker: string): boolean {
|
|
2617
2643
|
if (!/^[a-z][a-z0-9-]{0,31}:[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}@[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(marker)) throw new Error("invalid agent drift marker");
|
|
@@ -3046,6 +3072,52 @@ export class Board {
|
|
|
3046
3072
|
this.db.query("UPDATE milestone_suggestions SET created_milestone=? WHERE id=? AND state='pending' AND created_milestone IS NULL").run(milestoneId(milestone), milestoneId(id));
|
|
3047
3073
|
}
|
|
3048
3074
|
|
|
3075
|
+
/** R2: one pending decomposition per milestone. A newer answer supersedes the older one in the same transaction, never doubles it. */
|
|
3076
|
+
addDecomposition(row: { milestone: number; parts: DecomposePart[] }, by: string, now = Date.now()): MilestoneDecomposition {
|
|
3077
|
+
const actor = milestoneActor(by), at = milestoneId(now), milestone = milestoneId(row.milestone);
|
|
3078
|
+
return this.db.transaction(() => {
|
|
3079
|
+
this.db.query("UPDATE milestone_decompositions SET state='superseded', settled=?, settled_by=? WHERE milestone=? AND state='pending'").run(at, actor, milestone);
|
|
3080
|
+
const inserted = this.db.query("INSERT INTO milestone_decompositions(milestone,parts,state,by,created) VALUES(?,?,'pending',?,?)").run(milestone, JSON.stringify(row.parts), actor, at);
|
|
3081
|
+
// Settled rows are history, not storage: keep the newest 200.
|
|
3082
|
+
this.db.query("DELETE FROM milestone_decompositions WHERE state<>'pending' AND id NOT IN (SELECT id FROM milestone_decompositions WHERE state<>'pending' ORDER BY id DESC LIMIT 200)").run();
|
|
3083
|
+
return this.decomposition(Number(inserted.lastInsertRowid))!;
|
|
3084
|
+
})();
|
|
3085
|
+
}
|
|
3086
|
+
|
|
3087
|
+
decomposition(id: number): MilestoneDecomposition | undefined {
|
|
3088
|
+
milestoneId(id);
|
|
3089
|
+
const row = this.db.query("SELECT * FROM milestone_decompositions WHERE id=?").get(id) as Record<string, unknown> | null;
|
|
3090
|
+
return row ? parseDecomposition(row) : undefined;
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
decompositions(state?: DecompositionState): MilestoneDecomposition[] {
|
|
3094
|
+
const rows = (state === undefined ? this.db.query("SELECT * FROM milestone_decompositions ORDER BY id").all() : this.db.query("SELECT * FROM milestone_decompositions WHERE state=? ORDER BY id").all(state)) as Record<string, unknown>[];
|
|
3095
|
+
return rows.map(parseDecomposition);
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
/** R2 part 2: the answer an accept reads its parts from. A superseded one is not pending, so an accept cannot land on it. */
|
|
3099
|
+
pendingDecomposition(milestone: number): MilestoneDecomposition | undefined {
|
|
3100
|
+
const row = this.db.query("SELECT * FROM milestone_decompositions WHERE milestone=? AND state='pending'").get(milestoneId(milestone)) as Record<string, unknown> | null;
|
|
3101
|
+
return row ? parseDecomposition(row) : undefined;
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
/** R2 part 2: the draft one part already made, if it was accepted before. */
|
|
3105
|
+
decompositionAccept(decomposition: number, part: number): DecompositionAccept | undefined {
|
|
3106
|
+
const row = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record<string, unknown> | null;
|
|
3107
|
+
return row ? parseDecompositionAccept(row) : undefined;
|
|
3108
|
+
}
|
|
3109
|
+
|
|
3110
|
+
/**
|
|
3111
|
+
* R2 part 2: record that a part is held as a draft. The insert is ignored on a repeated accept, so the row that already names
|
|
3112
|
+
* the first draft is the one a retry reads, and no second draft is ever keyed here.
|
|
3113
|
+
*/
|
|
3114
|
+
acceptDecompositionPart(row: { decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake }, by: string, now = Date.now()): DecompositionAccept {
|
|
3115
|
+
const actor = milestoneActor(by), at = milestoneId(now);
|
|
3116
|
+
this.db.query("INSERT OR IGNORE INTO milestone_decomposition_accepts(decomposition,milestone,part,task,intake,by,at) VALUES(?,?,?,?,?,?,?)")
|
|
3117
|
+
.run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.task), row.intake, actor, at);
|
|
3118
|
+
return this.decompositionAccept(row.decomposition, row.part)!;
|
|
3119
|
+
}
|
|
3120
|
+
|
|
3049
3121
|
/** Compare-and-set from pending: a second settle of the same suggestion changes nothing. */
|
|
3050
3122
|
settleSuggestion(id: number, state: "accepted" | "rejected" | "superseded", by: string, now = Date.now()): MilestoneSuggestion {
|
|
3051
3123
|
const actor = milestoneActor(by), at = milestoneId(now);
|
|
@@ -3063,6 +3135,24 @@ export class Board {
|
|
|
3063
3135
|
return row?.milestone;
|
|
3064
3136
|
}
|
|
3065
3137
|
|
|
3138
|
+
/** R4 uses the same durable marks as R3 imports; conflicting legacy marks are never guessed. */
|
|
3139
|
+
mirrorMilestone(repo: string, id: number): number | undefined {
|
|
3140
|
+
const rows = this.db.query("SELECT number FROM milestone_imports WHERE repo=? AND milestone=? ORDER BY number LIMIT 2").all(githubRepo(repo), milestoneId(id)) as { number: number }[];
|
|
3141
|
+
if (rows.length > 1) throw new PreEffectToolRefusal("roadmap milestone has conflicting GitHub bindings; inspect imports before syncing");
|
|
3142
|
+
return rows[0]?.number;
|
|
3143
|
+
}
|
|
3144
|
+
|
|
3145
|
+
bindMirrorMilestone(repo: string, id: number, number: number, now = Date.now()): void {
|
|
3146
|
+
const key = githubRepo(repo), local = milestoneId(id), remote = milestoneId(number), at = milestoneId(now);
|
|
3147
|
+
this.db.transaction(() => {
|
|
3148
|
+
if (!this.milestone(local)) throw new PreEffectToolRefusal("roadmap milestone no longer exists; inspect ahub roadmap list");
|
|
3149
|
+
const prior = this.mirrorMilestone(key, local), owner = this.importedMilestone(key, remote);
|
|
3150
|
+
if (prior !== undefined && prior !== remote || owner !== undefined && owner !== local) throw new PreEffectToolRefusal("roadmap GitHub binding conflicts with an existing milestone; inspect imports before syncing");
|
|
3151
|
+
if (prior === remote && owner === local) return;
|
|
3152
|
+
this.db.query("INSERT INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, remote, local, at);
|
|
3153
|
+
})();
|
|
3154
|
+
}
|
|
3155
|
+
|
|
3066
3156
|
/** One transaction: the milestone and its import mark exist together or not at all, so a repeat finds the mark. */
|
|
3067
3157
|
importMilestone(repo: string, number: number, input: MilestoneInput, by: string, now = Date.now()): { milestone: Milestone; created: boolean } {
|
|
3068
3158
|
const key = repo.toLowerCase();
|
|
@@ -3246,6 +3336,17 @@ function parseSuggestion(row: Record<string, unknown>): MilestoneSuggestion {
|
|
|
3246
3336
|
settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
|
|
3247
3337
|
}
|
|
3248
3338
|
|
|
3339
|
+
function parseDecomposition(row: Record<string, unknown>): MilestoneDecomposition {
|
|
3340
|
+
return { id: milestoneId(row.id), milestone: milestoneId(row.milestone), parts: JSON.parse(String(row.parts)) as DecomposePart[],
|
|
3341
|
+
state: row.state as DecompositionState, by: milestoneActor(row.by), created: milestoneId(row.created),
|
|
3342
|
+
settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
|
|
3343
|
+
}
|
|
3344
|
+
|
|
3345
|
+
function parseDecompositionAccept(row: Record<string, unknown>): DecompositionAccept {
|
|
3346
|
+
return { decomposition: milestoneId(row.decomposition), milestone: milestoneId(row.milestone), part: milestoneId(row.part), task: milestoneId(row.task),
|
|
3347
|
+
intake: row.intake as DecomposeIntake, by: milestoneActor(row.by), at: milestoneId(row.at) };
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3249
3350
|
function parseRelease(row: Record<string, unknown>): Release {
|
|
3250
3351
|
return { ...(row.train == null ? {} : { train: JSON.parse(String(row.train)) }), planner: row.planner == null ? null : String(row.planner), id: Number(row.id), name: String(row.name), goal: String(row.goal), order: Number(row.release_order), state: row.state as ReleaseState,
|
|
3251
3352
|
plannedStart: row.planned_start as number | null, cut: row.cut as number | null, ship: row.ship as number | null,
|
package/src/hub/check-runner.ts
CHANGED
|
@@ -40,6 +40,8 @@ export interface RunnerOptions {
|
|
|
40
40
|
projectDir: string; stateDir: string; storageDir: string; projectKey: string;
|
|
41
41
|
enabled: boolean | (() => boolean); isDenied: (path: string) => boolean;
|
|
42
42
|
onResult?: (receipt: RunReceipt) => void | Promise<void>;
|
|
43
|
+
/** #1555 AC6: whether the task is approved or cancelled, so a run that settles after its task closed is compacted when it leaves the queue. */
|
|
44
|
+
taskClosed?: (task: number) => boolean;
|
|
43
45
|
/** Daemon authority fence, re-evaluated across every asynchronous stage. */
|
|
44
46
|
isCurrent?: (request: CheckRequest) => boolean;
|
|
45
47
|
/** Test seams; never supplied from a tool request or config. */
|
|
@@ -262,7 +264,10 @@ export class ContainerRunner {
|
|
|
262
264
|
const entry = this.queue.shift(); if (!entry) return;
|
|
263
265
|
this.active = entry;
|
|
264
266
|
try { await this.execute(entry); }
|
|
265
|
-
finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.drain(); }
|
|
267
|
+
finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.compactIfClosed(entry.receipt.task); void this.drain(); }
|
|
268
|
+
}
|
|
269
|
+
private async compactIfClosed(task: number): Promise<void> {
|
|
270
|
+
try { if (this.options.taskClosed?.(task)) await this.compactTask(task); } catch { /* retention only: the files stay */ }
|
|
266
271
|
}
|
|
267
272
|
private async heavy(entry: Entry): Promise<() => Promise<void>> {
|
|
268
273
|
const lock = join(this.common, "ahub-heavy.lock");
|
|
@@ -497,6 +502,25 @@ export class ContainerRunner {
|
|
|
497
502
|
}
|
|
498
503
|
}
|
|
499
504
|
async consumeOutput(run: string): Promise<void> { if (/^[a-f0-9-]{36}$/.test(run)) await rm(join(this.root, run, "output.log"), { force: true }); }
|
|
505
|
+
/**
|
|
506
|
+
* #1555 AC6: a task reached approved or cancelled. Its finished receipts keep every field the verdict and the metrics read, but lose the output tail, and the staged output
|
|
507
|
+
* file goes with it (nobody reads either once the task is closed). A run still queued or running is left alone, and each rewrite goes through the receipt's own save turn.
|
|
508
|
+
*/
|
|
509
|
+
async compactTask(task: number): Promise<number> {
|
|
510
|
+
const names = await readdir(this.records).catch(error => { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; });
|
|
511
|
+
let compacted = 0;
|
|
512
|
+
for (const name of names) {
|
|
513
|
+
const run = name.endsWith(".json") ? name.slice(0, -5) : "";
|
|
514
|
+
if (!/^[a-f0-9-]{36}$/.test(run) || this.entries.has(run)) continue;
|
|
515
|
+
let receipt: RunReceipt | undefined;
|
|
516
|
+
try { receipt = await this.result(run); } catch { continue; }
|
|
517
|
+
if (!receipt || receipt.task !== task || (receipt.status !== "finished" && receipt.status !== "stale")) continue;
|
|
518
|
+
if (receipt.tail !== "") { receipt.tail = ""; await this.save(receipt); }
|
|
519
|
+
await this.consumeOutput(run);
|
|
520
|
+
compacted++;
|
|
521
|
+
}
|
|
522
|
+
return compacted;
|
|
523
|
+
}
|
|
500
524
|
async cancel(run: string): Promise<void> {
|
|
501
525
|
const entry = this.entries.get(run); if (!entry) return;
|
|
502
526
|
entry.receipt.cancelled = true; entry.abort.abort();
|
package/src/hub/config-apply.ts
CHANGED
|
@@ -210,6 +210,8 @@ const schema: Record<string, Check> = {
|
|
|
210
210
|
budget: block({ gate: number(0, 1), stale_min: timerMinutes, poll_min: timerMinutes, checkpoint_timeout_s: timerSeconds, kimi_tokens_5h: number(0), wait_max_min: number(0) }),
|
|
211
211
|
context: block({ gate: number(0, 1), stale_min: timerMinutes, max_assignment_used: number(0, 1) }),
|
|
212
212
|
supervision: block({ mode: words(["off", "shadow", "advisory"]) }),
|
|
213
|
+
edit_governance: block({ arm: words(["baseline", "route_guard", "occ_guard", "combined_guard"]) }),
|
|
214
|
+
roadmap: block({ github_mirror: bool, github_write: words(["off", "conductor"]) }),
|
|
213
215
|
bus: block({ max_attempts: operationalNumberCheck("bus.max_attempts"), digest_max: operationalNumberCheck("bus.digest_max"), pull_budget_bytes: operationalNumberCheck("bus.pull_budget_bytes"), notes_kept: operationalNumberCheck("bus.notes_kept"), terminal_history_limit: operationalNumberCheck("bus.terminal_history_limit"), accepted_settle_ms: operationalNumberCheck("bus.accepted_settle_ms") }),
|
|
214
216
|
adapter_timing: block({ acp_tool_ceiling_min: operationalNumberCheck("adapter_timing.acp_tool_ceiling_min"), acp_activity_batch_ms: operationalNumberCheck("adapter_timing.acp_activity_batch_ms"), jcode_steer_timeout_s: operationalNumberCheck("adapter_timing.jcode_steer_timeout_s") }),
|
|
215
217
|
model_relay: block({ cooldown_failures: operationalNumberCheck("model_relay.cooldown_failures"), cooldown_s: operationalNumberCheck("model_relay.cooldown_s"), cooldown_cap_s: operationalNumberCheck("model_relay.cooldown_cap_s"), terminal_history_limit: operationalNumberCheck("model_relay.terminal_history_limit") }),
|
|
@@ -279,9 +281,9 @@ const restart: Record<string, string> = {
|
|
|
279
281
|
checks: "Bounded runner and completion-check contracts are constructed together",
|
|
280
282
|
pii: "Existing native sessions retain their startup privacy boundary", data: "Existing native sessions retain their startup read-only policy",
|
|
281
283
|
profile: "Session tool schemas and profile contracts are bound at startup", profile_overrides: "Session tool schemas and profile contracts are bound at startup",
|
|
282
|
-
text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
|
|
284
|
+
text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", roadmap: "GitHub mirror authority is bound at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
|
|
283
285
|
};
|
|
284
|
-
const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision"]);
|
|
286
|
+
const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision", "edit_governance"]);
|
|
285
287
|
const nextMemory = new Set(["memory.inject_tokens", "memory.brief_items", "memory.suggest_edges", "memory.preface_unused_after"]);
|
|
286
288
|
/** Closed top-level schema; leaf overrides retain the existing session/runtime boundaries. */
|
|
287
289
|
export function configApply(key: string, scopes: readonly ConfigIdentityScope[] = []): ApplyRule {
|
package/src/hub/config-trust.ts
CHANGED
|
@@ -37,7 +37,7 @@ export const MACHINE_LOCAL = [
|
|
|
37
37
|
"invocation", // #445 C1: what another agent may be offered from this machine's agents (a digest-pinned allowlist); a committed config may not share a person's agents' commands with someone else's peers
|
|
38
38
|
] as const;
|
|
39
39
|
/** Legacy exported field list stays compatible; new policies use the complete list below. */
|
|
40
|
-
export const ALL_MACHINE_LOCAL = [...MACHINE_LOCAL, "research.runners", "rooms", "tasks.queue_backpressure", "context.max_assignment_used", "action_policy", "protect_instruction_files", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_provider_profile", "start.agents", "adapters", "adapter_modules", "text_projection", "instances"] as const;
|
|
40
|
+
export const ALL_MACHINE_LOCAL = [...MACHINE_LOCAL, "edit_governance.arm", "roadmap.github_mirror", "roadmap.github_write", "research.runners", "rooms", "tasks.queue_backpressure", "context.max_assignment_used", "action_policy", "protect_instruction_files", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_provider_profile", "start.agents", "adapters", "adapter_modules", "text_projection", "instances"] as const;
|
|
41
41
|
/** An empty list of these is a value (`start.agents` empty starts no agent), not "the default", so the empty-value drop below skips them. */
|
|
42
42
|
const EMPTY_IS_VALUE: readonly string[] = ["start.agents"];
|
|
43
43
|
|
|
@@ -9,7 +9,7 @@ export function readNativeContext(definition: AdapterDefinition | undefined, val
|
|
|
9
9
|
|
|
10
10
|
/** Native active-context occupancy, separate from accumulated billable usage (#185). */
|
|
11
11
|
export interface ContextReading {
|
|
12
|
-
source: "claude_statusline" | "codex_token_usage" | "acp_usage_update" | "jcode_usage_update";
|
|
12
|
+
source: "claude_statusline" | "codex_token_usage" | "acp_usage_update" | "jcode_usage_update" | "pi_usage";
|
|
13
13
|
sessionId: string;
|
|
14
14
|
measuredAt: number;
|
|
15
15
|
tokens: number | null;
|
|
@@ -3,8 +3,8 @@ export interface ReviewScope { scope: "none" | "delta" | "full"; reviewers: numb
|
|
|
3
3
|
export interface CostPlan { review?: ReviewScope; ci?: "focused" | "full" | "reuse" }
|
|
4
4
|
export interface ReviewCost extends CostPlan { head?: string }
|
|
5
5
|
export interface CostTask { repo: string; pr: number; private?: boolean; history: { event: string; at: number; reviewCost?: ReviewCost }[] }
|
|
6
|
-
export interface CostPr { repo: string; pr: number; state: "OPEN" | "CLOSED" | "MERGED"; mergedAt?: number; complete: boolean; ciRuns?: { id: number; attempt: number }[]; reviews?: number }
|
|
7
|
-
export interface CostRow { repo: string; pr: number; reviewRounds: number; ciRuns: number | null; ciReruns: number | null; fullReReviews: number; deltaReviews: number; reviewMs: number | null; unknownReviewScopes: number; githubReviews: number | null; complete: boolean }
|
|
6
|
+
export interface CostPr { repo: string; pr: number; state: "OPEN" | "CLOSED" | "MERGED"; mergedAt?: number; complete: boolean; ciRuns?: { id: number; attempt: number }[]; reviews?: number; fullGateRuns?: number; successfulGateRuns?: number; failedGateRuns?: number; cancelledGateRuns?: number; otherGateRuns?: number; macosShardRuns?: number; firstPass?: 0 | 1 | null }
|
|
7
|
+
export interface CostRow { repo: string; pr: number; reviewRounds: number; ciRuns: number | null; ciReruns: number | null; fullReReviews: number; deltaReviews: number; reviewMs: number | null; unknownReviewScopes: number; githubReviews: number | null; complete: boolean; fullGateRuns?: number; successfulGateRuns?: number; failedGateRuns?: number; cancelledGateRuns?: number; otherGateRuns?: number; macosShardRuns?: number }
|
|
8
8
|
export interface CostReport { rows: CostRow[]; truncated: boolean }
|
|
9
9
|
/**
|
|
10
10
|
* #1087: why a cost scope was refused. The message is fixed text that names the field and its allowed values and never the value given, so a call site may show it
|
|
@@ -43,7 +43,7 @@ export function cleanCostPlan(input: unknown, field: string | { review: string;
|
|
|
43
43
|
* #481 S7: what the guarded merge records about a merged PR, from the PR read once at merge. Every field is `null` when the read could not establish it, never 0.
|
|
44
44
|
* CI figures need the complete read (runs linked by every head of the PR); a rerun is an attempt after the first of one run id, i.e. the same head run again.
|
|
45
45
|
*/
|
|
46
|
-
export interface MergeCost { mergedAt: number | null; ciRuns: number | null; ciReruns: number | null; reviews: number | null }
|
|
46
|
+
export interface MergeCost { mergedAt: number | null; ciRuns: number | null; ciReruns: number | null; reviews: number | null; fullGateRuns?: number | null; successfulGateRuns?: number | null; failedGateRuns?: number | null; cancelledGateRuns?: number | null; otherGateRuns?: number | null; macosShardRuns?: number | null; firstPass?: 0 | 1 | null }
|
|
47
47
|
export function ciRunCounts(runs: readonly { id: number; attempt: number }[] | undefined): { runs: number; reruns: number } | null {
|
|
48
48
|
if (!runs || runs.length > 100) return null;
|
|
49
49
|
const attempts = new Map<number, number>();
|
|
@@ -57,13 +57,15 @@ export function mergeCostFrom(pr: CostPr | undefined): MergeCost | undefined {
|
|
|
57
57
|
if (!pr || pr.state !== "MERGED") return undefined;
|
|
58
58
|
const counts = pr.complete ? ciRunCounts(pr.ciRuns) : null;
|
|
59
59
|
return { mergedAt: Number.isSafeInteger(pr.mergedAt) && pr.mergedAt! >= 0 ? pr.mergedAt! : null, ciRuns: counts?.runs ?? null, ciReruns: counts?.reruns ?? null,
|
|
60
|
-
reviews: Number.isSafeInteger(pr.reviews) && pr.reviews! >= 0 ? pr.reviews! : null
|
|
60
|
+
reviews: Number.isSafeInteger(pr.reviews) && pr.reviews! >= 0 ? pr.reviews! : null,
|
|
61
|
+
...(pr.complete && pr.fullGateRuns !== undefined ? { fullGateRuns: pr.fullGateRuns, successfulGateRuns: pr.successfulGateRuns ?? null, failedGateRuns: pr.failedGateRuns ?? null, cancelledGateRuns: pr.cancelledGateRuns ?? null, otherGateRuns: pr.otherGateRuns ?? null, macosShardRuns: pr.macosShardRuns ?? null, firstPass: pr.firstPass ?? null } : {}) };
|
|
61
62
|
}
|
|
62
63
|
/** Bounded, finite or absent: a stored record is data, never trusted shape. */
|
|
63
64
|
export function cleanMergeCost(value: unknown): MergeCost | undefined {
|
|
64
65
|
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
65
66
|
const raw = value as Record<string, unknown>, field = (key: string) => Number.isSafeInteger(raw[key]) && (raw[key] as number) >= 0 ? raw[key] as number : null;
|
|
66
|
-
return { mergedAt: field("mergedAt"), ciRuns: field("ciRuns"), ciReruns: field("ciReruns"), reviews: field("reviews")
|
|
67
|
+
return { mergedAt: field("mergedAt"), ciRuns: field("ciRuns"), ciReruns: field("ciReruns"), reviews: field("reviews"),
|
|
68
|
+
...(Object.hasOwn(raw, "fullGateRuns") ? { fullGateRuns: field("fullGateRuns"), successfulGateRuns: field("successfulGateRuns"), failedGateRuns: field("failedGateRuns"), cancelledGateRuns: field("cancelledGateRuns"), otherGateRuns: field("otherGateRuns"), macosShardRuns: field("macosShardRuns"), firstPass: raw.firstPass === 0 || raw.firstPass === 1 ? raw.firstPass : null } : {}) };
|
|
67
69
|
}
|
|
68
70
|
const validRepo = (repo: string) => /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) && !repo.startsWith("-");
|
|
69
71
|
const key = (repo: string, pr: number) => `${repo.toLowerCase()}#${pr}`;
|
|
@@ -99,12 +101,14 @@ export function costMetrics(tasks: CostTask[], prs: CostPr[]): CostReport {
|
|
|
99
101
|
}
|
|
100
102
|
if (pr.ciRuns && pr.ciRuns.length > 100) { complete = false; truncated = true; }
|
|
101
103
|
if (!pr.ciRuns || pr.reviews === undefined || rounds.some(round => round.elapsed === undefined || round.scope === undefined)) complete = false;
|
|
104
|
+
const ci = pr.complete ? ciRunCounts(pr.ciRuns) : null;
|
|
102
105
|
rows.push({ repo: pr.repo.toLowerCase(), pr: pr.pr, reviewRounds: rounds.length,
|
|
103
|
-
ciRuns:
|
|
106
|
+
ciRuns: ci?.runs ?? null, ciReruns: ci?.reruns ?? null,
|
|
104
107
|
fullReReviews: rounds.filter((round, index) => index > 0 && round.scope === "full").length,
|
|
105
108
|
deltaReviews: rounds.filter(round => round.scope === "delta").length,
|
|
106
109
|
reviewMs: rounds.every(round => round.elapsed !== undefined) ? rounds.reduce((sum, round) => sum + round.elapsed!, 0) : null,
|
|
107
|
-
unknownReviewScopes: rounds.filter(round => round.scope === undefined).length, githubReviews: pr.reviews ?? null, complete
|
|
110
|
+
unknownReviewScopes: rounds.filter(round => round.scope === undefined).length, githubReviews: pr.reviews ?? null, complete,
|
|
111
|
+
...(pr.complete && pr.fullGateRuns !== undefined ? { fullGateRuns: pr.fullGateRuns, successfulGateRuns: pr.successfulGateRuns, failedGateRuns: pr.failedGateRuns, cancelledGateRuns: pr.cancelledGateRuns, otherGateRuns: pr.otherGateRuns, macosShardRuns: pr.macosShardRuns } : {}) });
|
|
108
112
|
}
|
|
109
113
|
return { rows: rows.sort((a, b) => a.repo.localeCompare(b.repo) || a.pr - b.pr), truncated };
|
|
110
114
|
}
|