@staix/agent-hub 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +1 -1
  5. package/docs/agent-notes/local-worker.md +1 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +3 -1
  8. package/docs/agent-notes/tests.md +3 -2
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub.md +1 -1
  11. package/docs/design/roadmap.md +75 -2
  12. package/docs/design/supervision.md +21 -1
  13. package/docs/design/task-board.md +30 -2
  14. package/docs/dogfood.md +13 -4
  15. package/docs/events.md +5 -1
  16. package/docs/influences.md +7 -0
  17. package/docs/memory.md +4 -4
  18. package/docs/operations.md +51 -18
  19. package/docs/quickstart.md +8 -2
  20. package/docs/research.md +16 -0
  21. package/docs/roadmap.json +4 -0
  22. package/docs/roadmap.md +9 -0
  23. package/docs/sdlc.md +15 -3
  24. package/docs/security.md +3 -3
  25. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  26. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  27. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  28. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  29. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  30. package/docs/verified.json +32 -26
  31. package/package.json +2 -2
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +472 -229
  34. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  35. package/plugins/agent-hub/server.js +513 -258
  36. package/scripts/check-docs.mjs +9 -1
  37. package/src/adapters/acp.ts +11 -1
  38. package/src/adapters/compat.ts +3 -3
  39. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  40. package/src/adapters/definitions/native-context.ts +10 -0
  41. package/src/adapters/jcode.ts +10 -0
  42. package/src/adapters/local-worker.ts +3 -2
  43. package/src/adapters/pi.ts +15 -4
  44. package/src/cli/console-state.ts +3 -1
  45. package/src/cli/help.ts +3 -1
  46. package/src/cli/identity.ts +2 -1
  47. package/src/cli/main.ts +11 -5
  48. package/src/cli/recovery-package.ts +16 -3
  49. package/src/cli/roadmap-write.ts +59 -0
  50. package/src/cli/roadmap.ts +81 -4
  51. package/src/cli/sdlc-output.ts +4 -0
  52. package/src/cli/upgrade-runtime.ts +10 -6
  53. package/src/hub/agent-mem-range.ts +43 -0
  54. package/src/hub/board.ts +102 -1
  55. package/src/hub/check-runner.ts +25 -1
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +1 -1
  58. package/src/hub/context-window.ts +1 -1
  59. package/src/hub/cost-governance.ts +11 -7
  60. package/src/hub/daemon.ts +253 -30
  61. package/src/hub/dogfood-read.ts +4 -2
  62. package/src/hub/edit-guard.ts +100 -0
  63. package/src/hub/events.ts +79 -8
  64. package/src/hub/facts.ts +57 -4
  65. package/src/hub/hub-tools.ts +2 -0
  66. package/src/hub/lifecycle.ts +6 -1
  67. package/src/hub/log-rotation.ts +130 -0
  68. package/src/hub/memory-profile.ts +137 -21
  69. package/src/hub/no-writes.ts +1 -0
  70. package/src/hub/operational-authority.ts +3 -2
  71. package/src/hub/operational-settings.ts +2 -2
  72. package/src/hub/recovery-store.ts +49 -21
  73. package/src/hub/research-experiments.ts +132 -0
  74. package/src/hub/research-quality.ts +8 -2
  75. package/src/hub/research-record.ts +35 -0
  76. package/src/hub/research.ts +128 -28
  77. package/src/hub/roadmap-check.ts +65 -0
  78. package/src/hub/roadmap-decompose.ts +80 -0
  79. package/src/hub/roadmap-export.ts +27 -0
  80. package/src/hub/roadmap-sync.ts +97 -0
  81. package/src/hub/roadmap.ts +40 -0
  82. package/src/hub/sdlc-branch-ci.ts +128 -0
  83. package/src/hub/sdlc-merge.ts +6 -3
  84. package/src/hub/sdlc-metrics.ts +19 -5
  85. package/src/hub/sdlc.ts +73 -5
  86. package/src/hub/settings.ts +1 -0
  87. package/src/hub/snapshots.ts +13 -1
  88. package/src/hub/startup-event-seeds.ts +21 -15
  89. package/src/hub/startup-timing.ts +3 -1
  90. package/src/hub/supervision-proposals.ts +10 -2
  91. package/src/hub/supervision-rules.ts +26 -3
  92. package/src/hub/supervision.ts +7 -0
  93. package/src/hub/task-pr.ts +47 -0
  94. package/src/hub/task-worktree.ts +18 -11
  95. package/src/hub/tasks.ts +502 -34
  96. package/src/hub/usage-rollup.ts +35 -20
  97. package/src/local/tools.ts +13 -1
  98. package/src/memory/client.ts +3 -2
  99. package/src/pi/extension.ts +15 -3
  100. package/src/pi/tool-receipts.ts +26 -0
