@staix/agent-hub 0.42.0 → 0.44.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/agent-notes/daemon.md +3 -3
  5. package/docs/agent-notes/local-worker.md +1 -0
  6. package/docs/agent-notes/tasks.md +3 -2
  7. package/docs/agent-notes/tests.md +2 -2
  8. package/docs/design/adapters.md +3 -0
  9. package/docs/design/agent-hub-architecture.md +2 -0
  10. package/docs/design/bus.md +2 -0
  11. package/docs/design/supervision.md +13 -1
  12. package/docs/design/task-board.md +13 -1
  13. package/docs/dogfood.md +13 -3
  14. package/docs/events.md +4 -2
  15. package/docs/memory.md +5 -3
  16. package/docs/operations.md +97 -17
  17. package/docs/quickstart.md +18 -2
  18. package/docs/research.md +2 -0
  19. package/docs/sdlc.md +6 -3
  20. package/docs/security.md +2 -2
  21. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  22. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  23. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  24. package/docs/verified.json +25 -25
  25. package/package.json +2 -2
  26. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  27. package/plugins/agent-hub/kimi-hook.js +486 -218
  28. package/plugins/agent-hub/server.js +505 -234
  29. package/src/adapters/claude-implementer.ts +11 -1
  30. package/src/adapters/claude-print-child.ts +4 -1
  31. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  32. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  33. package/src/adapters/local-worker.ts +7 -3
  34. package/src/adapters/reviewer-print.ts +3 -1
  35. package/src/cli/help.ts +3 -3
  36. package/src/cli/identity.ts +2 -0
  37. package/src/cli/main.ts +57 -5
  38. package/src/cli/output.ts +2 -2
  39. package/src/cli/sdlc-output.ts +7 -1
  40. package/src/cli/upgrade-output.ts +43 -2
  41. package/src/cli/upgrade-stopped.ts +162 -0
  42. package/src/cli/upgrade-wait.ts +37 -0
  43. package/src/cli/upgrade.ts +9 -3
  44. package/src/hub/board.ts +17 -2
  45. package/src/hub/bus.ts +4 -0
  46. package/src/hub/claude-shell-wrapper.ts +2 -1
  47. package/src/hub/config-apply.ts +1 -0
  48. package/src/hub/control-write-trace.ts +39 -2
  49. package/src/hub/daemon.ts +141 -37
  50. package/src/hub/envelope.ts +1 -0
  51. package/src/hub/facts.ts +30 -0
  52. package/src/hub/handoff.ts +14 -0
  53. package/src/hub/hub-tools.ts +1 -1
  54. package/src/hub/questions.ts +7 -0
  55. package/src/hub/quota-events.ts +40 -0
  56. package/src/hub/recovery-store.ts +57 -0
  57. package/src/hub/report.ts +1 -1
  58. package/src/hub/research-quality.ts +5 -1
  59. package/src/hub/research-record.ts +5 -3
  60. package/src/hub/restart.ts +49 -2
  61. package/src/hub/runtime-capture-prune.ts +123 -4
  62. package/src/hub/runtime-prune-health.ts +10 -2
  63. package/src/hub/sdlc-merge.ts +7 -3
  64. package/src/hub/sdlc-metrics.ts +17 -8
  65. package/src/hub/sdlc.ts +18 -6
  66. package/src/hub/settings.ts +2 -0
  67. package/src/hub/snapshots.ts +43 -0
  68. package/src/hub/supervision-rules.ts +2 -2
  69. package/src/hub/task-shell-command.ts +124 -0
  70. package/src/hub/task-sweep.ts +6 -2
  71. package/src/hub/tasks.ts +131 -22
  72. package/src/hub/turn-attribution.ts +46 -0
  73. package/src/hub/worktree-shelf.ts +2 -1
  74. package/src/local/sandbox.ts +2 -1
  75. package/src/local/shell-environment.ts +6 -0
  76. package/src/memory/brief.ts +10 -1
  77. package/templates/AGENTS.block.md +1 -1
@@ -204,6 +204,13 @@ export class QuestionStore {
204
204
  }
205
205
  close(): void { try { this.db.close(); } catch { /* already closed */ } }
206
206
 
