@staix/agent-hub 0.43.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 (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -1
  3. package/docs/agent-notes/daemon.md +3 -3
  4. package/docs/agent-notes/local-worker.md +1 -0
  5. package/docs/agent-notes/tasks.md +2 -1
  6. package/docs/agent-notes/tests.md +1 -1
  7. package/docs/design/agent-hub-architecture.md +2 -0
  8. package/docs/design/supervision.md +13 -1
  9. package/docs/design/task-board.md +7 -1
  10. package/docs/dogfood.md +8 -2
  11. package/docs/events.md +4 -2
  12. package/docs/memory.md +3 -3
  13. package/docs/operations.md +37 -17
  14. package/docs/quickstart.md +8 -2
  15. package/docs/research.md +2 -0
  16. package/docs/sdlc.md +5 -2
  17. package/docs/security.md +2 -2
  18. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  19. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  20. package/docs/verified.json +22 -22
  21. package/package.json +2 -2
  22. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  23. package/plugins/agent-hub/kimi-hook.js +183 -105
  24. package/plugins/agent-hub/server.js +202 -121
  25. package/src/cli/main.ts +1 -1
  26. package/src/cli/output.ts +2 -2
  27. package/src/cli/sdlc-output.ts +7 -1
  28. package/src/cli/upgrade.ts +9 -3
  29. package/src/hub/board.ts +14 -1
  30. package/src/hub/bus.ts +4 -0
  31. package/src/hub/claude-shell-wrapper.ts +2 -1
  32. package/src/hub/control-write-trace.ts +39 -2
  33. package/src/hub/daemon.ts +66 -24
  34. package/src/hub/facts.ts +30 -0
  35. package/src/hub/hub-tools.ts +1 -1
  36. package/src/hub/quota-events.ts +40 -0
  37. package/src/hub/recovery-store.ts +21 -3
  38. package/src/hub/report.ts +1 -1
  39. package/src/hub/research-quality.ts +5 -1
  40. package/src/hub/research-record.ts +3 -2
  41. package/src/hub/restart.ts +49 -2
  42. package/src/hub/runtime-capture-prune.ts +9 -1
  43. package/src/hub/runtime-prune-health.ts +5 -1
  44. package/src/hub/sdlc-merge.ts +7 -3
  45. package/src/hub/sdlc-metrics.ts +15 -6
  46. package/src/hub/sdlc.ts +18 -6
  47. package/src/hub/snapshots.ts +43 -0
  48. package/src/hub/supervision-rules.ts +2 -2
  49. package/src/hub/task-shell-command.ts +124 -0
  50. package/src/hub/tasks.ts +124 -20
  51. package/src/hub/worktree-shelf.ts +2 -1
  52. package/src/local/sandbox.ts +2 -1
  53. package/src/local/shell-environment.ts +6 -0
  54. package/src/memory/brief.ts +10 -1
package/src/hub/facts.ts CHANGED
@@ -139,6 +139,9 @@ export interface Offered {
139
139
  coverage?: boolean;
140
140
  }
141
141
 
142
+ export const MAX_RECEIPTS_PER_PEER = 256;
143
+ export interface ReadReceipt { sha256: string; scope: "full" | "partial"; at: number; turnId: string }
144
+
142
145
  export class Facts {
143
146
  private readonly latest = new Map<string, Version>();
144
147
  private readonly transitions = new Map<string, Transition[]>();
@@ -185,6 +188,8 @@ export class Facts {
185
188
  private readonly covered = new Set<PeerId>();
186
189
  /** Each peer's native session or thread: a new one starts its views over. */
187
190
  private readonly sessions = new Map<PeerId, string>();
191
+ /** Read receipts, memory only (#1556 T1): peer -> "task\0path" -> receipt, insertion order is the LRU order. */
192
+ private readonly receipts = new Map<PeerId, Map<string, ReadReceipt>>();
188
193
  /** When tracking began: work on a task handed over before that is not covered. */
189
194
  private epoch = Date.now();
190
195
  private readonly root: string;
@@ -294,9 +299,29 @@ export class Facts {
294
299
  this.seenDropped.clear();
295
300
  this.unfollowed.clear(); // what was seen is forgotten: a notice about it would be stale
296
301
  this.writes.clear();
302
+ this.receipts.clear();
297
303
  this.epoch = Date.now();
298
304
  }
299
305
 
306
+ /** Record what `peer` read of `path` for `task`; bounded per peer, oldest evicted. Never persisted. */
307
+ recordRead(peer: PeerId, task: number, path: string, r: Omit<ReadReceipt, "at"> & { at?: number }): void {
308
+ let m = this.receipts.get(peer);
309
+ if (!m) this.receipts.set(peer, (m = new Map()));
310
+ const key = `${task}\0${path}`;
311
+ m.delete(key);
312
+ m.set(key, { ...r, at: r.at ?? Date.now() });
313
+ while (m.size > MAX_RECEIPTS_PER_PEER) m.delete(m.keys().next().value as string);
314
+ }
315
+
316
+ readReceipt(peer: PeerId, task: number, path: string): ReadReceipt | undefined {
317
+ return this.receipts.get(peer)?.get(`${task}\0${path}`);
318
+ }
319
+
320
+ /** The task closed: its receipts go. */
321
+ closeTask(task: number): void {
322
+ for (const m of this.receipts.values()) for (const k of [...m.keys()]) if (k.startsWith(`${task}\0`)) m.delete(k);
323
+ }
324
+
300
325
  /** A new native session or thread for `peer`: what the old one saw says nothing about the new one. */
301
326
  session(peer: PeerId, id: string | undefined): void {
302
327
  if (!id) return;
@@ -580,6 +605,11 @@ export class Facts {
580
605
  return this.observeAll();
581
606
  }
582
607
  if (tool === "Read") {
608
+ // #1556 T1: a read receipt per (peer, task, path), memory only. Unknown text (large or unreadable file) records nothing, never a guess.
609
+ const task = this.o.scope(peer)?.task?.id;
610
+ if (task !== undefined && pre.version.text !== undefined) {
611
+ this.recordRead(peer, task, file, { sha256: createHash("sha256").update(pre.version.text).digest("hex"), scope: input.offset === undefined && input.limit === undefined && readWhole(pre.version.text) ? "full" : "partial", turnId: toolUseId ?? "" });
612
+ }
583
613
  const version = this.observe(file);
584
614
  // Only a whole read of an unchanged file says what the peer saw: no offset or limit, and nothing Read cuts.
585
615
  if (!pre.version.projected && version.hash === pre.version.hash && input.offset === undefined && input.limit === undefined && readWhole(pre.version.text)) this.view(peer).set(file, version);
@@ -263,7 +263,7 @@ export const TASK_TOOLS: HubTool[] = [
263
263
  tool("hub_delivery_resolve", "Confirm completion or discard your own needs_review delivery using the revision shown by hub_inbox. Requires a reason. Never replays the delivery or changes task state; another peer's row and stale revisions are refused.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "integer", minimum: 0 }, action: { type: "string", enum: ["completed", "discard"] }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["delivery_id", "revision", "action", "reason"]),
264
264
  tool("hub_backlog_list", "Read public backlog cards with planning revisions. Configured planners only; PII remains a stub.", {}),
265
265
  tool("hub_backlog_plan", "Plan an unpinned backlog item outside frozen releases with the revision you read and a bounded reason. Omit fields or give {} for a note-only revision. fields.sdlc accepts only repo/issue identity on unstarted backlog work; relinking clears old spec acceptance. A person's rank is retained. Actual dates cannot be set. fields.needsPerson (marking a leg only the person can run) is the person's: an agent that sends it, or plans a marked card, is refused.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", maxLength: 1000 }, fields: { type: "object", properties: { sdlc: { type: "object", minProperties: 1, properties: { repo: { type: ["string", "null"], maxLength: 400 }, issue: { type: ["integer", "null"], minimum: 1 } }, additionalProperties: false }, rank: { type: ["integer", "null"], minimum: 0 }, priority: { type: ["integer", "null"], minimum: 0, maximum: 3 }, release: { type: ["integer", "null"], minimum: 1 }, plannedStart: { type: ["integer", "null"], minimum: 1 }, due: { type: ["integer", "null"], minimum: 1 }, deps: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, reserved: { type: ["string", "null"], minLength: 1, maxLength: 32 }, needsPerson: { type: "boolean" } }, additionalProperties: false } }, ["id", "revision", "reason"]),
266
- tool("hub_backlog_pull", "Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
266
+ tool("hub_backlog_pull", "Configured planners only. Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
267
267
  tool("hub_backlog_split", "Split unstarted backlog work into two to eight staged parts. The original card retains integration/acceptance and depends on the children. Use after for existing prerequisite ids and afterParts for earlier zero-based part indexes. Latest unused unchanged children can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 }, parts: { type: "array", minItems: 2, maxItems: 8, items: { type: "object", properties: { title: { type: "string", minLength: 1, maxLength: 300 }, detail: { type: "string", maxLength: 8000 }, class: str, refs, plan, after: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, afterParts: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "integer", minimum: 0 } } }, required: ["title"], additionalProperties: false } } }, ["id", "revision", "reason", "parts"]),
268
268
  tool("hub_backlog_undo", "Undo your latest planning change at its current revision. Refuses intervening changes and another actor's edit.", { id, revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
269
269
  tool("hub_study_draft", "Store a research campaign contract as a DRAFT revision 1 on an approved parent task. Configured planners only; it creates no task, dispatches nothing and never approves (only the person approves, with ahub study approve). The contract is data: question, scope, exclusions, sourceIds, units, deliverableSections, stopPolicy and an optional budget.", { parentTaskId: id, contract: { type: "object" } }, ["parentTaskId", "contract"]),
@@ -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;
@@ -283,11 +297,15 @@ export function claimRunner(id: string, home = hubHome()): () => void {
283
297
  };
284
298
  }
285
299
 
286
- /** True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held. */
287
- export function anyRecoveryHold(home = hubHome()): boolean {
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 {
288
306
  try {
289
307
  if (legacyRecoveryLock(home)) return true;
290
- const db = projectLocks(home);
308
+ const db = nonBlocking ? projectLocksNonBlocking(home) : projectLocks(home);
291
309
  if (!db) return false;
292
310
  try { return !!db.query("SELECT 1 FROM project_locks LIMIT 1").get(); } finally { db.close(); }
293
311
  } catch { return true; }
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: {} };
@@ -141,10 +141,11 @@ export function evidenceEntry(raw: unknown): EvidenceEntry | undefined {
141
141
  /** A board task (live `Task` or a parsed row) as closed evidence. The title, detail, plan, refs and every note stay behind. */
142
142
  export function evidenceTask(raw: { id: number; history?: unknown; sdlc?: unknown }, handoffs?: { in: number; out: number }): EvidenceTask {
143
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);
144
- 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);
145
146
  let mergeEvidence: EvidenceMerge | undefined;
146
147
  if (merge?.state === "merged") {
147
- 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);
148
149
  mergeEvidence = { mergedAt: at, ciRuns: cost?.ciRuns ?? null, ciReruns: cost?.ciReruns ?? null, reviews: cost?.reviews ?? null };
149
150
  }
150
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
  }
@@ -474,14 +474,20 @@ function admissionRow(db: Database): Admission | undefined {
474
474
  || row.signature !== null && (typeof row.signature !== "string" || !row.signature.trim() || Buffer.byteLength(row.signature) > 1024))) fail("runtime maintenance admission state is invalid");
475
475
  return rows[0];
476
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/;
477
479
  function admitSchedule(home: string): string | undefined {
478
480
  const db = startupAdmissionDatabase(home);
479
481
  try {
480
482
  return db.transaction(() => {
481
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
+ })();
482
488
  const dead = previous?.phase === "running" && previous.pid !== null && previous.signature !== null
483
489
  && processLiveness(previous.pid, previous.signature) === "gone";
484
- 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;
485
491
  const id = randomUUID();
486
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);
487
493
  return id;
@@ -497,6 +503,8 @@ export function scheduleRuntimeCapturePrune(home?: string): void {
497
503
  setImmediate(() => {
498
504
  try {
499
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
500
508
  const id = admitSchedule(targetHome); if (!id) return;
501
509
  const env = childEnv(process.env);
502
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,7 +4,7 @@ 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 { RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, 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;
@@ -64,6 +64,10 @@ function admissionHealth(file: string): LedgerHealth {
64
64
  || !Number.isSafeInteger(outcome.removed) || (outcome.removed as number) < 0 || !Array.isArray(outcome.quarantined) || outcome.quarantined.length > MAX_QUARANTINES
65
65
  || outcome.quarantined.some(value => typeof value !== "string" || value.length > 4096 || isAbsolute(value) || normalize(value) !== value || value.split(/[\\/]/).some(part => part === ".."))
66
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
+ }
67
71
  if (outcome.deferred !== undefined || outcome.quarantined.length) {
68
72
  // #1541: a deferral that already names a supported command (the receipt ceiling, an open operation) is not sent to the ledger.
69
73
  const text = typeof outcome.deferred === "string" ? outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ") : undefined;
@@ -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];
@@ -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;
@@ -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)),
package/src/hub/sdlc.ts CHANGED
@@ -65,8 +65,14 @@ export interface MergeRecord {
65
65
  /** #481 S7: the merged PR's review and CI figures, read once at merge by the host. Absent when the PR could not be read; fields inside are null when unknown. */
66
66
  cost?: import("./cost-governance.ts").MergeCost;
67
67
  }
68
+ /** A merge observed by readback, with no locally executed merge or cleanup. */
69
+ export interface ReadbackMergeRecord {
70
+ repo: string; pr: number; head: string; at: number; state: "merged";
71
+ mergeCommit?: string; cost?: import("./cost-governance.ts").MergeCost;
72
+ }
68
73
  export interface SdlcReceipt {
69
74
  merge?: MergeRecord;
75
+ mergeReadback?: ReadbackMergeRecord;
70
76
  stage: SdlcStage;
71
77
  planReview?: PlanReviewReceipt;
72
78
  criteria?: CriteriaReceipt;
@@ -284,7 +290,7 @@ export function sdlcReceipt(value: unknown, previous: SdlcReceipt | undefined =
284
290
 
285
291
  function receiptIdentity(next: SdlcReceipt, previous: SdlcReceipt, raw: Record<string, unknown>): SdlcReceipt {
286
292
  const checklist = raw.criteria ?? raw.phase;
287
- if (next.repo !== previous.repo || next.pr !== previous.pr || next.head !== previous.head || next.reviewedHead !== previous.reviewedHead || next.localHead !== previous.localHead) delete next.merge;
293
+ if (next.repo !== previous.repo || next.pr !== previous.pr || next.head !== previous.head || next.reviewedHead !== previous.reviewedHead || next.localHead !== previous.localHead) { delete next.merge; delete next.mergeReadback; }
288
294
  // A test receipt never carries across a different linked issue or artifact.
289
295
  if (raw.redFirst === undefined && (next.repo !== previous.repo || next.issue !== previous.issue || next.pr !== previous.pr)) delete next.redFirst;
290
296
  // An acceptance names one spec issue; relinking the receipt to another drops it (#481 S1).
@@ -739,15 +745,21 @@ async function identicalTreeGate(repository: string, tree: string, run: SdlcGh,
739
745
  }
740
746
 
741
747
  /** PR cost evidence excludes titles, bodies and comment text; unknown/truncated coverage never becomes zero. */
742
- export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh): Promise<import("./cost-governance.ts").CostPr | undefined> {
748
+ export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string): Promise<import("./cost-governance.ts").CostPr | undefined> {
743
749
  if (!repo(repository) || !id(number)) return;
744
750
  const [owner, name] = repository.split("/");
745
751
  try {
746
752
  const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){number state headRefOid mergedAt commits(first:100){nodes{commit{oid}} pageInfo{hasNextPage}} reviews(first:100){nodes{databaseId commit{oid}} pageInfo{hasNextPage}}}}}";
747
- const reply = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${number}`], 10_000, undefined, 128 * 1024);
748
- if (reply.code !== 0) return;
749
- const parsed = JSON.parse(reply.stdout), pr = parsed.data?.repository?.pullRequest;
750
- if (parsed.errors || pr?.number !== number || !["OPEN", "CLOSED", "MERGED"].includes(pr.state)) return;
753
+ let pr: any;
754
+ if (snapshot !== undefined) pr = snapshot;
755
+ else {
756
+ const reply = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${number}`], 10_000, undefined, 128 * 1024);
757
+ if (reply.code !== 0) return;
758
+ const parsed = JSON.parse(reply.stdout);
759
+ if (parsed.errors) return;
760
+ pr = parsed.data?.repository?.pullRequest;
761
+ }
762
+ if (pr?.number !== number || !["OPEN", "CLOSED", "MERGED"].includes(pr.state) || (expectedHead !== undefined && pr.headRefOid !== expectedHead)) return;
751
763
  const result: import("./cost-governance.ts").CostPr = { repo: repository, pr: number, state: pr.state, complete: false,
752
764
  ...(typeof pr.mergedAt === "string" && Number.isFinite(Date.parse(pr.mergedAt)) ? { mergedAt: Date.parse(pr.mergedAt) } : {}) };
753
765
  if (pr.state !== "MERGED") return result; // Cost metrics count merged PRs, not an active work queue.
@@ -26,6 +26,49 @@ export const budgetNow = (budget: SnapshotBudget): number => budget.now ? budget
26
26
  export class SnapshotBudgetExceeded extends Error {
27
27
  constructor() { super("snapshot burst budget exhausted; boundary evidence is unknown"); }
28
28
  }
29
+ // ponytail: five consecutive exhausted bursts suspend a repository for ten minutes; an isolated capture worker is the upgrade path to avoiding this evidence-loss ceiling.
30
+ export const SNAPSHOT_COOLDOWN_FAILURES = 5;
31
+ export const SNAPSHOT_COOLDOWN_MS = 10 * 60_000;
32
+
33
+ /** In-memory, per-repository circuit breaker; a restart begins with no observations. */
34
+ export class SnapshotCooldown {
35
+ private readonly states = new Map<string, { failures: number; until: number }>();
36
+ private readonly observed = new WeakMap<SnapshotBudget, Set<string>>();
37
+ private readonly successful = new WeakMap<SnapshotBudget, Set<string>>();
38
+ blocked(repository: string, now: number): boolean {
39
+ const state = this.states.get(repository);
40
+ return !!state && now < state.until;
41
+ }
42
+ /** True only when this observation starts a cooldown and needs one diagnostic. */
43
+ exhausted(repository: string, budget: SnapshotBudget): boolean {
44
+ let repositories = this.observed.get(budget);
45
+ if (!repositories) { repositories = new Set(); this.observed.set(budget, repositories); }
46
+ if (repositories.has(repository)) return false;
47
+ repositories.add(repository);
48
+ const now = budgetNow(budget);
49
+ const state = this.states.get(repository) ?? { failures: 0, until: 0 };
50
+ state.failures = Math.min(SNAPSHOT_COOLDOWN_FAILURES, state.failures + 1);
51
+ if (state.failures >= SNAPSHOT_COOLDOWN_FAILURES) {
52
+ state.until = now + SNAPSHOT_COOLDOWN_MS;
53
+ this.states.set(repository, state);
54
+ return true;
55
+ }
56
+ this.states.set(repository, state);
57
+ return false;
58
+ }
59
+ success(repository: string, budget: SnapshotBudget): void {
60
+ let repositories = this.successful.get(budget);
61
+ if (!repositories) { repositories = new Set(); this.successful.set(budget, repositories); }
62
+ repositories.add(repository);
63
+ }
64
+ finish(budget: SnapshotBudget): void {
65
+ for (const repository of this.successful.get(budget) ?? []) {
66
+ if (!this.observed.get(budget)?.has(repository)) this.reset(repository);
67
+ }
68
+ this.successful.delete(budget);
69
+ }
70
+ reset(repository: string): void { this.states.delete(repository); }
71
+ }
29
72
  const SNAPSHOT_TIMEOUT_MS = 10_000;
30
73
  /**
31
74
  * The wall-clock timeout of one git child. Production (no `budget.now`): the remaining budget, between 1 ms and the 10 s ceiling, so a child is killed at the budget.
@@ -15,7 +15,7 @@ import type { DeliverableRecord } from "./deliverables.ts";
15
15
  export const SUPERVISION_RULES = ["repeated_failure", "deliverable_invalidated_check", "declared_overlap_without_integration"] as const;
16
16
  export type SupervisionRuleId = (typeof SUPERVISION_RULES)[number];
17
17
  /** Bump one rule when its trigger, refs or reason codes change meaning: a stored observation names the version it was made under. */
18
- export const SUPERVISION_RULE_VERSION: Readonly<Record<SupervisionRuleId, number>> = { repeated_failure: 1, deliverable_invalidated_check: 1, declared_overlap_without_integration: 1 };
18
+ export const SUPERVISION_RULE_VERSION: Readonly<Record<SupervisionRuleId, number>> = { repeated_failure: 1, deliverable_invalidated_check: 2, declared_overlap_without_integration: 1 };
19
19
 
20
20
  /** The existing hub operation an observation names. T1 names one; nothing in this module runs it. */
21
21
  export const SUPERVISION_ACTIONS = ["escalate", "recheck", "request_integration"] as const;
@@ -213,7 +213,7 @@ function invalidatedCheck(side: Side, measurement: DeliverableMeasurementFact |
213
213
  let check: number | undefined;
214
214
  const recorded = new Set<string>();
215
215
  for (const [offset, entry] of side.window.entries()) {
216
- if (entry.event === "check passed") check = offset;
216
+ if (entry.event === "check passed" || entry.event === "check run passed") check = offset;
217
217
  for (const record of (entry.deliverables ?? []) as readonly DeliverableRecord[]) recorded.add(record.id);
218
218
  }
219
219
  if (check === undefined || !recorded.size) return {};