@@ -0,0 +1,128 @@
1
+ import type { SdlcGh } from "./sdlc.ts";
2
+
3
+ /** Bounded GitHub evidence; missing or ambiguous coverage never becomes a count. */
4
+ export interface BranchCi {
5
+ runs: { id: number; attempt: number }[];
6
+ fullGateRuns: number;
7
+ successfulGateRuns: number;
8
+ failedGateRuns: number;
9
+ cancelledGateRuns: number;
10
+ otherGateRuns: number;
11
+ macosShardRuns: number;
12
+ firstPass: 0 | 1 | null;
13
+ }
14
+
15
+ type Row = Record<string, any>;
16
+ const PAGE_SIZE = 100;
17
+ const PAGE_LIMIT = 10;
18
+ const TIMEOUT = 10_000;
19
+ const CAP = 256 * 1024;
20
+ const integer = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
21
+ const timestamp = (v: unknown): number => typeof v === "string" ? Date.parse(v) : NaN;
22
+
23
+ /** Read all pages, failing closed on an error, malformed page, changed total or a bounded overflow. */
24
+ async function pages(run: SdlcGh, endpoint: string, fields: string[], projection: string, key?: string): Promise<Row[] | undefined> {
25
+ const all: Row[] = []; let total: number | undefined;
26
+ for (let page = 1; page <= PAGE_LIMIT; page++) {
27
+ const reply = await run(["api", "-X", "GET", endpoint, ...fields, "-F", `per_page=${PAGE_SIZE}`, "-F", `page=${page}`, "--jq", projection], TIMEOUT, undefined, CAP);
28
+ if (reply.code !== 0) return;
29
+ const parsed = JSON.parse(reply.stdout), rows = key ? parsed?.[key] : parsed;
30
+ if (!Array.isArray(rows) || rows.length > PAGE_SIZE || rows.some(row => !row || typeof row !== "object")) return;
31
+ if (key) {
32
+ if (!Number.isSafeInteger(parsed.total_count) || parsed.total_count < 0 || (total !== undefined && total !== parsed.total_count)) return;
33
+ total = parsed.total_count;
34
+ }
35
+ all.push(...rows);
36
+ if (total !== undefined ? all.length === total : rows.length < PAGE_SIZE) return all;
37
+ if (total !== undefined && (all.length > total || rows.length < PAGE_SIZE)) return;
38
+ }
39
+ }
40
+
41
+ /** Associate PR workflow runs by verified same-repository branch and lifetime, not pull_requests (often empty). */
42
+ export async function readBranchCi(repo: string, number: number, firstHead: string | undefined, run: SdlcGh): Promise<BranchCi | undefined> {
43
+ try {
44
+ const response = await run(["api", `repos/${repo}/pulls/${number}`, "--jq", "{number,state,created_at,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{repo:{full_name:.base.repo.full_name}}}"], TIMEOUT, undefined, CAP);
45
+ if (response.code !== 0) return;
46
+ const pr = JSON.parse(response.stdout), branch = pr?.head?.ref, start = timestamp(pr?.created_at), end = timestamp(pr?.merged_at);
47
+ if (pr.number !== number || pr.state !== "closed" || typeof branch !== "string" || !branch || !Number.isFinite(start) || !Number.isFinite(end) || end < start
48
+ || pr.head?.repo?.full_name?.toLowerCase() !== repo.toLowerCase() || pr.base?.repo?.full_name?.toLowerCase() !== repo.toLowerCase()) return;
49
+ const owner = repo.split("/")[0];
50
+ const prs = await pages(run, `repos/${repo}/pulls`, ["-f", "state=all", "-f", `head=${owner}:${branch}`], "[.[]|{number,created_at,closed_at}]");
51
+ if (!prs || !prs.some(row => row.number === number)) return;
52
+ for (const other of prs) {
53
+ if (other.number === number) continue;
54
+ const created = timestamp(other.created_at), closed = other.closed_at === null ? Infinity : timestamp(other.closed_at);
55
+ if (!Number.isFinite(created) || !(Number.isFinite(closed) || closed === Infinity)) return;
56
+ if (created <= end && closed >= start) return;
57
+ }
58
+ const rows = await pages(run, `repos/${repo}/actions/runs`, ["-f", `branch=${branch}`, "-f", "event=pull_request"], "{total_count,workflow_runs:[.workflow_runs[]|{id,path,created_at,head_sha,status,conclusion,run_attempt,pull_requests:[.pull_requests[].number]}]}", "workflow_runs");
59
+ if (!rows) return;
60
+ if (rows.some(row => typeof row.path !== "string" || !Number.isFinite(timestamp(row.created_at)) || !Array.isArray(row.pull_requests) || row.pull_requests.some((value: unknown) => !integer(value)))) return;
61
+ const checks = rows.filter(row => row.path === ".github/workflows/check.yml" && timestamp(row.created_at) >= start && timestamp(row.created_at) <= end && (row.pull_requests.length === 0 || row.pull_requests.includes(number)));
62
+ if (checks.some(row => row.pull_requests.some((value: number) => value !== number))) return;
63
+ // ponytail: inspect at most one page of check runs and ten attempts each; raise the bounds with a provider-side summary.
64
+ if (checks.length > PAGE_SIZE || checks.some(row => !integer(row.id) || !integer(row.run_attempt) || row.run_attempt > PAGE_LIMIT || !/^[a-f0-9]{40}$/.test(row.head_sha) || typeof row.status !== "string")) return;
65
+ if (new Set(checks.map(row => row.id)).size !== checks.length) return;
66
+ const timeline = await pages(run, `repos/${repo}/issues/${number}/timeline`, [], "[.[]|{event,created_at}]");
67
+ if (!timeline) return;
68
+ const changes = timeline.filter(row => row.event === "ready_for_review" || row.event === "converted_to_draft").map(row => ({ event: row.event, at: timestamp(row.created_at) })).sort((a, b) => a.at - b.at);
69
+ if (changes.some(change => !Number.isFinite(change.at))) return;
70
+ const initialDraft = changes.length > 0 && changes[0]!.event === "ready_for_review";
71
+ let finalDraft = initialDraft;
72
+ for (const change of changes) {
73
+ if ((change.event === "ready_for_review") !== finalDraft) return;
74
+ finalDraft = change.event === "converted_to_draft";
75
+ }
76
+ if (finalDraft) return;
77
+ const draftAt = (at: number): boolean | undefined => {
78
+ let draft = initialDraft;
79
+ for (const change of changes) {
80
+ if (change.at === at) return;
81
+ if (change.at > at) break;
82
+ if ((change.event === "ready_for_review") !== draft) return;
83
+ draft = change.event === "converted_to_draft";
84
+ }
85
+ return draft;
86
+ };
87
+ let macosShardRuns = 0, firstPass: 0 | 1 | null = null, firstDecided = false;
88
+ const observedRuns: { id: number; attempt: number; conclusion: string }[] = [];
89
+ const ordered = checks.sort((a, b) => timestamp(a.created_at) - timestamp(b.created_at) || a.id - b.id);
90
+ const firstHeadTimes = ordered.filter(row => firstHead && row.head_sha === firstHead).map(row => timestamp(row.created_at));
91
+ const firstOrderAmbiguous = new Set(firstHeadTimes).size !== firstHeadTimes.length;
92
+ for (const check of ordered) {
93
+ let atMerge: { id: number; attempt: number; conclusion: string } | undefined;
94
+ let previousStarted = -Infinity;
95
+ for (let attempt = 1; attempt <= check.run_attempt; attempt++) {
96
+ const attemptReply = await run(["api", `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}`, "--jq", "{id,run_attempt,status,conclusion,run_started_at,updated_at}"], TIMEOUT, undefined, CAP);
97
+ if (attemptReply.code !== 0) return;
98
+ const observed = JSON.parse(attemptReply.stdout), started = timestamp(observed.run_started_at), updated = timestamp(observed.updated_at);
99
+ if (observed.id !== check.id || observed.run_attempt !== attempt || !Number.isFinite(started) || !Number.isFinite(updated) || started < previousStarted || updated < started || started === end || updated === end) return;
100
+ previousStarted = started;
101
+ if (started > end) continue;
102
+ if (observed.status !== "completed" || typeof observed.conclusion !== "string" || updated > end) return;
103
+ atMerge = { id: check.id, attempt, conclusion: observed.conclusion };
104
+ const jobs = await pages(run, `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}/jobs`, [], "{total_count,jobs:[.jobs[]|{name,status,conclusion,runner_id}]}", "jobs");
105
+ if (!jobs || jobs.some(job => typeof job.name !== "string")) return;
106
+ const shards = jobs.filter(job => /^check \(macos-latest\) shard [1-4]\/4$/.test(job.name));
107
+ if (shards.some(job => job.status !== "completed" || typeof job.conclusion !== "string" || !(job.runner_id === null || job.runner_id === 0 || integer(job.runner_id)) || (job.runner_id === null || job.runner_id === 0) && job.conclusion !== "skipped" && job.conclusion !== "cancelled")) return;
108
+ const ran = shards.filter(job => job.conclusion !== "skipped" && integer(job.runner_id));
109
+ macosShardRuns += ran.length;
110
+ if (attempt !== 1 || firstDecided || !firstHead || check.head_sha !== firstHead) continue;
111
+ const draft = draftAt(timestamp(check.created_at));
112
+ if (draft === undefined) return;
113
+ if (draft || ran.length === 0 || observed.status !== "completed" || observed.conclusion === "cancelled") continue;
114
+ if (observed.conclusion === "success") firstPass = 1;
115
+ else if (observed.conclusion === "failure" || observed.conclusion === "timed_out") firstPass = 0;
116
+ else return;
117
+ firstDecided = true;
118
+ }
119
+ if (!atMerge) return;
120
+ observedRuns.push(atMerge);
121
+ }
122
+ const successfulGateRuns = observedRuns.filter(row => row.conclusion === "success").length;
123
+ const failedGateRuns = observedRuns.filter(row => row.conclusion === "failure" || row.conclusion === "timed_out").length;
124
+ const cancelledGateRuns = observedRuns.filter(row => row.conclusion === "cancelled").length;
125
+ return { runs: observedRuns.map(row => ({ id: row.id, attempt: row.attempt })), fullGateRuns: observedRuns.length,
126
+ successfulGateRuns, failedGateRuns, cancelledGateRuns, otherGateRuns: observedRuns.length - successfulGateRuns - failedGateRuns - cancelledGateRuns, macosShardRuns, firstPass: firstOrderAmbiguous ? null : firstPass };
127
+ } catch { return; }
128
+ }
@@ -27,6 +27,7 @@ export interface MergeInput {
27
27
  tasks: DeliveryTask[];
28
28
  run: SdlcGh;
29
29
  readableMetadata?: (path: string) => boolean;
30
+ firstSubmittedHead?: string;
30
31
  /** Final synchronous authority and queue-input fence, after fresh gates and immediately before the gh call. */
31
32
  beforeMerge?: (queue: MergeQueue | undefined) => string | undefined;
32
33
  /** Post-run host fence and durable progress record. False or a throw withholds cleanup. No remote text is supplied. */
@@ -51,7 +52,9 @@ export interface MergeOutcome {
51
52
  }
52
53
 
53
54
  export const MERGE_READBACK_INTERVAL_MS = 5 * 60_000;
54
- export const MERGE_READBACK_DEADLINE_MS = 8_000;
55
+ // ponytail: 60 s bounds paged branch and job readbacks; lower it once a single bounded provider read supplies the same evidence.
56
+ export const MERGE_READBACK_DEADLINE_MS = 60_000;
57
+ export const INLINE_MERGE_READBACK_DEADLINE_MS = 8_000;
55
58
  const SHA = /^[0-9a-f]{40}$/;
56
59
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
57
60
  /**
@@ -305,11 +308,11 @@ export async function guardedMerge(input: MergeInput & { mode: AutoMergeMode }):
305
308
  if (input.recordMerge) {
306
309
  // #481 S7: the merged PR's review and CI figures, read once now that the merge is observed. After the merge there is nothing left to race, so this await is fine;
307
310
  // its own bound keeps a slow GitHub from holding the record, and a failed read records no cost (unknown), never a zero.
308
- const costDeadline = performance.now() + 8000;
311
+ const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
309
312
  const cost = result.state === "merged" ? await readPrCostHistory(decision.repo, decision.pr, (args, timeout, cwd, cap) => {
310
313
  const left = costDeadline - performance.now();
311
314
  return left > 0 ? input.run(args, Math.min(timeout ?? 10_000, left), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
312
- }).then(mergeCostFrom, () => undefined) : undefined;
315
+ }, undefined, undefined, input.firstSubmittedHead).then(mergeCostFrom, () => undefined) : undefined;
313
316
  let record: MergeRecord={repo:decision.repo,pr:decision.pr,head:decision.head,at:Date.now(),...result,...(cost?{cost}:{}),cleanup:"not_started",ownerNotice:"not_started"};
314
317
  const save = () => {try {return input.recordMerge!({...record});}catch{return false;}};
315
318
  if (!save()) {record={...record,cleanup:"skipped",reason:"authority_changed"};save();}
@@ -38,6 +38,12 @@ export interface TaskSample {
38
38
  review_rounds_at_merge: number | null;
39
39
  ci_runs_at_merge: number | null;
40
40
  github_reviews_at_merge: number | null;
41
+ full_gate_runs: number | null;
42
+ successful_gate_runs: number | null;
43
+ failed_gate_runs: number | null;
44
+ cancelled_gate_runs: number | null;
45
+ other_gate_runs: number | null;
46
+ macos_shard_runs: number | null;
41
47
  }
42
48
 
43
49
  export interface Summary { n: number; unknown: number; mean: number | null; median: number | null; p90: number | null; max: number | null }
@@ -102,7 +108,7 @@ function staleHeadRounds(history: MetricTask["history"]): number | null {
102
108
  }
103
109
 
104
110
  /** One task's values from its own history. A private task never reaches here. */
105
- export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null } = {}): TaskSample {
111
+ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null; firstPass?: 0 | 1 | null; fullGateRuns?: number | null; successfulGateRuns?: number | null; failedGateRuns?: number | null; cancelledGateRuns?: number | null; otherGateRuns?: number | null; macosShardRuns?: number | null } = {}): TaskSample {
106
112
  const history = [...task.history].filter(entry => Number.isFinite(entry.at) && entry.at >= 0).sort((a, b) => a.at - b.at);
107
113
  const view: MetricTask = { id: task.id, history };
108
114
  const accepted = first(view, ["accepted"]);
@@ -119,6 +125,7 @@ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciRerun
119
125
  const latestRun = doneHead ? history.slice(0, firstDone).findLast(entry => entry.event === "check run passed" || entry.event === "check run failed") : undefined;
120
126
  const isolatedCheck = latestRun?.requestHead === doneHead ? latestRun : undefined;
121
127
  const ci = completionCheck ?? isolatedCheck;
128
+ const hasHubCheck = history.some(entry => ["check passed", "check failed", "check run passed", "check run failed"].includes(entry.event));
122
129
  const approvedAt = history.find(entry => entry.event === "approved")?.at ?? null;
123
130
  return {
124
131
  id: task.id,
@@ -132,11 +139,17 @@ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciRerun
132
139
  // 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
133
140
  // provisional point would move at each verdict and could start a second breach episode inside one shift.
134
141
  rework_rounds: dones.length && approvedAt !== null ? history.filter(entry => entry.event === "changes_requested" && entry.evidenceOnly !== true).length : null,
135
- first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : null,
142
+ first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : hasHubCheck ? null : extra.firstPass ?? null,
136
143
  same_head_ci_reruns: extra.ciReruns === undefined ? null : extra.ciReruns,
137
144
  // Counted only for a merged PR whose figures were read: a done before the merge is one review round.
138
145
  review_rounds_at_merge: extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) ? dones.filter(entry => entry.at <= extra.mergedAt!).length : null,
139
146
  ci_runs_at_merge: extra.ciRuns === undefined ? null : extra.ciRuns,
147
+ full_gate_runs: extra.fullGateRuns ?? null,
148
+ successful_gate_runs: extra.successfulGateRuns ?? null,
149
+ failed_gate_runs: extra.failedGateRuns ?? null,
150
+ cancelled_gate_runs: extra.cancelledGateRuns ?? null,
151
+ other_gate_runs: extra.otherGateRuns ?? null,
152
+ macos_shard_runs: extra.macosShardRuns ?? null,
140
153
  github_reviews_at_merge: extra.reviews === undefined ? null : extra.reviews,
141
154
  stale_head_re_reviews: approvedAt !== null ? staleHeadRounds(history) : null,
142
155
  };