207
+ /** Timing only: never hydrate question text for the idle-owner sweep.
208
+ * ponytail: QuestionDesk's KEEP_SETTLED_MS (7 days) is the anchor ceiling; after pruning the ladder falls back to its own state. A durable board marker is the upgrade path. */
209
+ ownerWait(task: number, peer: string): { open: boolean; settled?: number } {
210
+ const row = this.db.query("SELECT MAX(CASE WHEN state = 'open' THEN 1 ELSE 0 END) AS open, MAX(settled) AS settled FROM questions WHERE task = ? AND peer = ?").get(task, peer) as { open: number | null; settled: number | null };
211
+ return { open: row.open === 1, ...(row.settled === null ? {} : { settled: row.settled }) };
212
+ }
213
+
207
214
  get(set: string): QuestionRow | undefined {
208
215
  if (typeof set !== "string" || !QUESTION_SET.test(set)) return undefined;
209
216
  const raw = this.db.query("SELECT * FROM questions WHERE set_id = ?").get(set) as RawRow | null;
@@ -0,0 +1,40 @@
1
+ import type { HubEvent } from "./events.ts";
2
+
3
+ export const QUOTA_HEARTBEAT_MS = 15 * 60_000;
4
+ const QUOTA_USED_DELTA = 0.005;
5
+ type QuotaEvent = Extract<HubEvent, { type: "quota" }>;
6
+ type Reading = { peer: string; windows: QuotaEvent["windows"]; hard: boolean; at: number };
7
+ type State = { recorded: Reading; last: Reading; pending: boolean };
8
+
9
+ /** Recorded rows describe changes and bounded coverage, not the number of provider polls. */
10
+ export class QuotaEventFilter {
11
+ private readonly peers = new Map<string, State>();
12
+ constructor(private readonly emit: (event: QuotaEvent) => void) {}
13
+
14
+ private write(reading: Reading): void {
15
+ this.emit({ type: "quota", peer: reading.peer, windows: reading.windows, hard: reading.hard, measuredAt: new Date(reading.at).toISOString() });
16
+ const previous = this.peers.get(reading.peer);
17
+ if (previous) { previous.recorded = reading; if (previous.last === reading) previous.pending = false; }
18
+ else this.peers.set(reading.peer, { recorded: reading, last: reading, pending: false });
19
+ }
20
+
21
+ record(peer: string, windows: QuotaEvent["windows"], hard: boolean, at: number): void {
22
+ // ponytail: a crash loses at most one unemitted tail per peer; an older out-of-order reading can delay a flush.
23
+ for (const state of this.peers.values()) if (state.pending && at - state.last.at >= QUOTA_HEARTBEAT_MS) this.write(state.last);
24
+ const reading: Reading = { peer, windows: windows.map(window => ({ ...window })), hard, at };
25
+ const state = this.peers.get(peer);
26
+ if (!state) { this.write(reading); return; }
27
+ const before = new Map(state.recorded.windows.map(window => [window.id, window]));
28
+ const changed = hard !== state.recorded.hard || before.size !== windows.length || windows.some(window => {
29
+ const prior = before.get(window.id);
30
+ return !prior || prior.resetsAt !== window.resetsAt || Math.abs(window.used - prior.used) + Number.EPSILON >= QUOTA_USED_DELTA;
31
+ });
32
+ state.last = reading;
33
+ if (changed || at - state.recorded.at >= QUOTA_HEARTBEAT_MS || at < state.recorded.at) this.write(reading);
34
+ else state.pending = true;
35
+ }
36
+
37
+ flush(): void {
38
+ for (const state of this.peers.values()) if (state.pending) this.write(state.last);
39
+ }
40
+ }
@@ -7,6 +7,8 @@ import { isDatabaseBusy } from "./recovery-error.ts";
7
7
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
8
8
 
9
9
  const RUNNER_DB_BUSY_TIMEOUT_MS = 3000;
10
+ /** A startup-path hold check never waits on the event loop: busy counts as held (#1546). */
11
+ const HOLD_CHECK_DB_BUSY_TIMEOUT_MS = 1;
10
12
  export const operationIdPattern = /^[a-f0-9-]{36}$/;
11
13
  export function operationPath(id: string, home = hubHome()): string {
12
14
  if (typeof id !== "string" || id.length !== 36 || !operationIdPattern.test(id)) throw new Error("invalid recovery operation ID");
@@ -89,6 +91,18 @@ function projectLocks(home: string, create = false): Database | undefined {
89
91
  return db;
90
92
  } catch (error) { db?.close(); if (isDatabaseBusy(error)) throw error; throw projectLockError(); }
91
93
  }
94
+ /** Read-only, 1 ms busy wait: for a check on a startup path that must never wait on the event loop (#1546). Unreadable or busy throws. */
95
+ function projectLocksNonBlocking(home: string): Database | undefined {
96
+ const file = projectLocksPath(home);
97
+ if (!projectLocksExist(file)) return undefined;
98
+ let db: Database | undefined;
99
+ try {
100
+ db = new Database(file, { readonly: true, create: false });
101
+ db.run(`PRAGMA busy_timeout = ${HOLD_CHECK_DB_BUSY_TIMEOUT_MS}`);
102
+ if (!db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='project_locks'").get()) throw projectLockError();
103
+ return db;
104
+ } catch (error) { db?.close(); throw error; }
105
+ }
92
106
  function projectLockOn(db: Database, key: string): string | undefined {
93
107
  const rows = db.query("SELECT CASE WHEN typeof(operation_id)='text' AND length(operation_id)=36 THEN operation_id END AS id FROM project_locks WHERE project_root=? LIMIT 2").all(key) as { id: string | null }[];
94
108
  if (!rows.length) return undefined;
@@ -282,3 +296,46 @@ export function claimRunner(id: string, home = hubHome()): () => void {
282
296
  db.close();
283
297
  };
284
298
  }
299
+
300
+ /**
301
+ * True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held.
302
+ * `nonBlocking` bounds how long a locked project-locks.db may block the caller to 1 ms: a startup path passes it so a busy database is a
303
+ * hold, never a wait on the event loop (#1546). Without it the normal runner timeout applies.
304
+ */
305
+ export function anyRecoveryHold(home = hubHome(), nonBlocking = false): boolean {
306
+ try {
307
+ if (legacyRecoveryLock(home)) return true;
308
+ const db = nonBlocking ? projectLocksNonBlocking(home) : projectLocks(home);
309
+ if (!db) return false;
310
+ try { return !!db.query("SELECT 1 FROM project_locks LIMIT 1").get(); } finally { db.close(); }
311
+ } catch { return true; }
312
+ }
313
+
314
+ /**
315
+ * #1541: remove one terminal receipt and its runner db. The exclusive runner claim is the only mutual exclusion: a live or
316
+ * unidentifiable runner keeps the receipt, a dead one is replaced by `claimRunner` in its own transaction, so two retirers
317
+ * on the same stale claim cannot both proceed. Under the claim `confirm` sees the receipt as it is now; the receipt leaves
318
+ * first, then the claim row is released, then the runner db. An interruption between them leaves only a runner db without
319
+ * a receipt, which the next call settles through the ENOENT branch (a later claimant re-reads the receipt, finds none and
320
+ * fails). A runner db whose receipt is gone is settled the same way (`settled`, `confirm` never called); only the call that
321
+ * removed the receipt answers `retired`.
322
+ */
323
+ export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void } = {}): "retired" | "settled" | "kept" {
324
+ const file = operationPath(id, home);
325
+ let release: () => void;
326
+ try { release = claimRunner(id, home); } catch { return "kept"; }
327
+ let result: "retired" | "settled" = "settled";
328
+ try {
329
+ let record: unknown, removed = false;
330
+ try { record = readOperation(id, home); }
331
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "kept"; }
332
+ if (record !== undefined) {
333
+ if (!confirm(record)) return "kept";
334
+ rmSync(file); removed = true;
335
+ hooks.betweenPair?.();
336
+ }
337
+ result = removed ? "retired" : "settled";
338
+ } finally { release(); }
339
+ rmSync(`${file}.runner.db`, { force: true });
340
+ return result;
341
+ }
package/src/hub/report.ts CHANGED
@@ -243,7 +243,7 @@ export function formatReport(r: Report): string[] {
243
243
  lines.push(`overlap warnings: ${r.overlaps.warnings}, task pairs: ${r.overlaps.pairs}; edit conflicts: ${r.conflicts}`);
244
244
  const tasks = Object.entries(r.tasks).sort().map(([k, n]) => `${k} ${n}`).join(", ");
245
245
  lines.push(`task events: ${tasks || "none"}`);
246
- lines.push(`quota readings: ${r.quota.readings} (${r.quota.hard} hard limits)`);
246
+ lines.push(`quota rows: ${r.quota.readings} (${r.quota.hard} hard rows)`);
247
247
  for (const [key, s] of Object.entries(r.routes).sort(([a], [b]) => a.localeCompare(b))) {
248
248
  const sessions = s.stateless ? `sessions unknown (${s.stateless} decision${s.stateless === 1 ? "" : "s"} without a session key)`
249
249
  : s.sessions ? `${s.sessions} session${s.sessions === 1 ? "" : "s"}, ${(s.switches / s.sessions).toFixed(1)} model changes per session` : "sessions unknown (stay_switch off)";
@@ -74,7 +74,11 @@ export function buildResearchQuality(records: readonly ResearchRecord[], events:
74
74
  note(name, value);
75
75
  }
76
76
  }
77
- const windowEvents = events.filter(e => { const t = Date.parse(e.at); return Number.isFinite(t) && t >= from && t <= to; });
77
+ const windowEvents = events.filter(e => {
78
+ const measured = e.type === "quota" && typeof e.measuredAt === "string" ? Date.parse(e.measuredAt) : NaN;
79
+ const t = Number.isFinite(measured) ? measured : Date.parse(e.at);
80
+ return Number.isFinite(t) && t >= from && t <= to;
81
+ });
78
82
  const present: Record<string, number> = {};
79
83
  const quota: Record<string, { times: number[]; measured: number; event: number }> = {};
80
84
  const budget: QualityReport["budget"] = { pauses: 0, resumes: 0, handoffs: null, byFamily: {} };
@@ -115,7 +115,8 @@ export function evidenceEntry(raw: unknown): EvidenceEntry | undefined {
115
115
  const family = closedId(e.reviewerFamily);
116
116
  if (family) out.reviewerFamily = family;
117
117
  const cost = text(e.reviewCost), findings = text(e.reviewFindings);
118
- if (typeof cost?.head === "string" && /^[0-9a-f]{40}$/.test(cost.head)) out.requestHead = cost.head;
118
+ const requestedHead = e.event === "done" ? e.requestHead ?? cost?.head ?? text(e.specReport)?.head : undefined;
119
+ if (typeof requestedHead === "string" && /^[0-9a-f]{40}$/.test(requestedHead)) out.requestHead = requestedHead;
119
120
  const planned = member(PLANNED_SCOPES, text(cost?.review)?.scope);
120
121
  if (planned) out.plannedScope = planned;
121
122
  if (typeof findings?.head === "string" && /^[0-9a-f]{40}$/.test(findings.head)) out.verdictHead = findings.head;
@@ -140,10 +141,11 @@ export function evidenceEntry(raw: unknown): EvidenceEntry | undefined {
140
141
  /** A board task (live `Task` or a parsed row) as closed evidence. The title, detail, plan, refs and every note stay behind. */
141
142
  export function evidenceTask(raw: { id: number; history?: unknown; sdlc?: unknown }, handoffs?: { in: number; out: number }): EvidenceTask {
142
143
  const history = (Array.isArray(raw.history) ? raw.history : []).flatMap(entry => { const e = evidenceEntry(entry); return e ? [e] : []; }).sort((a, b) => a.at - b.at);
143
- const merge = text(text(raw.sdlc)?.merge);
144
+ const receipt = text(raw.sdlc), guarded = text(receipt?.merge);
145
+ const merge = guarded?.state === "merged" ? guarded : text(receipt?.mergeReadback);
144
146
  let mergeEvidence: EvidenceMerge | undefined;
145
147
  if (merge?.state === "merged") {
146
- const cost = cleanMergeCost(merge.cost), at = cost?.mergedAt ?? (typeof merge.at === "number" && Number.isSafeInteger(merge.at) ? merge.at : null);
148
+ const cost = cleanMergeCost(merge.cost), at = cost?.mergedAt ?? (merge === guarded && typeof merge.at === "number" && Number.isSafeInteger(merge.at) ? merge.at : null);
147
149
  mergeEvidence = { mergedAt: at, ciRuns: cost?.ciRuns ?? null, ciReruns: cost?.ciReruns ?? null, reviews: cost?.reviews ?? null };
148
150
  }
149
151
  return { id: raw.id, history, ...(mergeEvidence ? { merge: mergeEvidence } : {}), ...(handoffs ? { handoffs } : {}) };
@@ -1,4 +1,4 @@
1
- import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import type { BusSnapshot } from "./bus.ts";
@@ -200,7 +200,7 @@ export function readRestartSnapshot(stateDir: string, expected: RestartReadExpec
200
200
  || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
201
201
  }
202
202
  if (bus.journal !== undefined) { try { validateJournalSnapshot(bus.journal); } catch { return undefined; } }
203
- return s as RestartSnapshot;
203
+ return { ...s, bus: expandRestartBus(s.bus as BusSnapshot) } as RestartSnapshot;
204
204
  }
205
205
 
206
206
  /** Atomic, owner-readable recovery state. The file never carries delivery bodies outside this 0600 path. */
@@ -241,10 +241,57 @@ export function abandonRestartSnapshot(stateDir: string, operationId: string): v
241
241
  const archived = join(stateDir, `restart.abandoned.${createHash("sha256").update(operationId).digest("hex")}.json`);
242
242
  renameSync(restartPath(stateDir), archived);
243
243
  chmodSync(archived, 0o600);
244
+ pruneRestartArchives(stateDir);
244
245
  }
245
246
 
246
247
  /** Preserve an uncertain release outcome for manual reconciliation without making it authoritative on startup. */
247
248
  export function archiveRestartSnapshot(stateDir: string, operationId: string): void {
248
249
  renameSync(restartPath(stateDir), releasedRestartPath(stateDir, operationId));
249
250
  chmodSync(releasedRestartPath(stateDir, operationId), 0o600);
251
+ pruneRestartArchives(stateDir);
252
+ }
253
+
254
+ /** Recent archived copies kept per kind (#1546). ponytail: a fixed count; a configurable one can follow if a person needs more history. */
255
+ export const RESTART_ARCHIVES_KEPT = 5;
256
+ /** Terminal delivery bodies in a restart snapshot are cut to this many characters (#1546). */
257
+ export const RESTART_TERMINAL_BODY = 256;
258
+
259
+ /** Keep the newest `keep` restart.released.* and restart.abandoned.* files; best effort, never throws. */
260
+ export function pruneRestartArchives(stateDir: string, keep = RESTART_ARCHIVES_KEPT): void {
261
+ for (const kind of ["released", "abandoned"]) {
262
+ try {
263
+ const files = readdirSync(stateDir).filter((f) => f.startsWith(`restart.${kind}.`) && f.endsWith(".json")).map((f) => {
264
+ const path = join(stateDir, f);
265
+ return { path, at: statSync(path).mtimeMs };
266
+ }).sort((a, b) => b.at - a.at || (a.path < b.path ? 1 : -1));
267
+ for (const old of files.slice(keep)) { try { unlinkSync(old.path); } catch { /* already gone */ } }
268
+ } catch { /* state dir unreadable: keep everything */ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * The bus as written to restart.json: `seen` is stored once (the nested journal's copy is emptied and restored from the
274
+ * top level on read), and completed and discarded deliveries keep identity and state but only a cut body.
275
+ * Pending and in-flight deliveries are untouched. Both fields stay valid for an older hub, which reads an empty nested seen.
276
+ */
277
+ export function compactRestartBus(bus: BusSnapshot): BusSnapshot {
278
+ const journal = bus.journal;
279
+ if (!journal) return bus;
280
+ const cut = (e: Envelope): Envelope => e.body.length > RESTART_TERMINAL_BODY ? { ...e, body: e.body.slice(0, RESTART_TERMINAL_BODY) } : e;
281
+ // failed is not terminal for retry: a retry child copies originals and out, so a failed delivery keeps its full bodies.
282
+ const terminal = new Set(["completed", "discarded"]);
283
+ return {
284
+ ...bus,
285
+ journal: {
286
+ ...journal,
287
+ bus: { ...journal.bus, seen: [] },
288
+ deliveries: journal.deliveries.map((d) => terminal.has(d.state) ? { ...d, originals: d.originals.map(cut), out: d.out.map(cut) } : d),
289
+ },
290
+ };
291
+ }
292
+
293
+ /** Undo the single-stored `seen` on read. */
294
+ export function expandRestartBus(bus: BusSnapshot): BusSnapshot {
295
+ if (!bus.journal || bus.journal.bus.seen.length) return bus;
296
+ return { ...bus, journal: { ...bus.journal, bus: { ...bus.journal.bus, seen: bus.seen } } };
250
297
  }
@@ -9,6 +9,7 @@ import { childEnv } from "./child-process.ts";
9
9
  import { hubHome, realPath } from "./project.ts";
10
10
  import { readProjectRuntimeReference, projectRuntimeFile } from "./project-runtime-state.ts";
11
11
  import { Registry, REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
12
+ import { anyRecoveryHold, retireOperation } from "./recovery-store.ts";
12
13
 
13
14
  export interface RuntimeCapturePrunePlan { remove: string[]; kept: string[]; deferred?: string }
14
15
  export interface RuntimeCapturePruneResult { removed: string[]; kept: string[]; quarantined?: string[]; deferred?: string }
@@ -24,6 +25,13 @@ const MAX_INVENTORY_BYTES = 16 * 1024 * 1024;
24
25
  // ponytail: larger inventories defer; upgrade to indexed/batched reference inventory, never larger lock/busy limits.
25
26
  const MAX_PROJECTS = 128, MAX_RECEIPTS = 128, MAX_CAPTURE_ENTRIES = 512, MAX_REFERENCE_FILES = 512;
26
27
  const LOCK_METADATA_MS = 250;
28
+ /** #1541: finished receipts the hub keeps (newest first), and the extra newest-per-selected-runtime ones; both stay far below MAX_RECEIPTS. */
29
+ export const RETAINED_TERMINAL_RECEIPTS = 32, RETAINED_SELECTED_RECEIPTS = 64;
30
+ // ponytail: one pass retires at most this many receipts and reads at most this many directory entries; a larger backlog drains over later passes.
31
+ const MAX_RETIRED_PER_PASS = 256, MAX_RECEIPT_SCAN_ENTRIES = 4096, MAX_RECEIPT_BYTES = 1024 * 1024, MAX_RECEIPT_SCAN_BYTES = 64 * 1024 * 1024;
32
+ const RUNNER_DB = /^[a-f0-9-]{36}\.json\.runner\.db$/;
33
+ /** What a deferral for the receipt ceiling starts with; doctor keys on it to add the retention rule. */
34
+ export const RECEIPT_CEILING_REASON = `recovery receipts exceed the ${MAX_RECEIPTS} receipt safety ceiling`;
27
35
  export const RUNTIME_PRUNE_MAX_BATCH = 3;
28
36
  export const RUNTIME_PRUNE_INTERVAL_MS = 60 * 60 * 1000;
29
37
  const RUNTIME_PRUNE_ADMISSION_BUSY_TIMEOUT_MS = 1;
@@ -166,14 +174,15 @@ function observeReferences(home: string, registry: Registry): Observation {
166
174
  observeDatabase(locks, observation, db => { if (db.query("SELECT 1 FROM project_locks LIMIT 1").get()) fail("project recovery coordination is present"); });
167
175
  }
168
176
  let receipts = 0;
169
- for (const entry of entries(recovery, observation)) {
177
+ const rows = entries(recovery, observation);
178
+ for (const entry of rows) {
170
179
  if (!entry.name.endsWith(".json")) continue;
171
- if (++receipts > MAX_RECEIPTS) fail("recovery receipt inventory exceeds its bound");
180
+ if (++receipts > MAX_RECEIPTS) fail(receiptCeilingRefusal(recovery, rows));
172
181
  if (OPERATION.exec(entry.name)?.[0] !== entry.name || !entry.isFile() || entry.isSymbolicLink()) fail("recovery receipt inventory is invalid");
173
182
  const record = metadata(join(recovery, entry.name), observation);
174
183
  if (!object(record) || ![1, 2, 3].includes(record.schema as number) || `${record.id}.json` !== entry.name
175
184
  || !["pending", "running", "blocked", "completed", "cancelled"].includes(record.phase as string)) fail("recovery receipt inventory is invalid");
176
- if (record.phase !== "completed" && record.phase !== "cancelled") fail("a retained recovery operation is not terminal");
185
+ if (record.phase !== "completed" && record.phase !== "cancelled") fail(`a retained recovery operation is not terminal: run ahub recovery status ${record.id}, then resume or abort it`);
177
186
  if (!object(record.plan) || !Array.isArray(record.plan.projects) || !Array.isArray(record.projects)
178
187
  || record.plan.projects.length !== record.projects.length || !["restart", "upgrade"].includes(record.plan.kind as string)
179
188
  || typeof record.plan.sourceDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.plan.sourceDigest)) fail("retained recovery runtime references are incomplete");
@@ -191,6 +200,21 @@ function observeReferences(home: string, registry: Registry): Observation {
191
200
  }
192
201
  return observation;
193
202
  }
203
+ /** AC4: the cause and a supported command. Only open receipts can hold the count above the ceiling, so name the first one found. */
204
+ function receiptCeilingRefusal(recovery: string, rows: Dirent[]): string {
205
+ const scratch: Observation = { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 };
206
+ let first: string | undefined;
207
+ for (const row of rows) {
208
+ if (!row.name.endsWith(".json") || !OPERATION.test(row.name)) continue;
209
+ try {
210
+ const record = metadata(join(recovery, row.name), scratch);
211
+ if (object(record) && record.phase !== "completed" && record.phase !== "cancelled") { first = row.name.slice(0, -".json".length); break; }
212
+ } catch { /* an unreadable receipt is reported by the generic refusal below */ }
213
+ }
214
+ const next = first ? `run ahub recovery status ${first}, then ahub recovery resume ${first} or ahub recovery abort ${first}`
215
+ : "no open receipt was found, so the next maintenance pass (after a hub start, at most hourly) removes the finished ones; ahub recovery status <operation-id> shows one the hub keeps";
216
+ return `${RECEIPT_CEILING_REASON}: the hub keeps open receipts and removes finished ones itself; ${next}`;
217
+ }
194
218
  function validateObservation(registry: Registry, observation: Observation, budget: LockBudget): void {
195
219
  tick(budget);
196
220
  if (JSON.stringify(registry.list()) !== observation.projects) fail("project runtime registry changed before pruning");
@@ -269,6 +293,92 @@ function openRegistry(home: string): { home: string; registry: Registry } {
269
293
  const deferred = (error: unknown): string => `runtime capture pruning deferred: ${error instanceof Error ? error.message : "inventory unavailable"}`;
270
294
  function checkRetention(keepNewest: number): void { if (!Number.isSafeInteger(keepNewest) || keepNewest < 0) fail("runtime capture retention must be a nonnegative integer"); }
271
295
 
296
+ interface ReceiptRow { name: string; id: string; at: number; roots: string[] }
297
+ function receiptRoot(value: unknown): string | undefined {
298
+ if (typeof value !== "string" || !isAbsolute(value) || value.includes(String.fromCharCode(0))) return undefined;
299
+ try { return realPath(value); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; return resolve(value); }
300
+ }
301
+ function readReceipt(file: string, budget: { bytes: number }): unknown {
302
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
303
+ try {
304
+ const info = fstatSync(fd);
305
+ if (!info.isFile() || info.nlink !== 1 || info.size > MAX_RECEIPT_BYTES || budget.bytes + info.size > MAX_RECEIPT_SCAN_BYTES) return undefined;
306
+ const bytes = Buffer.alloc(info.size), count = readSync(fd, bytes, 0, info.size, 0);
307
+ if (count !== info.size) return undefined;
308
+ budget.bytes += count;
309
+ try { return JSON.parse(bytes.toString("utf8")); } catch { return undefined; }
310
+ } finally { closeSync(fd); }
311
+ }
312
+ const terminalReceipt = (record: unknown, name: string): record is Record<string, unknown> =>
313
+ object(record) && [1, 2, 3].includes(record.schema as number) && `${record.id}.json` === name && OPERATION.test(name) && (record.phase === "completed" || record.phase === "cancelled");
314
+ /** Runtime roots a registered project's runtime.json (or the live manager) selects, canonical; undefined when any of them cannot be read, which stops retention. */
315
+ function selectedRuntimeRoots(home: string, registry: Registry): string[] | undefined {
316
+ try {
317
+ const roots: string[] = [], projects = registry.list();
318
+ if (projects.length > MAX_PROJECTS) return undefined;
319
+ for (const project of projects) { const runtime = readProjectRuntimeReference(project); if (runtime) roots.push(realPath(runtime.root)); }
320
+ const manager = managerRuntimeRoot(home, { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 });
321
+ if (manager) roots.push(manager);
322
+ return roots;
323
+ } catch { return undefined; }
324
+ }
325
+ /**
326
+ * #1541: the hub's own retention rule for finished recovery receipts. Keeps every receipt that is not terminal, the newest
327
+ * RETAINED_TERMINAL_RECEIPTS terminal ones, and the newest RETAINED_SELECTED_RECEIPTS terminal ones that name a runtime a
328
+ * registered project (or the live manager) still selects. The rest leave with their `.runner.db` through
329
+ * `retireOperation` (the exclusive runner claim, never check-then-unlink). The captures themselves stay protected by
330
+ * runtime.json, not by a receipt, so retention never releases one a project selects. Skips everything while any recovery hold exists.
331
+ */
332
+ export function retireTerminalReceipts(home: string, registry: Registry, hooks: { betweenPair?: () => void } = {}): number {
333
+ const recovery = join(home, "recovery");
334
+ if (!directory(recovery) || anyRecoveryHold(home)) return 0;
335
+ const selected = selectedRuntimeRoots(home, registry);
336
+ if (!selected) return 0;
337
+ const names: string[] = [], handle = opendirSync(recovery);
338
+ try {
339
+ for (;;) {
340
+ const entry = handle.readSync(); if (!entry) break;
341
+ if (names.length >= MAX_RECEIPT_SCAN_ENTRIES) return 0;
342
+ if (entry.isFile() && (entry.name.endsWith(".json") || RUNNER_DB.test(entry.name))) names.push(entry.name);
343
+ }
344
+ } finally { handle.closeSync(); }
345
+ const budget = { bytes: 0 }, terminal: ReceiptRow[] = [], receipts = new Set<string>();
346
+ for (const name of names) {
347
+ if (!name.endsWith(".json")) continue;
348
+ receipts.add(name);
349
+ let record: unknown;
350
+ try { record = readReceipt(join(recovery, name), budget); } catch { continue; }
351
+ if (!terminalReceipt(record, name)) continue; // open, unreadable or unknown receipts always stay
352
+ const roots: string[] = [];
353
+ try {
354
+ for (const value of [record.sourceRoot, object(record.plan) ? record.plan.sourceRoot : undefined, record.targetRoot]) { const root = receiptRoot(value); if (root) roots.push(root); }
355
+ } catch { continue; }
356
+ const at = Number.isFinite(record.updatedAt) ? record.updatedAt as number : Number.isFinite(record.createdAt) ? record.createdAt as number : 0;
357
+ terminal.push({ name, id: record.id as string, at, roots });
358
+ }
359
+ terminal.sort((a, b) => b.at - a.at || b.id.localeCompare(a.id));
360
+ const keep = new Set(terminal.slice(0, RETAINED_TERMINAL_RECEIPTS).map(row => row.name));
361
+ let extra = 0;
362
+ for (const row of terminal) {
363
+ if (extra >= RETAINED_SELECTED_RECEIPTS) break;
364
+ if (keep.has(row.name) || !selected.some(root => row.roots.some(own => contains(root, own) || contains(own, root)))) continue;
365
+ keep.add(row.name); extra++;
366
+ }
367
+ let retired = 0;
368
+ for (const row of terminal) {
369
+ if (keep.has(row.name)) continue;
370
+ if (retired >= MAX_RETIRED_PER_PASS) break;
371
+ const outcome = retireOperation(row.id, home, record => terminalReceipt(record, row.name), hooks);
372
+ if (outcome === "retired") retired++;
373
+ }
374
+ // A runner db whose receipt is gone (an interrupted earlier pass) is settled through the same claim; a live claim keeps it.
375
+ for (const name of names) {
376
+ const receipt = name.replace(/\.runner\.db$/, "");
377
+ if (RUNNER_DB.test(name) && !receipts.has(receipt) && retired < MAX_RETIRED_PER_PASS && retireOperation(receipt.slice(0, -".json".length), home, () => false, hooks) === "retired") retired++;
378
+ }
379
+ return retired;
380
+ }
381
+
272
382
  /** Metadata preview only; execution always refreshes reference observations before quarantining each candidate. */
273
383
  export function planRuntimeCapturePrune(home = hubHome(), keepNewest = 3): RuntimeCapturePrunePlan {
274
384
  let registry: Registry | undefined;
@@ -283,6 +393,7 @@ export function pruneRuntimeCaptures(home = hubHome(), keepNewest = 3): RuntimeC
283
393
  const removed: string[] = [], quarantined: string[] = []; let kept: string[] = [], registry: Registry | undefined;
284
394
  try {
285
395
  checkRetention(keepNewest); const opened = openRegistry(home); registry = opened.registry; home = opened.home;
396
+ retireTerminalReceipts(home, registry);
286
397
  const initial = lockedPlan(home, registry, observeReferences(home, registry), keepNewest); kept = initial.plan.kept;
287
398
  // Reject unknown layouts across the small batch before moving any entry; no package contents are hashed here.
288
399
  for (const root of initial.plan.remove) captureLayout(root);
@@ -363,14 +474,20 @@ function admissionRow(db: Database): Admission | undefined {
363
474
  || row.signature !== null && (typeof row.signature !== "string" || !row.signature.trim() || Buffer.byteLength(row.signature) > 1024))) fail("runtime maintenance admission state is invalid");
364
475
  return rows[0];
365
476
  }
477
+ /** A prune that only found recovery coordination present did nothing: it is not a completed pass (#1546). */
478
+ export const RECOVERY_DEFERRAL = /recovery coordination is present/;
366
479
  function admitSchedule(home: string): string | undefined {
367
480
  const db = startupAdmissionDatabase(home);
368
481
  try {
369
482
  return db.transaction(() => {
370
483
  const previous = admissionRow(db), now = Date.now();
484
+ // A pass deferred only by recovery coordination starts no cooldown: the next schedule (after the lock is released) may run at once.
485
+ const recoveryOnly = previous?.phase === "complete" && (() => {
486
+ try { const o = db.query("SELECT outcome FROM admission WHERE slot=1").get() as { outcome: string | null } | null; return typeof JSON.parse(o?.outcome ?? "{}").deferred === "string" && RECOVERY_DEFERRAL.test(JSON.parse(o!.outcome!).deferred); } catch { return false; }
487
+ })();
371
488
  const dead = previous?.phase === "running" && previous.pid !== null && previous.signature !== null
372
489
  && processLiveness(previous.pid, previous.signature) === "gone";
373
- if (previous && (previous.phase === "running" && !dead || !dead && now - previous.admitted_at < RUNTIME_PRUNE_INTERVAL_MS)) return undefined;
490
+ if (previous && (previous.phase === "running" && !dead || !dead && !recoveryOnly && now - previous.admitted_at < RUNTIME_PRUNE_INTERVAL_MS)) return undefined;
374
491
  const id = randomUUID();
375
492
  db.query("INSERT OR REPLACE INTO admission(slot,id,admitted_at,phase,pid,outcome,signature) VALUES(1,?,?,'scheduled',NULL,NULL,NULL)").run(id, now);
376
493
  return id;
@@ -386,6 +503,8 @@ export function scheduleRuntimeCapturePrune(home?: string): void {
386
503
  setImmediate(() => {
387
504
  try {
388
505
  const targetHome = home ?? hubHome({ AGENTHUB_HOME: inheritedHome });
506
+ // Never schedule a pass that is bound to defer: while any recovery hold exists (or it cannot be read) the runner schedules one after its release.
507
+ if (anyRecoveryHold(targetHome, true)) return; // non-blocking: a locked project-locks.db is a hold, never a wait on the startup loop
389
508
  const id = admitSchedule(targetHome); if (!id) return;
390
509
  const env = childEnv(process.env);
391
510
  for (const key of Object.keys(env)) if (key.startsWith("ORCA_") || ["AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR", "AGENTHUB_PEER_ID", "AGENTHUB_CHANNEL", "CLAUDECODE", "CODEX_THREAD_ID"].includes(key)) delete env[key];
@@ -4,12 +4,14 @@ import { isAbsolute, join, normalize } from "node:path";
4
4
  import { processLiveness } from "../pi/process-signature.ts";
5
5
  import { hubHome } from "./project.ts";
6
6
  import { REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
7
- import { RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
7
+ import { RECOVERY_DEFERRAL, RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
8
8
 
9
9
  export interface RuntimePruneHealthCheck { ok: boolean | undefined; name: string; detail: string }
10
10
  const MAX_LEDGER_BYTES = 1024 * 1024, MAX_OUTCOME_BYTES = 16 * 1024;
11
11
  const MAX_SCAN_ENTRIES = 1024, MAX_QUARANTINES = 64, SCAN_MS = 250;
12
12
  const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
13
+ /** #1541: the one retention rule, as docs/operations.md states it. */
14
+ export const RECEIPT_RETENTION_RULE = `Retention: maintenance keeps every open recovery receipt, the newest ${RETAINED_TERMINAL_RECEIPTS} finished ones and up to ${RETAINED_SELECTED_RECEIPTS} finished ones naming a runtime a project still selects, and removes older finished ones with their runner database itself`;
13
15
  const columns = "slot,id,admitted_at,phase,pid,outcome";
14
16
  const issue = (detail: string, ok: boolean | undefined = undefined): RuntimePruneHealthCheck => ({ ok, name: "runtime pruning", detail });
15
17
  const info = (file: string): Stats | undefined => {
@@ -62,8 +64,14 @@ function admissionHealth(file: string): LedgerHealth {
62
64
  || !Number.isSafeInteger(outcome.removed) || (outcome.removed as number) < 0 || !Array.isArray(outcome.quarantined) || outcome.quarantined.length > MAX_QUARANTINES
63
65
  || outcome.quarantined.some(value => typeof value !== "string" || value.length > 4096 || isAbsolute(value) || normalize(value) !== value || value.split(/[\\/]/).some(part => part === ".."))
64
66
  || outcome.deferred !== undefined && (typeof outcome.deferred !== "string" || Buffer.byteLength(outcome.deferred) > 512)) throw new Error("invalid completed outcome");
67
+ if (typeof outcome.deferred === "string" && RECOVERY_DEFERRAL.test(outcome.deferred) && !outcome.quarantined.length) {
68
+ // #1546: a pass that only found recovery coordination present did nothing and is retried after the lock is released: not a failure.
69
+ return { checks: [issue("maintenance was deferred while recovery coordination was present; it is scheduled again after the recovery lock is released", true)], active: false };
70
+ }
65
71
  if (outcome.deferred !== undefined || outcome.quarantined.length) {
66
- const detail = typeof outcome.deferred === "string" ? `maintenance deferred: ${outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ")}; inspect ${file}` : `maintenance retained quarantine paths; inspect ${file}`;
72
+ // #1541: a deferral that already names a supported command (the receipt ceiling, an open operation) is not sent to the ledger.
73
+ const text = typeof outcome.deferred === "string" ? outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ") : undefined;
74
+ const detail = text !== undefined ? `maintenance deferred: ${text}${text.includes("ahub recovery") ? `. ${RECEIPT_RETENTION_RULE}` : `; inspect ${file}`}` : `maintenance retained quarantine paths; inspect ${file}`;
67
75
  return { active: false, checks: [issue(detail, false)] };
68
76
  }
69
77
  return { checks: [], active: false };
@@ -50,6 +50,8 @@ export interface MergeOutcome {
50
50
  result?: { exit: number; state: "merged" | "not_merged" | "unknown"; mergeCommit?: string; cleanup?: MergeRecord["cleanup"]; reason?: MergeRecord["reason"] };
51
51
  }
52
52
 
53
+ export const MERGE_READBACK_INTERVAL_MS = 5 * 60_000;
54
+ export const MERGE_READBACK_DEADLINE_MS = 8_000;
53
55
  const SHA = /^[0-9a-f]{40}$/;
54
56
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
55
57
  /**
@@ -92,10 +94,10 @@ function checkGates(evidence: PrEvidence, required: readonly string[], extra: re
92
94
  }
93
95
 
94
96
  /** One bounded GitHub snapshot for adoption: no bodies, no merge or cleanup mutation, and complete head-bound review/check coverage. */
95
- export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh): Promise<PrEvidence | undefined> {
97
+ export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh): Promise<(PrEvidence & { costSnapshot?: unknown }) | undefined> {
96
98
  if (!REPO.test(receipt.repo ?? "") || receipt.repo!.startsWith("-") || !Number.isSafeInteger(receipt.pr) || receipt.pr! <= 0) return undefined;
97
99
  const [owner, name] = receipt.repo!.split("/");
98
- const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state reviewDecision isDraft mergeCommit{oid} reviewRequests(first:100){nodes{requestedReviewer{__typename}} pageInfo{hasNextPage}} reviewThreads(first:100){nodes{isResolved} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
100
+ const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){number headRefOid state mergedAt reviews(first:100){nodes{databaseId commit{oid}} pageInfo{hasNextPage}} costCommits:commits(first:100){nodes{commit{oid}} pageInfo{hasNextPage}} reviewDecision isDraft mergeCommit{oid} reviewRequests(first:100){nodes{requestedReviewer{__typename}} pageInfo{hasNextPage}} reviewThreads(first:100){nodes{isResolved} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
99
101
  try {
100
102
  const result = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${receipt.pr}`]);
101
103
  if (result.code !== 0) return undefined;
@@ -113,7 +115,9 @@ export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh):
113
115
  return check.state === "passed" && !green ? { ...check, state: "unknown" } : check;
114
116
  });
115
117
  // Files are outside adoption's decision. Keep their coverage explicitly unknown in the shared evidence shape.
116
- return { ...evidence, pathsComplete: false, typesComplete: false };
118
+ const costSnapshot = pr.number === receipt.pr && typeof pr.mergedAt === "string" && pr.costCommits && pr.reviews
119
+ ? { ...pr, commits: pr.costCommits } : undefined;
120
+ return { ...evidence, pathsComplete: false, typesComplete: false, ...(costSnapshot ? { costSnapshot } : {}) };
117
121
  } catch { return undefined; }
118
122
  }
119
123
 
@@ -1,6 +1,6 @@
1
1
  // #481 S7: SDLC metrics and deterministic control bands. Pure: board history in, numbers out. No I/O, no clock, no model.
2
2
  // A metric that cannot be derived is `unknown` and counted as such, never 0.
3
- // `first_pass_check` reads the hub's own completion check (`check passed` / `check failed` at hub_task_done), not PR CI: it is unknown where completion checks are off.
3
+ // `first_pass_check` prefers the completion check, then the latest isolated run before the first done at the same head.
4
4
 
5
5
  export const BAND_METRICS = ["acceptance_to_plan_ms", "acceptance_to_first_review_ms", "first_pass_approval", "rework_rounds", "first_pass_check", "stale_head_re_reviews", "hotfix_rate", "security_open_alerts"] as const;
6
6
  export type BandMetric = typeof BAND_METRICS[number];
@@ -14,7 +14,7 @@ export type BandTier = typeof BAND_TIERS[number];
14
14
  export interface MetricTask {
15
15
  id: number;
16
16
  private?: boolean;
17
- /** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (reviewCost.head); `verdictHead` the head a verdict was bound to (reviewFindings.head). Compared for equality only, never printed. */
17
+ /** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (requestHead, with historical fallbacks); `verdictHead` the head a verdict was bound to (reviewFindings.head). Compared for equality only, never printed. */
18
18
  history: { at: number; event: string; requestHead?: string; verdictHead?: string; evidenceOnly?: true }[];
19
19
  }
20
20
 
@@ -26,6 +26,7 @@ export interface TaskSample {
26
26
  /** When the task was approved, else null: `rework_rounds` and `stale_head_re_reviews` are final only then, and sit at this time in their series. */
27
27
  approved_at: number | null;
28
28
  acceptance_to_plan_ms: number | null;
29
+ accepted_to_plan_ms: number | null;
29
30
  acceptance_to_first_review_ms: number | null;
30
31
  acceptance_to_merge_ms: number | null;
31
32
  first_pass_approval: 0 | 1 | null;
@@ -84,7 +85,7 @@ const VERDICTS = ["approved", "changes_requested"];
84
85
  * Review rounds whose verdict was bound to a different head than the review was requested for: the head moved while the review ran.
85
86
  * Known only for a round with both heads recorded; a task with no such round is unknown, never 0. (A `done` after an `approved` is not
86
87
  * evidence: the board cannot produce one.)
87
- * ponytail: the request head is `reviewCost.head` (the commit the done named first) while a verdict's head prefers the lifecycle receipt's
88
+ * ponytail: the request head is the commit recorded for the done while a verdict's head prefers the lifecycle receipt's
88
89
  * `head`/`localHead` over `refs.commit` (`findingHead`), so a receipt head that differs from the commit can read as stale. Ceiling: a
89
90
  * spurious stale round for a task whose receipt head and commit disagree; the upgrade is one shared head rule for both sides.
90
91
  */
@@ -105,26 +106,33 @@ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciRerun
105
106
  const history = [...task.history].filter(entry => Number.isFinite(entry.at) && entry.at >= 0).sort((a, b) => a.at - b.at);
106
107
  const view: MetricTask = { id: task.id, history };
107
108
  const accepted = first(view, ["accepted"]);
108
- const spec = first(view, ["spec accepted"]);
109
+ const spec = first(view, ["spec accepted", "spec acceptance carried"]);
109
110
  const plan = spec ? first(view, ["plan reviewed"], spec.at) : undefined;
111
+ const acceptedPlan = !spec && accepted ? first(view, ["plan reviewed"], accepted.at) : undefined;
110
112
  const verdict = accepted ? first(view, VERDICTS, accepted.at) : first(view, VERDICTS);
111
113
  // Evidence-only still ends the actual wait for a first review, but says nothing about whether the work passed.
112
114
  const substantiveVerdict = history.find(entry => entry.at >= (accepted?.at ?? -Infinity) && VERDICTS.includes(entry.event) && entry.evidenceOnly !== true);
113
115
  const dones = history.filter(entry => entry.event === "done");
114
- const ci = first(view, ["check passed", "check failed"]);
116
+ const completionCheck = first(view, ["check passed", "check failed"]);
117
+ const firstDone = history.findIndex(entry => entry.event === "done");
118
+ const doneHead = firstDone >= 0 ? history[firstDone]?.requestHead : undefined;
119
+ const latestRun = doneHead ? history.slice(0, firstDone).findLast(entry => entry.event === "check run passed" || entry.event === "check run failed") : undefined;
120
+ const isolatedCheck = latestRun?.requestHead === doneHead ? latestRun : undefined;
121
+ const ci = completionCheck ?? isolatedCheck;
115
122
  const approvedAt = history.find(entry => entry.event === "approved")?.at ?? null;
116
123
  return {
117
124
  id: task.id,
118
125
  at: verdict?.at ?? accepted?.at ?? history[0]?.at ?? 0,
119
126
  approved_at: approvedAt,
120
127
  acceptance_to_plan_ms: spec && plan ? plan.at - spec.at : null,
128
+ accepted_to_plan_ms: accepted && acceptedPlan ? acceptedPlan.at - accepted.at : null,
121
129
  acceptance_to_first_review_ms: accepted && verdict ? verdict.at - accepted.at : null,
122
130
  acceptance_to_merge_ms: accepted && extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) && extra.mergedAt >= accepted.at ? extra.mergedAt - accepted.at : null,
123
131
  first_pass_approval: substantiveVerdict ? (substantiveVerdict.event === "approved" ? 1 : 0) : null,
124
132
  // Rework grows with every round, so it is a value only once the task is approved: a task still in flight has no final one, and a
125
133
  // provisional point would move at each verdict and could start a second breach episode inside one shift.
126
134
  rework_rounds: dones.length && approvedAt !== null ? history.filter(entry => entry.event === "changes_requested" && entry.evidenceOnly !== true).length : null,
127
- first_pass_check: ci ? (ci.event === "check passed" ? 1 : 0) : null,
135
+ first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : null,
128
136
  same_head_ci_reruns: extra.ciReruns === undefined ? null : extra.ciReruns,
129
137
  // Counted only for a merged PR whose figures were read: a done before the merge is one review round.
130
138
  review_rounds_at_merge: extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) ? dones.filter(entry => entry.at <= extra.mergedAt!).length : null,
@@ -202,8 +210,9 @@ export interface MetricsReport {
202
210
  since: number | null;
203
211
  tasks: number;
204
212
  withheldPrivate: number;
213
+ securityScan?: Record<string, number | null>;
205
214
  metrics: {
206
- acceptance_to_plan_ms: Summary; acceptance_to_first_review_ms: Summary; acceptance_to_merge_ms: Summary;
215
+ acceptance_to_plan_ms: Summary; accepted_to_plan_ms: Summary; acceptance_to_first_review_ms: Summary; acceptance_to_merge_ms: Summary;
207
216
  first_pass_approval: { n: number; unknown: number; rate: number | null };
208
217
  rework_rounds: Summary;
209
218
  first_pass_check: { n: number; unknown: number; rate: number | null };
@@ -236,7 +245,7 @@ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number
236
245
  return {
237
246
  since: opts.since ?? null, tasks: samples.length, withheldPrivate: tasks.length - visible.length,
238
247
  metrics: {
239
- acceptance_to_plan_ms: summarize(samples.map(s => s.acceptance_to_plan_ms)), acceptance_to_first_review_ms: summarize(samples.map(s => s.acceptance_to_first_review_ms)),
248
+ acceptance_to_plan_ms: summarize(samples.map(s => s.acceptance_to_plan_ms)), accepted_to_plan_ms: summarize(samples.map(s => s.accepted_to_plan_ms)), acceptance_to_first_review_ms: summarize(samples.map(s => s.acceptance_to_first_review_ms)),
240
249
  acceptance_to_merge_ms: summarize(samples.map(s => s.acceptance_to_merge_ms)),
241
250
  first_pass_approval: rate(samples.map(s => s.first_pass_approval)), rework_rounds: summarize(samples.map(s => s.rework_rounds)),
242
251
  first_pass_check: rate(samples.map(s => s.first_pass_check)), same_head_ci_reruns: summarize(samples.map(s => s.same_head_ci_reruns)),