@@ -218,7 +231,7 @@ export interface MetricsReport {
218
231
  first_pass_check: { n: number; unknown: number; rate: number | null };
219
232
  same_head_ci_reruns: Summary;
220
233
  stale_head_re_reviews: Summary;
221
- review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary;
234
+ review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary; full_gate_runs: Summary; successful_gate_runs: Summary; failed_gate_runs: Summary; cancelled_gate_runs: Summary; other_gate_runs: Summary; macos_shard_runs: Summary;
222
235
  };
223
236
  /** Merged PRs whose review and CI figures were read at merge, and how many of the counted tasks have none (unknown, never 0). */
224
237
  merged: { read: number; unknown: number };
@@ -235,9 +248,9 @@ const rate = (values: readonly (number | null)[]) => {
235
248
  * The whole report from board tasks. `since` keeps samples that count at or after it; `mergedAt` and `ciReruns` come from bounded
236
249
  * PR readbacks keyed by task id and are optional. Private tasks are counted as withheld and read for nothing else.
237
250
  */
238
- export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
251
+ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; firstPass?: Readonly<Record<number, 0 | 1 | null>>; fullGateRuns?: Readonly<Record<number, number | null>>; successfulGateRuns?: Readonly<Record<number, number | null>>; failedGateRuns?: Readonly<Record<number, number | null>>; cancelledGateRuns?: Readonly<Record<number, number | null>>; otherGateRuns?: Readonly<Record<number, number | null>>; macosShardRuns?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
239
252
  const visible = tasks.filter(task => !task.private);
240
- const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id] }));
253
+ const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id], firstPass: opts.firstPass?.[task.id], fullGateRuns: opts.fullGateRuns?.[task.id], successfulGateRuns: opts.successfulGateRuns?.[task.id], failedGateRuns: opts.failedGateRuns?.[task.id], cancelledGateRuns: opts.cancelledGateRuns?.[task.id], otherGateRuns: opts.otherGateRuns?.[task.id], macosShardRuns: opts.macosShardRuns?.[task.id] }));
241
254
  const samples = opts.since === undefined ? all : all.filter(sample => sample.at >= opts.since!);
242
255
  const bands: BandResult[] | "off" = opts.bands && Object.keys(opts.bands).length
243
256
  ? BAND_METRICS.flatMap(metric => opts.bands![metric] ? [controlEpisode(EXTERNAL_METRICS.includes(metric) ? [...(opts.external?.[metric] ?? [])] : series(samples, metric as TaskMetric), metric, opts.bands![metric]!)] : [])
@@ -252,6 +265,7 @@ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number
252
265
  stale_head_re_reviews: summarize(samples.map(s => s.stale_head_re_reviews)),
253
266
  review_rounds_at_merge: summarize(samples.map(s => s.review_rounds_at_merge)), ci_runs_at_merge: summarize(samples.map(s => s.ci_runs_at_merge)),
254
267
  github_reviews_at_merge: summarize(samples.map(s => s.github_reviews_at_merge)),
268
+ full_gate_runs: summarize(samples.map(s => s.full_gate_runs)), successful_gate_runs: summarize(samples.map(s => s.successful_gate_runs)), failed_gate_runs: summarize(samples.map(s => s.failed_gate_runs)), cancelled_gate_runs: summarize(samples.map(s => s.cancelled_gate_runs)), other_gate_runs: summarize(samples.map(s => s.other_gate_runs)), macos_shard_runs: summarize(samples.map(s => s.macos_shard_runs)),
255
269
  },
256
270
  merged: { read: samples.filter(s => s.ci_runs_at_merge !== null || s.github_reviews_at_merge !== null).length, unknown: samples.filter(s => s.ci_runs_at_merge === null && s.github_reviews_at_merge === null).length },
257
271
  stalls: opts.stalls ?? { open: 0, byKind: {}, doneWithoutWrites: 0 }, bands,
package/src/hub/sdlc.ts CHANGED
@@ -13,6 +13,7 @@ import { join } from "node:path";
13
13
  import { spawn } from "node:child_process";
14
14
  import { childEnv, stopOwnedProcess } from "./child-process.ts";
15
15
  import { hostExecutable } from "./host-executable.ts";
16
+ import { readBranchCi } from "./sdlc-branch-ci.ts";
16
17
 
17
18
  /** The off-mode default (#257). Off output, receipts and schemas keep this shape. */
18
19
  export const SDLC_STAGES = ["spec", "plan", "implement", "review", "verify", "merge", "release"] as const;
@@ -634,6 +635,8 @@ export function requiredCiBlocker(required: readonly string[], checks: PrEvidenc
634
635
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
635
636
  export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
636
637
  if (!evidence || evidence.unresolved !== 0) return undefined;
638
+ // A draft's failed aggregate needs job-step evidence, which this compact snapshot does not carry.
639
+ if (evidence.draft === true && evidence.checks.some(check => check.name === "check (macos-latest)" && check.state === "failed")) return undefined;
637
640
  const checks = requiredCheckNames(repository, required);
638
641
  if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
639
642
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
@@ -647,7 +650,30 @@ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, ex
647
650
  }
648
651
 
649
652
  /** `checks` (#824) names the required checks that were judged, so a fresh reviewer can be told which ones passed at this head; absent when the read was unknown. */
650
- export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[] }
653
+ export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[]; deferred?: string[]; draftApprovalEligible?: boolean }
654
+
655
+ /** Only this repository's actual draft-deferral step can explain its failed macOS aggregate. */
656
+ async function draftMacosDeferred(repository: string, head: string, node: any, run: SdlcGh): Promise<boolean> {
657
+ if (repository.toLowerCase() !== "staixbwlb/agent-hub" || node?.name !== "check (macos-latest)"
658
+ || node.status !== "COMPLETED" || node.conclusion !== "FAILURE"
659
+ || node.checkSuite?.workflowRun?.workflow?.resourcePath !== "/STAIxBWLB/agent-hub/actions/workflows/check.yml") return false;
660
+ const url = typeof node.detailsUrl === "string" ? node.detailsUrl : "";
661
+ const match = /^https:\/\/github\.com\/STAIxBWLB\/agent-hub\/actions\/runs\/(\d+)\/job\/(\d+)$/.exec(url);
662
+ if (!match) return false;
663
+ const result = await run(["api", `repos/${repository}/actions/jobs/${match[2]}`], 10_000, undefined, 64 * 1024);
664
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) return false;
665
+ try {
666
+ const job = JSON.parse(result.stdout), steps = job.steps;
667
+ if (String(job.id) !== match[2] || String(job.run_id) !== match[1] || job.head_sha !== head
668
+ || job.name !== node.name || job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(steps)) return false;
669
+ const deferred = steps.filter((step: any) => step?.name === "macOS shards deferred for a draft PR");
670
+ const stacked = steps.filter((step: any) => step?.name === "macOS shards deferred for a stacked PR");
671
+ return deferred.length === 1 && deferred[0].status === "completed" && deferred[0].conclusion === "failure"
672
+ && stacked.length === 1 && stacked[0].conclusion === "skipped"
673
+ && steps.filter((step: any) => step?.conclusion === "failure").length === 1
674
+ && steps.every((step: any) => step?.status === "completed" && ["success", "skipped", "failure"].includes(step.conclusion));
675
+ } catch { return false; }
676
+ }
651
677
  /** Metadata-only pre-review admission; no remote body or comment text is requested. */
652
678
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
653
679
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
@@ -655,7 +681,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
655
681
  const full = requiredCheckNames(receipt.repo, requiredChecks);
656
682
  if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
657
683
  const [owner, name] = receipt.repo.split("/");
658
- const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
684
+ const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state isDraft reviewDecision reviewRequests(first:100){nodes{__typename} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt detailsUrl checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
659
685
  try {
660
686
  const deadline = performance.now() + 20_000;
661
687
  const bounded: SdlcGh = (args, timeout, cwd, cap) => performance.now() < deadline
@@ -688,6 +714,25 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
688
714
  }) : [];
689
715
  const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
690
716
  if (ciBlocker) blockers.push(ciBlocker);
717
+ let deferred: string[] | undefined;
718
+ const mac = "check (macos-latest)";
719
+ const macNodes = requiredNodes.filter(node => (node as { name?: unknown })?.name === mac);
720
+ if (pr.isDraft === true && !blockers.some(blocker => blocker !== ciBlocker) && ciBlocker
721
+ && [mac, "check (ubuntu-latest)", "seeded guards"].every(name => full.includes(name)) && macNodes.length === 1
722
+ && !requiredCiBlocker(full.filter(name => name !== mac), checkEvidence, completeChecks)
723
+ && checkEvidence.filter(check => check.name === mac).length === 1
724
+ && checkEvidence.find(check => check.name === mac)?.state === "failed"
725
+ && await draftMacosDeferred(receipt.repo, pr.headRefOid, macNodes[0], bounded)) {
726
+ // The proof is fetched separately; the PR may have changed while it was read.
727
+ const after = await bounded(args, 10_000, undefined, 512 * 1024);
728
+ try {
729
+ const refreshed = JSON.parse(after.stdout);
730
+ if (after.code === 0 && !refreshed.errors && JSON.stringify(refreshed.data?.repository?.pullRequest) === JSON.stringify(pr)) {
731
+ blockers.splice(blockers.indexOf(ciBlocker), 1);
732
+ deferred = [mac];
733
+ }
734
+ } catch { /* Incomplete evidence never admits review. */ }
735
+ }
691
736
  if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
692
737
  && full.every(name => { const matches = (nodes as { name?: string; conclusion?: string }[]).filter(node => node?.name === name); return matches.length === 1 && matches[0]?.conclusion === "SKIPPED"; }) && sha(commit?.tree?.oid)) {
693
738
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
@@ -718,7 +763,12 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
718
763
  }
719
764
  if (unanswered) blockers.push("bot review threads unanswered");
720
765
  }
721
- return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: [...full], ...(reusedRun !== undefined ? { reusedRun } : {}) };
766
+ const requests = pr.reviewRequests;
767
+ const draftApprovalEligible = !!deferred && Object.hasOwn(pr, "reviewDecision")
768
+ && [null, "APPROVED", "REVIEW_REQUIRED"].includes(pr.reviewDecision)
769
+ && requests?.pageInfo?.hasNextPage === false && parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: [], reviewRequests: requests.nodes }).pendingReviews !== null
770
+ && threads?.pageInfo?.hasNextPage === false && Array.isArray(threads.nodes) && threads.nodes.every((thread: { isResolved?: unknown }) => thread?.isResolved === true);
771
+ return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: full.filter(name => !deferred?.includes(name)), ...(deferred ? { deferred, draftApprovalEligible } : {}), ...(reusedRun !== undefined ? { reusedRun } : {}) };
722
772
  } catch { return unknown(); }
723
773
  }
724
774
 
@@ -745,7 +795,7 @@ async function identicalTreeGate(repository: string, tree: string, run: SdlcGh,
745
795
  }
746
796
 
747
797
  /** PR cost evidence excludes titles, bodies and comment text; unknown/truncated coverage never becomes zero. */
748
- export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string): Promise<import("./cost-governance.ts").CostPr | undefined> {
798
+ export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string, firstSubmittedHead?: string, recordedHeadInventory = false): Promise<import("./cost-governance.ts").CostPr | undefined> {
749
799
  if (!repo(repository) || !id(number)) return;
750
800
  const [owner, name] = repository.split("/");
751
801
  try {
@@ -775,7 +825,25 @@ export async function readPrCostHistory(repository: string, number: number, run:
775
825
  const linked = runs.workflow_runs.filter((row: { head_sha?: string; pull_requests?: number[] }) => heads.has(row.head_sha ?? "") || Array.isArray(row.pull_requests) && row.pull_requests.includes(number));
776
826
  if (linked.some((row: { id?: number; run_attempt?: number }) => !id(row.id) || !id(row.run_attempt))) return result;
777
827
  result.ciRuns = linked.map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
778
- result.complete = reviewComplete && commitComplete && runs.total_count === runs.workflow_runs.length;
828
+ // The dogfood reader supplies a separately validated, complete recorded-head inventory for its bounded time window.
829
+ if (recordedHeadInventory && runs.total_count === runs.workflow_runs.length) {
830
+ result.complete = reviewComplete && commitComplete;
831
+ return result;
832
+ }
833
+ const directComplete = runs.total_count === runs.workflow_runs.length && runs.workflow_runs.every((row: { pull_requests?: number[] }) => Array.isArray(row.pull_requests) && row.pull_requests.length > 0 && row.pull_requests.every(id));
834
+ if (directComplete) {
835
+ result.ciRuns = runs.workflow_runs.filter((row: { pull_requests: number[] }) => row.pull_requests.includes(number)).map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
836
+ result.complete = reviewComplete && commitComplete;
837
+ }
838
+ const branch = await readBranchCi(repository, number, firstSubmittedHead, run);
839
+ const sameDirectRuns = !directComplete || branch && result.ciRuns?.length === branch.runs.length && result.ciRuns.every(row => branch.runs.some(candidate => candidate.id === row.id));
840
+ if (branch && sameDirectRuns) {
841
+ result.ciRuns = branch.runs;
842
+ result.fullGateRuns = branch.fullGateRuns; result.cancelledGateRuns = branch.cancelledGateRuns;
843
+ result.successfulGateRuns = branch.successfulGateRuns; result.failedGateRuns = branch.failedGateRuns; result.otherGateRuns = branch.otherGateRuns;
844
+ result.macosShardRuns = branch.macosShardRuns; result.firstPass = branch.firstPass;
845
+ result.complete = reviewComplete && commitComplete;
846
+ }
779
847
  return result;
780
848
  } catch { return; }
781
849
  }
@@ -67,6 +67,7 @@ export const SETTINGS: readonly SettingDef[] = [
67
67
  ...OPERATIONAL_NUMBERS.map(({ defaultValue, unit, inventory, ...def }): SettingDef => def),
68
68
  { key: "tasks.auto_pull", group: "Switches", label: "Auto-pull the top reserved ready card when a planner slot frees", type: "boolean", store: "config", applies: "live", risk: "raises", floor: false, path: ["tasks", "auto_pull"] },
69
69
  // #1221 T2: off evaluates nothing, shadow stores bounded proposals with no inbox row or notice, advisory may also show one in the inbox.
70
+ { key: "edit_governance.arm", group: "Switches", label: "Edit governance arm", type: "enum", values: ["baseline", "route_guard", "occ_guard", "combined_guard"], store: "config", applies: "live", risk: "raises", floor: "baseline", path: ["edit_governance", "arm"] },
70
71
  { key: "supervision.mode", group: "Switches", label: "Supervision proposals: off, shadow (stored, zero-effect) or advisory (also shown in the inbox)", type: "enum", values: ["off", "shadow", "advisory"], store: "config", applies: "live", risk: "raises", floor: "off", path: ["supervision", "mode"] },
71
72
  { key: "tasks.queue_backpressure.max_queued", group: "Routing", label: "Automatic offers: max queued envelopes (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_queued, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_queued"] },
72
73
  { key: "tasks.queue_backpressure.max_oldest_s", group: "Routing", label: "Automatic offers: max oldest queued age in seconds (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_oldest_s, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_oldest_s"] },
@@ -708,7 +708,7 @@ export class Turns {
708
708
  // Opened by a starting hub: a turn still open was cut short when the last run stopped. It has no end snapshot, and
709
709
  // it may have run until now, so its window ends now (other turns that overlapped it stay unknowable).
710
710
  this.db.query("UPDATE turns SET ended = ? WHERE ended IS NULL").run(Date.now());
711
- // ponytail: rows of finished tasks stay (a few per file per task); prune by task state if hub.db ever grows.
711
+ // Rows of a task that reached approved or cancelled are pruned by the daemon (#1555 AC6, `pruneTouches`).
712
712
  this.db.run("CREATE TABLE IF NOT EXISTS touches (task INTEGER NOT NULL, peer TEXT NOT NULL, path TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (task, peer, path))");
713
713
  this.db.run("CREATE INDEX IF NOT EXISTS touches_path ON touches (path)"); // the PreToolUse hook looks up one path
714
714
  this.db.run("CREATE TABLE IF NOT EXISTS turn_workspaces (turn TEXT PRIMARY KEY, root TEXT NOT NULL, start_tree TEXT, end_tree TEXT, changed TEXT NOT NULL DEFAULT '[]')");
@@ -836,6 +836,18 @@ export class Turns {
836
836
  if (!tasks.length) return [];
837
837
  return this.db.query(`SELECT * FROM touches WHERE task IN (${tasks.map(() => "?").join(",")})`).all(...tasks) as Touch[];
838
838
  }
839
+ /** #1555 AC6: a closed task's rows go. Every reader (conflicts, check-path, owner-write evidence) looks at open tasks only, and the counts the metrics read are frozen in history. */
840
+ pruneTouches(tasks: number[]): number {
841
+ if (!tasks.length) return 0;
842
+ let removed = 0;
843
+ this.db.transaction(() => { for (const id of tasks) removed += this.db.query("DELETE FROM touches WHERE task = ?").run(id).changes; })();
844
+ return removed;
845
+ }
846
+ /** Rows of tasks that closed while no hub ran, or before this pass existed: the ids with a row are asked about, and `closed` says which are terminal. */
847
+ pruneClosedTouches(closed: (task: number) => boolean): number {
848
+ const ids = (this.db.query("SELECT DISTINCT task FROM touches").all() as { task: number }[]).map(row => row.task).filter(closed);
849
+ return this.pruneTouches(ids);
850
+ }
839
851
  /** Other peers with a turn that was open at some point since `since`: their changes may be in this turn's diff. */
840
852
  busySince(peer: string, since: number): string[] {
841
853
  return (this.db.query("SELECT DISTINCT peer FROM turns WHERE peer != ? AND (ended IS NULL OR ended >= ?) ORDER BY peer").all(peer, since) as { peer: string }[]).map((r) => r.peer);
@@ -1,6 +1,7 @@
1
- import { closeSync, existsSync, openSync, readSync } from "node:fs";
1
+ import { closeSync, openSync, readSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { parseEventLine, type StampedEvent } from "./events.ts";
4
+ import { segmentsOf } from "./log-rotation.ts";
4
5
 
5
6
  const STARTUP_EVENT_BUFFER_BYTES = 64 * 1024;
6
7
  export interface StartupEventSeeds {
@@ -16,11 +17,12 @@ export interface StartupEventSeeds {
16
17
  /** One streaming pass, retaining every accepted row and every historical dedupe key. */
17
18
  export function readStartupEventSeeds(file: string, options: { bufferBytes?: number } = {}): StartupEventSeeds {
18
19
  const seeds: StartupEventSeeds = { events: [], complete: true, nativeStopsSeen: new Set(), claudeNativeUsageSeen: new Set(), readPasses: 0, readBytes: 0 };
19
- if (!existsSync(file)) return seeds;
20
+ const segments = segmentsOf(file); // #1546: rotated segments first, then the live file, so a restart still sees every dedupe key the kept history holds
21
+ if (!segments.length) return seeds;
20
22
  // Host-only chunk-boundary test seam, never a line, history or total-byte ceiling.
21
23
  const bufferBytes = options.bufferBytes ?? STARTUP_EVENT_BUFFER_BYTES;
22
24
  if (!Number.isSafeInteger(bufferBytes) || bufferBytes < 1) throw new Error("startup event buffer must be a positive integer; use the default reader buffer");
23
- const decoder = new StringDecoder("utf8"), buffer = Buffer.alloc(bufferBytes), fd = openSync(file, "r");
25
+ const decoder = new StringDecoder("utf8"), buffer = Buffer.alloc(bufferBytes);
24
26
  let parts: string[] = [];
25
27
  const accept = (line: string) => {
26
28
  const event = parseEventLine(line);
@@ -37,17 +39,21 @@ export function readStartupEventSeeds(file: string, options: { bufferBytes?: num
37
39
  }
38
40
  if (start < text.length) parts.push(text.slice(start));
39
41
  };
40
- try {
41
- seeds.readPasses++;
42
- for (;;) {
43
- const bytes = readSync(fd, buffer, 0, buffer.length, null);
44
- if (!bytes) break;
45
- seeds.readBytes += bytes;
46
- consume(decoder.write(buffer.subarray(0, bytes)));
47
- }
48
- consume(decoder.end());
42
+ seeds.readPasses++;
43
+ for (const segment of segments) {
44
+ let fd: number;
45
+ try { fd = openSync(segment.path, "r"); } catch { seeds.complete = false; continue; }
46
+ try {
47
+ for (;;) {
48
+ const bytes = readSync(fd, buffer, 0, buffer.length, null);
49
+ if (!bytes) break;
50
+ seeds.readBytes += bytes;
51
+ consume(decoder.write(buffer.subarray(0, bytes)));
52
+ }
53
+ consume(decoder.end());
54
+ } finally { closeSync(fd); }
49
55
  // readEvents also accepts a complete final JSON record without a newline.
50
- if (parts.length) { seeds.complete = false; accept(parts.join("")); }
51
- return seeds;
52
- } finally { closeSync(fd); }
56
+ if (parts.length) { seeds.complete = false; accept(parts.join("")); parts = []; }
57
+ }
58
+ return seeds;
53
59
  }
@@ -3,7 +3,9 @@ export const STARTUP_PHASES = [
3
3
  "schema", "source", "configuration", "control", "recovery", "journal", "bus", "memory", "model_runtime", "board",
4
4
  "task_checks", "task_ports", "task_board", "task_recovery",
5
5
  "task_runtime", "native_stop_seed", "budget", "usage_seed", "usage_rollup", "token_runtime", "token_seed",
6
- "services", "transcript_usage_seed", "ready", "post_ready",
6
+ "services", "transcript_usage_seed", "ready",
7
+ // #1445: the steps between ready and the end of start, each its own boundary; `post_ready` keeps what follows the last of them.
8
+ "post_ready_handoff", "post_ready_queue", "post_ready_watch", "post_ready_reconcile", "post_ready_goals", "post_ready_leases", "post_ready_crash", "post_ready_pi", "post_ready_drift", "post_ready",
7
9
  ] as const;
8
10
  export type StartupPhase = typeof STARTUP_PHASES[number];
9
11
 
@@ -243,6 +243,7 @@ export class SupervisionProposals {
243
243
  async observe(task: number): Promise<SupervisionProposal[]> {
244
244
  if (this.ports.isPrivate(task)) return [];
245
245
  const facts = await this.ports.facts(task);
246
+ if (this.ports.isPrivate(task)) return [];
246
247
  const side = facts.tasks.find((candidate) => candidate.id === task);
247
248
  if (!side) return [];
248
249
  const at = this.ports.now(), evaluation = evaluateSupervision(facts);
@@ -252,7 +253,11 @@ export class SupervisionProposals {
252
253
  const reading = evaluation.observations.filter((observation) => observation.task === task && !observation.limits.truncated);
253
254
  if (!clipped) {
254
255
  const fresh = new Set(reading.map(proposalKey));
255
- const stale = this.store.pendingFor(task).filter((proposal) => !fresh.has(proposal.key)).map((proposal) => proposal.id);
256
+ const covered = new Set(evaluation.evaluated.filter((entry) => entry.task === task).map((entry) => `${entry.rule}:${entry.revision}`));
257
+ const stale = this.store.pendingFor(task).filter((proposal) => {
258
+ const editRule = proposal.rule === "unverified_shell_write" || proposal.rule === "cascading_edit_after_failed_check";
259
+ return !fresh.has(proposal.key) && (!editRule || proposal.revision !== taskRevision(side).revision || covered.has(`${proposal.rule}:${proposal.revision}`));
260
+ }).map((proposal) => proposal.id);
256
261
  if (stale.length) this.store.expire(stale, "hub", at);
257
262
  }
258
263
  const added: SupervisionProposal[] = [];
@@ -330,7 +335,10 @@ export class SupervisionProposals {
330
335
  if (taskRevision(side).revision !== proposal.revision) return this.stale(proposal, "the task moved to another revision");
331
336
  if (this.ports.generation(proposal.task) !== proposal.generation) return this.stale(proposal, "the native session it was read under was replaced");
332
337
  // Recheck the input identity immediately before any effect: the same reading has to still hold now.
333
- if (!evaluateSupervision(facts).observations.some((observation) => proposalKey(observation) === proposal.key)) return this.stale(proposal, "the reading changed: new input replaced this proposal");
338
+ const reading = evaluateSupervision(facts);
339
+ if ((proposal.rule === "unverified_shell_write" || proposal.rule === "cascading_edit_after_failed_check")
340
+ && !reading.evaluated.some(entry => entry.task === proposal.task && entry.rule === proposal.rule && entry.revision === proposal.revision)) return { ok: false, error: "edit evidence unavailable; the proposal stays pending" };
341
+ if (!reading.observations.some((observation) => proposalKey(observation) === proposal.key)) return this.stale(proposal, "the reading changed: new input replaced this proposal");
334
342
  if (this.ports.held(proposal.task)) return { ok: false, error: "the owner has a needs_review delivery; resolve it before acting on this proposal" };
335
343
  // Authority is read again after the await: the board can move while the facts are being read, and a role or a
336
344
  // session that went away in that window must not run anything.
@@ -13,15 +13,18 @@ import type { DeliverableRecord } from "./deliverables.ts";
13
13
  */
14
14
 
15
15
  export const SUPERVISION_RULES = ["repeated_failure", "deliverable_invalidated_check", "declared_overlap_without_integration"] as const;
16
- export type SupervisionRuleId = (typeof SUPERVISION_RULES)[number];
16
+ /** Additive edit rules are evaluated only when a host supplies edit evidence. */
17
+ export const EDIT_SUPERVISION_RULES = ["unverified_shell_write", "cascading_edit_after_failed_check"] as const;
18
+ export const ALL_SUPERVISION_RULES = [...SUPERVISION_RULES, ...EDIT_SUPERVISION_RULES] as const;
19
+ export type SupervisionRuleId = (typeof ALL_SUPERVISION_RULES)[number];
17
20
  /** 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: 2, declared_overlap_without_integration: 1 };
21
+ export const SUPERVISION_RULE_VERSION: Readonly<Record<SupervisionRuleId, number>> = { repeated_failure: 1, deliverable_invalidated_check: 2, declared_overlap_without_integration: 1, unverified_shell_write: 1, cascading_edit_after_failed_check: 1 };
19
22
 
20
23
  /** The existing hub operation an observation names. T1 names one; nothing in this module runs it. */
21
24
  export const SUPERVISION_ACTIONS = ["escalate", "recheck", "request_integration"] as const;
22
25
  export type SupervisionAction = (typeof SUPERVISION_ACTIONS)[number];
23
26
  /** Closed reason codes: an observation says why it fired in a token, never in prose. */
24
- export const SUPERVISION_REASONS = ["repeated_failure", "stale_check", "unintegrated_overlap"] as const;
27
+ export const SUPERVISION_REASONS = ["repeated_failure", "stale_check", "unintegrated_overlap", "unverified_shell_write", "cascading_edit_after_failed_check"] as const;
25
28
  export type SupervisionReasonCode = (typeof SUPERVISION_REASONS)[number];
26
29
  /** Why a rule could not decide for one task and revision. A gap is not a trigger and never a zero. */
27
30
  export const SUPERVISION_GAPS = ["no-history", "no-deliverable-measurement", "history-truncated"] as const;
@@ -96,10 +99,14 @@ export interface SupervisionEvaluation {
96
99
  evaluated: EvaluatedRevision[];
97
100
  }
98
101
 
102
+ /** Text-free, in-memory edit evidence bound to an owner revision. */
103
+ export interface EditRevisionFact { task: number; revision: string; unverified: number; cascading: number }
104
+
99
105
  export interface SupervisionFacts {
100
106
  tasks: readonly TaskRevisionFacts[];
101
107
  deliverables?: readonly DeliverableMeasurementFact[];
102
108
  overlaps?: readonly DeclaredOverlapFact[];
109
+ edits?: readonly EditRevisionFact[];
103
110
  }
104
111
 
105
112
  /** Records one rule reads from one revision. A longer revision is read as a prefix and the observation says `truncated`. */
@@ -287,6 +294,22 @@ export function evaluateSupervision(facts: SupervisionFacts): SupervisionEvaluat
287
294
  if (!repeated.length) gaps.push(gapOf("repeated_failure", side.task.id, side.revision, "history-truncated"));
288
295
  if (!check.observation && !check.gap) gaps.push(gapOf("deliverable_invalidated_check", side.task.id, side.revision, "history-truncated"));
289
296
  }
297
+ for (const edit of facts.edits ?? []) {
298
+ const side = sides.get(edit.task);
299
+ if (!side || isClosedTaskState(side.task.state) || side.revision !== edit.revision) continue;
300
+ const rules = [
301
+ { rule: "unverified_shell_write" as const, count: edit.unverified },
302
+ { rule: "cascading_edit_after_failed_check" as const, count: edit.cascading },
303
+ ];
304
+ for (const item of rules) {
305
+ if (!Number.isSafeInteger(item.count) || item.count < 0) continue;
306
+ evaluated.push({ rule: item.rule, task: side.task.id, revision: side.revision });
307
+ if (side.limits.truncated) { gaps.push(gapOf(item.rule, side.task.id, side.revision, "history-truncated")); continue; }
308
+ if (item.count < REPEAT_FLOOR) continue;
309
+ observations.push({ rule: item.rule, version: SUPERVISION_RULE_VERSION[item.rule], task: side.task.id, revision: side.revision,
310
+ trigger: item.rule, refs: [], limits: side.limits, action: "recheck", reason: item.rule });
311
+ }
312
+ }
290
313
  for (const overlap of facts.overlaps ?? []) {
291
314
  const pair = unintegratedOverlap(overlap, sides);
292
315
  if (pair.evaluated) evaluated.push(pair.evaluated);
@@ -84,6 +84,13 @@ export class SupervisionFeed {
84
84
  return this.send(`task:${id}:${milestone}`, bits.join("; "), "status", id);
85
85
  }
86
86
 
87
+ /** R4: only ids and the fixed rule number enter the conductor's feed. */
88
+ roadmapFinding(taskId: number, milestone: number | null, rule: number, marker: string): boolean {
89
+ const task = this.d.tasks().find(row => row.id === taskId);
90
+ if (!task || !this.includes(task) || this.d.isPrivate(task) || milestone !== null && (!Number.isSafeInteger(milestone) || milestone < 1) || !Number.isSafeInteger(rule) || rule < 1 || rule > 8 || !/^[a-f0-9]{64}$/.test(marker)) return false;
91
+ return this.send(`roadmap:${marker}`, `roadmap${milestone === null ? "" : ` milestone ${milestone}`}, task ${taskId}: drift rule ${rule}; inspect ahub roadmap check`, "status", taskId);
92
+ }
93
+
87
94
  /** Only structured history metadata is read; notes may contain private content. */
88
95
  taskChanged(task: Task, entry: HistoryEntry, metadata: SupervisionFields = {}): void {
89
96
  const fields: SupervisionFields = { by: entry.by, owner: task.owner, ...(entry.reason ? { reason: entry.reason } : {}), ...metadata };