@staix/agent-hub 0.34.1 → 0.36.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 (213) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +53 -7
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/addons/claude-mem.md +4 -4
  5. package/docs/addons/open-code-review.md +1 -1
  6. package/docs/agent-notes/README.md +66 -0
  7. package/docs/agent-notes/adapters.md +14 -7
  8. package/docs/agent-notes/budget.md +1 -1
  9. package/docs/agent-notes/bus.md +2 -1
  10. package/docs/agent-notes/daemon.md +9 -7
  11. package/docs/agent-notes/local-worker.md +1 -1
  12. package/docs/agent-notes/models.md +5 -2
  13. package/docs/agent-notes/tasks.md +9 -2
  14. package/docs/agent-notes/tests.md +6 -0
  15. package/docs/design/adapters.md +182 -2
  16. package/docs/design/agent-hub-architecture.md +64 -2
  17. package/docs/design/agent-hub.md +6 -0
  18. package/docs/design/bus.md +26 -0
  19. package/docs/design/execution-reference.md +306 -0
  20. package/docs/design/guidance-experiments.md +438 -0
  21. package/docs/design/model-routes.md +628 -0
  22. package/docs/design/supervision.md +121 -0
  23. package/docs/design/task-board.md +121 -0
  24. package/docs/dogfood.md +45 -13
  25. package/docs/events.md +38 -20
  26. package/docs/memory.md +21 -7
  27. package/docs/operations.md +824 -40
  28. package/docs/profiles.md +2 -2
  29. package/docs/quickstart.md +117 -4
  30. package/docs/research.md +73 -13
  31. package/docs/roles.md +1 -1
  32. package/docs/sdlc.md +117 -11
  33. package/docs/security.md +153 -15
  34. package/docs/smoke.md +14 -0
  35. package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
  36. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  37. package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
  38. package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
  39. package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
  40. package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
  41. package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
  42. package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
  43. package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
  44. package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
  45. package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
  46. package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
  47. package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
  48. package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
  49. package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
  50. package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
  51. package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
  52. package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
  53. package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
  54. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
  55. package/docs/verification/2026-11-09-0.35.0.md +129 -0
  56. package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
  57. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  58. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  59. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  60. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  61. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  62. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  63. package/docs/verification/claude-permission-transport-native.py +10 -3
  64. package/docs/verification/claude-shell-wrapper-native.py +8 -8
  65. package/docs/verified.json +245 -15
  66. package/package.json +3 -3
  67. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  68. package/plugins/agent-hub/kimi-hook.js +21230 -0
  69. package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
  70. package/plugins/agent-hub/server.js +4359 -1071
  71. package/scripts/check-docs.mjs +12 -1
  72. package/src/adapters/acp-model-policy.ts +56 -0
  73. package/src/adapters/acp.ts +175 -5
  74. package/src/adapters/agy/entry.ts +8 -5
  75. package/src/adapters/agy/hooks.ts +65 -15
  76. package/src/adapters/channel-peer.ts +33 -1
  77. package/src/adapters/claude-channel.ts +7 -4
  78. package/src/adapters/claude-implementer.ts +16 -3
  79. package/src/adapters/codex-appserver.ts +118 -8
  80. package/src/adapters/codex-review-isolation.ts +3 -1
  81. package/src/adapters/compat.ts +18 -13
  82. package/src/adapters/definitions/builtin-metadata.ts +8 -1
  83. package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
  84. package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
  85. package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
  86. package/src/adapters/definitions/reviewer-variants.ts +3 -1
  87. package/src/adapters/kimi-review-policy-worker.js +2 -0
  88. package/src/adapters/kimi-review-policy-worker.ts +85 -0
  89. package/src/adapters/kimi-review-policy.ts +68 -0
  90. package/src/adapters/kimi-review.ts +41 -41
  91. package/src/adapters/kimi-tui-facts.ts +153 -0
  92. package/src/adapters/kimi-wire-usage.ts +33 -8
  93. package/src/adapters/local-worker.ts +60 -21
  94. package/src/adapters/model-token.ts +3 -0
  95. package/src/adapters/pi.ts +27 -5
  96. package/src/adapters/qwen-dual.ts +324 -44
  97. package/src/adapters/registry-types.ts +34 -3
  98. package/src/adapters/registry.ts +1 -0
  99. package/src/adapters/reviewer-policy-watch.ts +86 -0
  100. package/src/adapters/reviewer-print.ts +80 -18
  101. package/src/cli/agents.ts +1 -1
  102. package/src/cli/facts-hook.ts +4 -2
  103. package/src/cli/guidance.ts +67 -0
  104. package/src/cli/help.ts +13 -5
  105. package/src/cli/identity.ts +13 -3
  106. package/src/cli/init-prompt.ts +15 -2
  107. package/src/cli/init-required-checks.ts +122 -0
  108. package/src/cli/init-settings.ts +10 -4
  109. package/src/cli/init.ts +39 -3
  110. package/src/cli/kimi-facts-hook.ts +11 -0
  111. package/src/cli/kimi-plugin.ts +157 -0
  112. package/src/cli/lineage.ts +78 -0
  113. package/src/cli/main.ts +159 -19
  114. package/src/cli/model.ts +52 -0
  115. package/src/cli/output.ts +23 -1
  116. package/src/cli/reset.ts +1 -1
  117. package/src/cli/setup-research.ts +10 -0
  118. package/src/cli/status-lines.ts +8 -4
  119. package/src/hub/autonomy-defaults.ts +20 -9
  120. package/src/hub/board.ts +346 -4
  121. package/src/hub/budget.ts +1 -1
  122. package/src/hub/build-entry.ts +11 -0
  123. package/src/hub/bus.ts +52 -2
  124. package/src/hub/ci-watch.ts +4 -4
  125. package/src/hub/code-facts.ts +10 -3
  126. package/src/hub/completions.ts +3 -1
  127. package/src/hub/config-apply.ts +3 -1
  128. package/src/hub/config-trust.ts +1 -0
  129. package/src/hub/control-client.ts +1 -1
  130. package/src/hub/daemon.ts +1387 -121
  131. package/src/hub/deliverable-files.ts +38 -5
  132. package/src/hub/delivery-hints.ts +4 -2
  133. package/src/hub/delivery-journal.ts +50 -2
  134. package/src/hub/delivery-public.ts +51 -0
  135. package/src/hub/dogfood-profile.ts +9 -5
  136. package/src/hub/envelope.ts +1 -1
  137. package/src/hub/events.ts +28 -18
  138. package/src/hub/execution-lineage-owner.ts +272 -0
  139. package/src/hub/execution-lineage.ts +164 -0
  140. package/src/hub/execution-links.ts +85 -0
  141. package/src/hub/execution-reference.ts +36 -0
  142. package/src/hub/guidance-variants.ts +398 -0
  143. package/src/hub/handoff.ts +1 -0
  144. package/src/hub/hub-tools.ts +62 -2
  145. package/src/hub/instances.ts +4 -3
  146. package/src/hub/kimi-events.ts +46 -0
  147. package/src/hub/kimi-usage.ts +132 -29
  148. package/src/hub/lifecycle.ts +31 -15
  149. package/src/hub/limits.ts +13 -4
  150. package/src/hub/manager.ts +58 -3
  151. package/src/hub/memory-policy.ts +4 -3
  152. package/src/hub/memory-sync-attestation.ts +54 -0
  153. package/src/hub/memory-sync-state.ts +20 -5
  154. package/src/hub/model-overrides.ts +115 -0
  155. package/src/hub/native-hook-launch.ts +12 -3
  156. package/src/hub/operational-view.ts +2 -2
  157. package/src/hub/peers.ts +28 -1
  158. package/src/hub/permission-mode.ts +1 -1
  159. package/src/hub/person-figures.ts +88 -0
  160. package/src/hub/planning.ts +1 -1
  161. package/src/hub/progress.ts +24 -7
  162. package/src/hub/report.ts +38 -4
  163. package/src/hub/research-dataset.ts +158 -0
  164. package/src/hub/research-memory.ts +68 -0
  165. package/src/hub/research-quality.ts +118 -0
  166. package/src/hub/research-record.ts +279 -0
  167. package/src/hub/research.ts +126 -27
  168. package/src/hub/restart.ts +27 -0
  169. package/src/hub/roles.ts +26 -0
  170. package/src/hub/routing.ts +4 -1
  171. package/src/hub/sdlc-merge.ts +39 -1
  172. package/src/hub/sdlc-release.ts +1 -1
  173. package/src/hub/sdlc.ts +62 -11
  174. package/src/hub/settings.ts +5 -0
  175. package/src/hub/startup-event-seeds.ts +51 -0
  176. package/src/hub/startup-readiness.ts +65 -0
  177. package/src/hub/startup-timing.ts +38 -0
  178. package/src/hub/supervision-proposals.ts +405 -0
  179. package/src/hub/supervision-rules.ts +388 -0
  180. package/src/hub/supervision.ts +2 -0
  181. package/src/hub/task-approval.ts +2 -2
  182. package/src/hub/task-repository.ts +5 -0
  183. package/src/hub/tasks.ts +632 -59
  184. package/src/hub/ui.ts +9 -5
  185. package/src/hub/visual-assets.ts +50 -0
  186. package/src/hub/visual.ts +257 -0
  187. package/src/memory/brief.ts +169 -14
  188. package/src/memory/capture.ts +4 -3
  189. package/src/memory/recall.ts +46 -5
  190. package/src/memory/record-provenance.ts +82 -0
  191. package/src/memory/records.ts +116 -0
  192. package/src/models/relay.ts +9 -2
  193. package/src/models/route/adec.ts +190 -0
  194. package/src/models/route/config.ts +64 -3
  195. package/src/models/route/decision-evidence.ts +83 -0
  196. package/src/models/route/decision.ts +215 -0
  197. package/src/models/route/relay-selector.ts +8 -7
  198. package/src/models/route/runtime.ts +35 -22
  199. package/src/models/route/stage-diagnostics.ts +22 -0
  200. package/src/models/route/stage-evidence.ts +55 -0
  201. package/src/models/route/stage-fallback.ts +58 -0
  202. package/src/models/route/stage-input.ts +155 -0
  203. package/src/models/route/stage.ts +5 -147
  204. package/src/ui/guidance-panel.ts +156 -0
  205. package/src/ui/guidance-view.ts +43 -0
  206. package/src/ui/index.html +134 -6
  207. package/src/ui/lineage-view.ts +34 -0
  208. package/src/ui/plugin.ts +136 -11
  209. package/templates/AGENTS.block.md +1 -1
  210. package/templates/config.json +1 -1
  211. package/templates/profiles/general.json +1 -1
  212. package/templates/profiles/research.json +1 -1
  213. package/templates/profiles/writing.json +1 -1
@@ -5,13 +5,21 @@ import type { RoleIdentity, StampedEvent } from "./events.ts";
5
5
  import { hubHome } from "./project.ts";
6
6
  import { ADDONS, addonState, type Addon, type AddonName } from "./tooling.ts";
7
7
  import { MIN_ATTEMPTS, mulberry32 } from "./bench.ts";
8
+ import { UNKNOWN_MEMORY_FIGURES } from "./research-memory.ts";
9
+ import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, type PersonCounts } from "./person-figures.ts";
10
+ import { closedId, journalFigures, mergeBlock, NO_EVIDENCE, reviewBlock, specsBlock, type CancelCause, type CohortKind, type DeliveryBlock, type HandoffsBlock, type MemoryBlock, type MergeBlock, type PersonBlock, type ResearchEvidence, type ReviewBlock, type SpecsBlock, cancelCauseOf } from "./research-record.ts";
11
+ export type { CancelCause, CohortKind, DeliveryBlock, HandoffsBlock, MemoryBlock, MergeBlock, PersonBlock, ResearchEvidence, ReviewBlock, SpecsBlock } from "./research-record.ts";
8
12
 
9
13
  /**
10
14
  * #247: opt-in research records of how tasks went, built only from `events.jsonl` (ids, states, counts, tokens), so the
11
15
  * live writer and `ahub research backfill` produce the same records. Never a title, detail, plan, note, path, message
12
16
  * body or check output: the events carry none of those.
13
17
  */
14
- export const RESEARCH_SCHEMA = "agent-hub.research/v1";
18
+ /** v1 rows (approved tasks only, no review, delivery, merge, specs, memory or person block) stay readable; every row written now is v2 (#1277). */
19
+ export const RESEARCH_SCHEMA_V1 = "agent-hub.research/v1";
20
+ export const RESEARCH_SCHEMA = "agent-hub.research/v2";
21
+ export type ResearchSchema = typeof RESEARCH_SCHEMA | typeof RESEARCH_SCHEMA_V1;
22
+ const SCHEMAS: readonly string[] = [RESEARCH_SCHEMA_V1, RESEARCH_SCHEMA];
15
23
  export const LABELS = ["ok", "regressed", "reverted", "incomplete", "wrong", "abandoned"] as const;
16
24
  export type Label = (typeof LABELS)[number];
17
25
  /** A person's later verdict that turns an approved task into a failure. */
@@ -19,16 +27,22 @@ const FAILED: ReadonlySet<string> = new Set(["regressed", "reverted", "incomplet
19
27
 
20
28
  export interface PeerUsage { input: number | null; output: number | null; cacheRead: number | null; total: number | null }
21
29
  export interface TaskRecord {
22
- schema: typeof RESEARCH_SCHEMA; kind: "task"; project: string; task: number;
30
+ schema: ResearchSchema; kind: "task"; project: string; task: number;
23
31
  profile?: string; profileClass?: string;
24
32
  release?: number | null; priority?: number | null; plannedStart?: number | null; due?: number | null;
25
33
  role?: string; roleIdentity?: { id: string; layer: "shipped" | "project"; hash: string };
26
34
  /** Native preamble preparations frozen at each attributed turn's start, never proof of model consumption. */
27
35
  sessionRoles?: { peer: string; turn: string; roles: RoleIdentity[] | null }[];
28
- class: string | null; pii: boolean; outcome: "approved";
36
+ class: string | null; pii: boolean;
37
+ /** #1277 AC6: every task in a terminal board state has a record. A v1 row is always `approved`. Statistics about approved tasks filter on this. */
38
+ outcome: "approved" | "cancelled";
29
39
  /** The proposal time also tells a task from an earlier one with the same id after `ahub reset --all`. */
30
- createdAt: string | null; startedAt: string | null; approvedAt: string;
31
- /** From the first `in_progress` to the approval; null when the start is not in the events. */
40
+ createdAt: string | null; startedAt: string | null;
41
+ /** Null on a cancelled record. */
42
+ approvedAt: string | null;
43
+ /** When the task reached its terminal state (v2); a v1 row reads as its `approvedAt`. */
44
+ closedAt?: string;
45
+ /** From the first `in_progress` to the terminal state; null when the start is not in the events. */
32
46
  wallMs: number | null;
33
47
  /** Sum of the attributed turns' durations, the turns still open at the approval included. */
34
48
  activeMs: number;
@@ -57,9 +71,30 @@ export interface TaskRecord {
57
71
  peers?: string[];
58
72
  /** #258 AC11: task briefs handed over for it, and how many of them carried a hub-memory fail note; absent without briefs. */
59
73
  briefs?: { delivered: number; withFail: number };
74
+ /** #1277 (v2). Every block is a count, a duration or a closed value; a value that cannot be derived is null and counted as unknown by the quality report, never 0. */
75
+ /** Only on a cancelled record: an explicit closed cause the board retains, else `unknown`. Never inferred from a decline, an escalation or the cancellation note. */
76
+ cancelCause?: CancelCause;
77
+ /** Intermediate declines and escalations (history events, not terminal), counted on every record next to `reassignments`. */
78
+ declines?: number; escalations?: number;
79
+ review?: ReviewBlock; delivery?: DeliveryBlock; merge?: MergeBlock; specs?: SpecsBlock; memory?: MemoryBlock; person?: PersonBlock;
80
+ /** Persisted idle-ladder entries on the task's board history (the stall table itself is cleared when a task closes); null without the board. */
81
+ stalls?: number | null;
82
+ handoffs?: HandoffsBlock; cohort?: CohortKind;
60
83
  }
84
+ /** A record carries merge figures when any of them is known. */
85
+ const mergeKnown = (r: TaskRecord): boolean => !!r.merge && (r.merge.ciRuns !== null || r.merge.ciReruns !== null || r.merge.githubReviews !== null || r.merge.approvedToMergedMs !== null);
86
+ /** True when `next` has merge figures the held record of the same task lacks. */
87
+ export const fillsMerge = (held: TaskRecord, next: TaskRecord): boolean => next.schema === RESEARCH_SCHEMA && !mergeKnown(held) && mergeKnown(next);
88
+
89
+ /** The latest record of each task (a later row of the same task replaces an earlier one), in order of first appearance. */
90
+ export function latestTaskRecords(records: readonly ResearchRecord[]): TaskRecord[] {
91
+ const latest = new Map<string, TaskRecord>();
92
+ for (const r of records) if (r.kind === "task") latest.set(recordKey(r), r);
93
+ return [...latest.values()];
94
+ }
95
+
61
96
  /** A person's later verdict on one task record: `createdAt` binds it to that task, not a later one with the same id. `by`: the agent that labelled its own task (#933); absent for the person. */
62
- export interface LabelRecord { schema: typeof RESEARCH_SCHEMA; kind: "label"; project: string; task: number; createdAt: string; label: Label; at: string; by?: string }
97
+ export interface LabelRecord { schema: ResearchSchema; kind: "label"; project: string; task: number; createdAt: string; label: Label; at: string; by?: string }
63
98
  export type ResearchRecord = TaskRecord | LabelRecord;
64
99
 
65
100
  /** The store name for a project: a hash of its id, never its path. */
@@ -67,29 +102,43 @@ export const projectKey = (projectId: string): string => createHash("sha256").up
67
102
  export const researchDir = (home = hubHome()): string => join(home, "research");
68
103
  export const researchFile = (projectId: string, home = hubHome()): string => join(researchDir(home), `${projectKey(projectId)}.jsonl`);
69
104
  /** One task across every record about it: a task id is reused after `ahub reset --all`, its proposal time is not. */
70
- export const recordKey = (r: { project: string; task: number; createdAt: string | null; approvedAt?: string }): string => `${r.project}#${r.task}@${r.createdAt ?? r.approvedAt ?? ""}`;
105
+ export const recordKey = (r: { project: string; task: number; createdAt: string | null; approvedAt?: string | null; closedAt?: string }): string => `${r.project}#${r.task}@${r.createdAt ?? r.approvedAt ?? r.closedAt ?? ""}`;
106
+ /** When a record's task closed: v2 says so, a v1 row is approved-only and closed at its approval. */
107
+ export const closedAtOf = (r: TaskRecord): string | null => r.closedAt ?? r.approvedAt;
71
108
 
72
- type Acc = Omit<TaskRecord, "schema" | "kind" | "project" | "approvedAt" | "wallMs" | "firstPass" | "outcome" | "writer" | "models" | "tooling" | "peers" | "briefs"> & {
109
+ type V2Fields = "closedAt" | "cancelCause" | "declines" | "escalations" | "review" | "delivery" | "merge" | "specs" | "memory" | "person" | "stalls" | "handoffs" | "cohort";
110
+ type Acc = Omit<TaskRecord, "schema" | "kind" | "project" | "approvedAt" | "wallMs" | "firstPass" | "outcome" | "writer" | "models" | "tooling" | "peers" | "briefs" | "person" | V2Fields> & {
73
111
  models: Set<string>; approvedAt: string | null; lastState: string | null; tooling: Record<string, Addon[]>; peers: Map<string, number>; briefs: { delivered: number; withFail: number };
112
+ /** #1278: the counts of the four attributed person events; joined with whether the log covers the task at the end. */
113
+ person: PersonCounts;
114
+ /** #1277: what the events alone say; the board and journal evidence is joined at the end. */
115
+ cancelledAt: string | null; declines: number; escalations: number; lastDoneMs: number | null; envelopes: number; dropped: { fyi: number; hop: number };
116
+ briefNotes: number; briefFails: number; cohort: "silent" | "advisory" | null;
74
117
  };
75
118
  /** Keyed by peer ids, model names and reasons, any of which may be `constructor` or `__proto__`: no prototype to inherit from. */
76
119
  const keyed = <T>(): Record<string, T> => Object.create(null) as Record<string, T>;
77
120
  const blank = (task: number): Acc => ({ task, class: null, pii: false, createdAt: null, startedAt: null, activeMs: 0, owners: [], reviewer: null,
78
121
  reviewRounds: 0, changesRequested: 0, checkPassed: 0, checkFailed: 0, dones: 0, reassignments: 0, reassignedBy: keyed(), stuck: 0, overlaps: 0, conflicts: 0,
79
122
  tests: { pass: 0, fail: 0 }, tokens: { total: 0, byPeer: keyed(), byAttribution: keyed() }, usage: keyed(), usageByModel: keyed(), turns: 0, filesChanged: 0, models: new Set(),
80
- approvedAt: null, lastState: null, tooling: keyed(), peers: new Map(), briefs: { delivered: 0, withFail: 0 } });
123
+ approvedAt: null, lastState: null, tooling: keyed(), peers: new Map(), briefs: { delivered: 0, withFail: 0 }, person: emptyPersonCounts(),
124
+ cancelledAt: null, declines: 0, escalations: 0, lastDoneMs: null, envelopes: 0, dropped: { fyi: 0, hop: 0 }, briefNotes: 0, briefFails: 0, cohort: null });
81
125
  const add = (current: number | null, value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? (current ?? 0) + value : current;
82
126
  const bump = (counts: Record<string, number>, key: string, n = 1) => { counts[key] = (counts[key] ?? 0) + n; };
83
127
 
84
128
  /**
85
- * One record per approved task in `events`. Approval is final on the board, so everything attributed to the task
129
+ * One record per task that reached a terminal board state in `events`: approved, or cancelled (#1277 AC6). Approval is final on the board, so everything attributed to the task
86
130
  * counts, also after the approval: the turn that approved it ends later, and its usage arrives after that. The live
87
- * writer therefore waits for those turns (daemon `recordResearch`); backfill reads to the end of the file.
131
+ * writer therefore waits for those turns (daemon `recordResearch`); backfill reads to the end of the file. `evidence` (the board's history and the delivery journal,
132
+ * read-only and closed fields only, `readEvidence`) fills the review, merge, spec and delivery-state blocks; without it those fields are null, not 0. A task that was approved
133
+ * and later reopened keeps its approved record, as before.
88
134
  */
89
- export function taskRecords(events: StampedEvent[], projectId: string, writer: TaskRecord["writer"]): TaskRecord[] {
135
+ export function taskRecords(events: StampedEvent[], projectId: string, writer: TaskRecord["writer"], evidence: ResearchEvidence = NO_EVIDENCE): TaskRecord[] {
90
136
  const tasks = new Map<number, Acc>(), earlier: Acc[] = [];
91
137
  const acc = (id: number) => { let a = tasks.get(id); if (!a) tasks.set(id, a = blank(id)); return a; };
92
138
  const seenUsage = new Set<string>();
139
+ let briefReporting = false;
140
+ // #1278: the time of the first hub run that attributes person events. A task that began before it has an unknown person block (see `startsAttribution`).
141
+ let personReportingSince: number | null = null;
93
142
  // A fingerprint belongs to one attachment of its peer: from a state event that brings it online to the next offline.
94
143
  // Detection settles in the background, so it can arrive after the peer's first work in that attachment.
95
144
  const attach = new Map<string, number>(), online = new Set<string>();
@@ -109,7 +158,7 @@ export function taskRecords(events: StampedEvent[], projectId: string, writer: T
109
158
  };
110
159
  for (const e of events) {
111
160
  // A crash writes no offline: a new run is a new attachment, and no fingerprint from before it describes later work.
112
- if (e.type === "hub_start") { online.clear(); tooling.clear(); continue; }
161
+ if (e.type === "hub_start") { online.clear(); tooling.clear(); if (startsAttribution(e)) personReportingSince ??= Date.parse(e.at); continue; }
113
162
  if (e.type === "state") {
114
163
  if (e.state === "offline") online.delete(e.peer);
115
164
  else if (!online.has(e.peer)) { online.add(e.peer); attach.set(e.peer, (attach.get(e.peer) ?? 0) + 1); }
@@ -121,6 +170,15 @@ export function taskRecords(events: StampedEvent[], projectId: string, writer: T
121
170
  for (const a of tasks.values()) if (a.peers.get(e.peer) === now) a.tooling[e.peer] = e.addons;
122
171
  continue;
123
172
  }
173
+ if (e.type === "envelope") {
174
+ // An envelope names its task as a string; a count of them, and of the ones the bus dropped, is all the record keeps.
175
+ if (typeof e.task === "string" && /^[1-9]\d{0,9}$/.test(e.task)) { const a = acc(Number(e.task)); a.envelopes++; if (e.dropped === "fyi" || e.dropped === "hop") a.dropped[e.dropped]++; }
176
+ continue;
177
+ }
178
+ if (e.type === "cohort") {
179
+ for (const id of e.tasks) if (Number.isSafeInteger(id) && id > 0) { const a = acc(id); if (e.silent) a.cohort = "silent"; else a.cohort ??= "advisory"; }
180
+ continue;
181
+ }
124
182
  if (e.type === "task") {
125
183
  const proposed = e.event === "proposed" || e.event === "backlog pulled";
126
184
  // Ids restart after `ahub reset --all` archives the events, but a file that kept both starts the task anew.
@@ -136,16 +194,25 @@ export function taskRecords(events: StampedEvent[], projectId: string, writer: T
136
194
  if (e.reviewer) a.reviewer = e.reviewer;
137
195
  if (proposed) a.createdAt ??= e.at;
138
196
  if (e.state === "in_progress") a.startedAt ??= e.at;
139
- if (e.event === "done") a.dones++;
197
+ if (e.event === "done") { a.dones++; if (a.approvedAt === null) a.lastDoneMs = Date.parse(e.at); }
198
+ if (e.event === "declined") a.declines++;
199
+ if (e.event === "escalated") a.escalations++;
140
200
  if (e.event === "check passed") a.checkPassed++;
141
201
  if (e.event === "check failed") a.checkFailed++;
142
202
  if (e.state === "in_review" && a.lastState !== "in_review") a.reviewRounds++;
143
203
  if (e.state === "changes_requested" && a.lastState !== "changes_requested") a.changesRequested++;
144
204
  if (e.state === "approved") a.approvedAt ??= e.at;
205
+ if (e.state === "cancelled" && a.lastState !== "cancelled") a.cancelledAt = e.at;
145
206
  a.lastState = e.state;
146
207
  involve(a, e.by); involve(a, e.owner, false); involve(a, e.reviewer, false);
147
208
  continue;
148
209
  }
210
+ if (isPersonEvent(e)) {
211
+ // Before the generic path on purpose: a permission or a question does not make its peer a worker on the task (`peers`, `tooling`).
212
+ const owner = personTask(e);
213
+ if (owner !== undefined) { const a = acc(owner); if (e.pii) a.pii = true; addPersonEvent(a.person, e); }
214
+ continue;
215
+ }
149
216
  const task = "task" in e && typeof e.task === "number" ? e.task : undefined;
150
217
  if (task === undefined) continue;
151
218
  const a = acc(task);
@@ -168,22 +235,45 @@ export function taskRecords(events: StampedEvent[], projectId: string, writer: T
168
235
  }
169
236
  else if (e.type === "route") a.models.add(e.route);
170
237
  else if (e.type === "route_outcome") { if (e.next?.tests === "pass") a.tests.pass++; if (e.next?.tests === "fail") a.tests.fail++; }
171
- else if (e.type === "memory_brief") { a.briefs.delivered++; if (e.fails > 0) a.briefs.withFail++; }
238
+ else if (e.type === "memory_brief") { briefReporting = true; a.briefs.delivered++; if (e.fails > 0) a.briefs.withFail++; a.briefNotes += (Number.isSafeInteger(e.native) ? e.native : 0) + (Number.isSafeInteger(e.claudeMem) ? e.claudeMem : 0); a.briefFails += Number.isSafeInteger(e.fails) ? e.fails : 0; }
172
239
  else if (e.type === "stuck") a.stuck++;
173
240
  else if (e.type === "overlap") a.overlaps++;
174
241
  else if (e.type === "conflict") a.conflicts++;
175
242
  }
176
243
  const out: TaskRecord[] = [];
177
244
  for (const a of [...earlier, ...tasks.values()]) {
178
- if (!a.approvedAt) continue;
179
- const { approvedAt, lastState: _state, models, tooling: fingerprints, peers, briefs, ...rest } = a;
180
- const start = a.startedAt ? Date.parse(a.startedAt) : NaN, end = Date.parse(approvedAt);
181
- out.push({ schema: RESEARCH_SCHEMA, kind: "task", project: projectKey(projectId), ...rest, outcome: "approved", approvedAt,
245
+ // Approved wins over a later reopening (the record the live writer stored at the approval); otherwise the task must end cancelled.
246
+ const outcome: "approved" | "cancelled" | undefined = a.approvedAt ? "approved" : a.lastState === "cancelled" && a.cancelledAt ? "cancelled" : undefined;
247
+ if (!outcome) continue;
248
+ const { person, approvedAt, lastState: _state, models, tooling: fingerprints, peers, briefs, cancelledAt, declines, escalations, lastDoneMs, envelopes, dropped, briefNotes, briefFails, cohort, ...rest } = a;
249
+ const closedAt = (outcome === "approved" ? approvedAt : cancelledAt)!;
250
+ const start = a.startedAt ? Date.parse(a.startedAt) : NaN, end = Date.parse(closedAt);
251
+ const task = evidence.tasks.get(a.task), board = evidence.board;
252
+ const began = a.createdAt ? Date.parse(a.createdAt) : a.startedAt ? Date.parse(a.startedAt) : NaN;
253
+ const covered = personCoverage(personReportingSince, began);
254
+ const ownerFamily = closedId(a.owners.at(-1) ? evidence.familyOf?.(a.owners.at(-1)!) : undefined);
255
+ const approvedMs = outcome === "approved" ? Date.parse(approvedAt!) : null;
256
+ const created = a.createdAt ? Date.parse(a.createdAt) : NaN;
257
+ const journal = journalFigures(evidence, a.task, Number.isFinite(created) ? created : null, Number.isFinite(end) ? end : 0);
258
+ const review = reviewBlock(task, board, ownerFamily, a.pii);
259
+ // The events say whether the task went to review at all; a board that cannot say leaves the round count unknown.
260
+ out.push({ schema: RESEARCH_SCHEMA, kind: "task", project: projectKey(projectId), ...rest, outcome, approvedAt: approvedAt ?? null, closedAt,
182
261
  wallMs: Number.isFinite(start) && Number.isFinite(end) && end >= start ? end - start : null,
183
- firstPass: a.changesRequested === 0 && a.checkFailed === 0 && a.reviewRounds <= 1, models: [...models].sort(), writer,
184
- ...(Object.keys(fingerprints).length ? { tooling: fingerprints, peers: [...peers.keys()].sort() } : {}), ...(briefs.delivered ? { briefs } : {}) });
262
+ firstPass: outcome === "approved" && a.changesRequested === 0 && a.checkFailed === 0 && a.reviewRounds <= 1, models: [...models].sort(), writer,
263
+ ...(Object.keys(fingerprints).length ? { tooling: fingerprints, peers: [...peers.keys()].sort() } : {}), ...(briefs.delivered ? { briefs } : {}),
264
+ ...(outcome === "cancelled" ? { cancelCause: task?.history.findLast(entry => entry.event === "cancelled")?.cause ?? "unknown" } : {}),
265
+ declines, escalations, review,
266
+ delivery: { count: envelopes, ...journal, dropped: { fyi: dropped.fyi, hop: dropped.hop } },
267
+ merge: mergeBlock(task, lastDoneMs, approvedMs),
268
+ specs: specsBlock(task, a.pii),
269
+ // A task with no brief is a known 0 only when the log shows briefs were being reported at all (memory on); otherwise nothing says whether one was built.
270
+ memory: { briefs: briefs.delivered || (briefReporting ? 0 : null), briefNotes: briefs.delivered ? briefNotes : briefReporting ? 0 : null, fails: briefs.delivered ? briefFails : briefReporting ? 0 : null, ...(evidence.memory?.(a.task) ?? UNKNOWN_MEMORY_FIGURES) },
271
+ person: personFigures(person, covered),
272
+ stalls: task && board ? task.history.filter(entry => entry.sweep).length : null,
273
+ handoffs: task?.handoffs ? { in: task.handoffs.in, out: task.handoffs.out } : { in: null, out: null },
274
+ cohort: cohort ?? "none" });
185
275
  }
186
- return out.sort((x, y) => x.approvedAt.localeCompare(y.approvedAt) || x.task - y.task);
276
+ return out.sort((x, y) => closedAtOf(x)!.localeCompare(closedAtOf(y)!) || x.task - y.task);
187
277
  }
188
278
 
189
279
  /** Every record in one store file; a line that does not parse is skipped. */
@@ -191,9 +281,13 @@ export function readStore(file: string): ResearchRecord[] {
191
281
  if (!existsSync(file)) return [];
192
282
  return readFileSync(file, "utf8").split("\n").flatMap((line) => {
193
283
  if (!line.trim()) return [];
194
- try { const r = JSON.parse(line); return r?.schema === RESEARCH_SCHEMA ? [r as ResearchRecord] : []; } catch { return []; }
284
+ try { const r = JSON.parse(line); return SCHEMAS.includes(r?.schema) ? [normalize(r)] : []; } catch { return []; }
195
285
  });
196
286
  }
287
+ /** A v1 task row predates `outcome` and was written only at an approval, so it reads as approved; the file itself is never rewritten. */
288
+ function normalize(r: ResearchRecord): ResearchRecord {
289
+ return r.kind === "task" && r.schema === RESEARCH_SCHEMA_V1 && r.outcome === undefined ? { ...r, outcome: "approved" } : r;
290
+ }
197
291
  /** This project's store, or every project's with `all`. */
198
292
  export function readStores(projectId: string | undefined, home = hubHome()): ResearchRecord[] {
199
293
  if (projectId) return readStore(researchFile(projectId, home));
@@ -208,8 +302,10 @@ export function appendRecords(projectId: string, records: ResearchRecord[], home
208
302
  const file = researchFile(projectId, home);
209
303
  mkdirSync(researchDir(home), { recursive: true, mode: 0o700 });
210
304
  chmodSync(researchDir(home), 0o700); // mkdir's mode applies only when it creates the directory
211
- const held = new Set(readStore(file).flatMap((r) => r.kind === "task" ? [recordKey(r)] : []));
212
- const added = records.filter((r) => r.kind === "label" || !held.has(recordKey(r)));
305
+ // A v2 row replaces a held v1 row of the same task (readers keep the latest per task). A held v2 row is final, as a held row always was, with one exception: the live writer
306
+ // records a task at its approval and the guarded merge writes its receipt later, so a later pass may append the same task with the merge figures it could not know then.
307
+ const held = new Map(readStore(file).flatMap((r) => r.kind === "task" && r.schema === RESEARCH_SCHEMA ? [[recordKey(r), r] as const] : []));
308
+ const added = records.filter((r) => r.kind === "label" || r.schema !== RESEARCH_SCHEMA || !held.has(recordKey(r)) || fillsMerge(held.get(recordKey(r))!, r));
213
309
  if (!added.length) return 0;
214
310
  appendFileSync(file, added.map((r) => JSON.stringify(r)).join("\n") + "\n", { mode: 0o600 });
215
311
  chmodSync(file, 0o600);
@@ -224,7 +320,9 @@ export function appendRecords(projectId: string, records: ResearchRecord[], home
224
320
  */
225
321
  export function labelTarget(records: ResearchRecord[], events: StampedEvent[], task: number, created?: string): TaskRecord {
226
322
  // A record without a proposal time (its proposal was not in the events) cannot be told apart, so it takes no label.
227
- const mine = records.filter((r): r is TaskRecord => r.kind === "task" && r.task === task && r.createdAt !== null);
323
+ // A label is a verdict on an approved task: a cancelled record takes none.
324
+ // One candidate per task: a later revision of a record (the merge figures filled in, or a v2 row over a v1 one) is the same task, and listing it twice would refuse an unambiguous historical label.
325
+ const mine = latestTaskRecords(records).filter((r) => r.outcome === "approved" && r.task === task && r.createdAt !== null);
228
326
  if (created !== undefined) {
229
327
  return mine.find((r) => r.createdAt === created) ?? fail(`no research record for task #${task} proposed at ${created}${mine.length ? ` (it has: ${mine.map((r) => r.createdAt).join(", ")})` : ""}`);
230
328
  }
@@ -311,7 +409,8 @@ const labelValues = (labels: Map<string, LabelRecord>): Map<string, Label> => ne
311
409
  /** Each approved task once, its last record, and every task's effective label: what both reports count. */
312
410
  function latestRecords(records: ResearchRecord[], since: number): { all: TaskRecord[]; labels: Map<string, Label> } {
313
411
  const latest = new Map<string, TaskRecord>();
314
- for (const r of records) if (r.kind === "task" && Date.parse(r.approvedAt) >= since) latest.set(recordKey(r), r);
412
+ // Statistics about approved tasks: a cancelled record (#1277) is another outcome and never counts here.
413
+ for (const r of records) if (r.kind === "task" && r.outcome === "approved" && Date.parse(r.approvedAt!) >= since) latest.set(recordKey(r), r);
315
414
  return { all: [...latest.values()], labels: labelValues(effectiveLabels(records)) };
316
415
  }
317
416
 
@@ -46,6 +46,9 @@ export interface RestartSnapshot {
46
46
  manualPaused: PeerId[];
47
47
  boardDigest: string;
48
48
  budgetDigest: string;
49
+ modelOverrides?: { count: number; digest: string };
50
+ guidanceVariants?: { experiments: number; variants: number; digest: string };
51
+ executionReferences?: { count: number; digest: string };
49
52
  /** Whole captured binding set; portable identities are covered alongside queue/board integrity. */
50
53
  externalBindingsDigest?: string;
51
54
  /** Research state remains part of controlled-recovery integrity when present. */
@@ -56,6 +59,8 @@ export interface RestartSnapshot {
56
59
  researchRunners?: { count: number; digest: string };
57
60
  researchEvidence?: { links: number; revisions: number; digest: string };
58
61
  reviewComments?: { comments: number; packages: number; digest: string };
62
+ /** Stored visual payloads and image metadata, never external image bytes. */
63
+ visuals?: { count: number; digest: string };
59
64
  };
60
65
  }
61
66
 
@@ -106,6 +111,22 @@ export function readRestartSnapshot(stateDir: string, expected: RestartReadExpec
106
111
  if (s.peers.some(peer => Object.hasOwn(peer, "controlProtocol") && (typeof peer.controlProtocol !== "number" || !Number.isSafeInteger(peer.controlProtocol) || peer.controlProtocol < 1))) return undefined;
107
112
  if (s.integrity !== undefined && (!s.integrity || typeof s.integrity !== "object" || typeof s.integrity.boardDigest !== "string" || typeof s.integrity.budgetDigest !== "string" || !Array.isArray(s.integrity.manualPaused) || !s.integrity.manualPaused.every((id) => typeof id === "string") || !s.integrity.queues || typeof s.integrity.queues !== "object" || !Object.values(s.integrity.queues).every((ids) => Array.isArray(ids) && ids.every((id) => typeof id === "string")))) return undefined;
108
113
  if (s.integrity && Object.hasOwn(s.integrity, "externalBindingsDigest") && (typeof s.integrity.externalBindingsDigest !== "string" || !/^[a-f0-9]{64}$/.test(s.integrity.externalBindingsDigest))) return undefined;
114
+ if (s.integrity && Object.hasOwn(s.integrity, "modelOverrides")) {
115
+ const value = s.integrity.modelOverrides;
116
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "count,digest"
117
+ || !Number.isSafeInteger(value.count) || value.count < 0 || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
118
+ }
119
+ if (s.integrity && Object.hasOwn(s.integrity, "guidanceVariants")) {
120
+ const value = s.integrity.guidanceVariants;
121
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "digest,experiments,variants"
122
+ || !Number.isSafeInteger(value.experiments) || value.experiments < 0 || !Number.isSafeInteger(value.variants) || value.variants < value.experiments
123
+ || typeof value.digest !== "string" || value.digest.length !== 64 || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
124
+ }
125
+ if (s.integrity && Object.hasOwn(s.integrity, "executionReferences")) {
126
+ const value = s.integrity.executionReferences;
127
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "count,digest"
128
+ || !Number.isSafeInteger(value.count) || value.count < 0 || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
129
+ }
109
130
  if (s.integrity && Object.hasOwn(s.integrity, "research")) {
110
131
  const research = s.integrity.research;
111
132
  if (!research || typeof research !== "object" || Array.isArray(research)
@@ -144,6 +165,12 @@ export function readRestartSnapshot(stateDir: string, expected: RestartReadExpec
144
165
  || ![value.comments, value.packages].every(count => Number.isSafeInteger(count) && count >= 0)
145
166
  || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
146
167
  }
168
+ if (s.integrity && Object.hasOwn(s.integrity, "visuals")) {
169
+ const value = s.integrity.visuals;
170
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !["count", "digest"].includes(key))
171
+ || !Number.isSafeInteger(value.count) || value.count < 0
172
+ || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
173
+ }
147
174
  if (bus.journal !== undefined) { try { validateJournalSnapshot(bus.journal); } catch { return undefined; } }
148
175
  return s as RestartSnapshot;
149
176
  }
package/src/hub/roles.ts CHANGED
@@ -14,6 +14,16 @@ export interface CatalogRole {
14
14
  body: string; review: string; layer: "shipped" | "project"; hash: string;
15
15
  }
16
16
  export interface RoleCatalog { roles: Map<string, CatalogRole>; errors: { id: string; reason: string }[] }
17
+ export interface RoleSectionSpan {
18
+ readonly name: typeof ROLE_SECTIONS[number];
19
+ readonly startUtf16: number; readonly endUtf16: number; readonly contentStartUtf16: number;
20
+ readonly headingRaw: string; readonly contentRaw: string; readonly raw: string;
21
+ }
22
+ export interface RoleDocument {
23
+ readonly role: Readonly<CatalogRole>;
24
+ readonly rawHeader: string; readonly bodyPrefix: string;
25
+ readonly sections: readonly RoleSectionSpan[];
26
+ }
17
27
  /** Flat headers are data, never YAML execution or authority configuration. */
18
28
  export function parseRole(text: string, stem: string, layer: CatalogRole["layer"]): CatalogRole {
19
29
  if (Buffer.byteLength(text) > 8192 || text.includes("\r") || !ID.test(stem)) throw new Error("invalid role size, encoding or file id");
@@ -48,6 +58,22 @@ export function parseRole(text: string, stem: string, layer: CatalogRole["layer"
48
58
  const review = body.slice(reviewStart, sections[5]!.index).trim();
49
59
  return { id: stem, name: header.name!, group: header.group!, summary: header.summary!, source: header.source!, base: list("base", BASES), classes: list("classes", CLASSES), body, review, layer, hash: createHash("sha256").update(text).digest("hex") };
50
60
  }
61
+ /** Validate with the existing parser, then retain exact source slices without trim or normalization. */
62
+ export function parseRoleDocument(text: string, stem: string, layer: CatalogRole["layer"]): RoleDocument {
63
+ const role = parseRole(text, stem, layer);
64
+ const rawHeader = /^---\n[\s\S]*?\n---\n/.exec(text)![0];
65
+ const body = text.slice(rawHeader.length), headings = [...body.matchAll(/^## (.+)$/gm)];
66
+ const sections = headings.map((heading, index): RoleSectionSpan => {
67
+ const startUtf16 = rawHeader.length + heading.index!;
68
+ const endUtf16 = rawHeader.length + (headings[index + 1]?.index ?? body.length);
69
+ let contentStartUtf16 = startUtf16 + heading[0].length;
70
+ if (text[contentStartUtf16] === "\n") contentStartUtf16++;
71
+ return Object.freeze({ name: ROLE_SECTIONS[index]!, startUtf16, endUtf16, contentStartUtf16,
72
+ headingRaw: text.slice(startUtf16, contentStartUtf16), contentRaw: text.slice(contentStartUtf16, endUtf16), raw: text.slice(startUtf16, endUtf16) });
73
+ });
74
+ Object.freeze(role.base); Object.freeze(role.classes); Object.freeze(role);
75
+ return Object.freeze({ role, rawHeader, bodyPrefix: body.slice(0, headings[0]!.index), sections: Object.freeze(sections) });
76
+ }
51
77
  function projectRole(file: string): string {
52
78
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
53
79
  try {
@@ -11,7 +11,7 @@ export interface PeerCapabilities { tests: boolean; spec: boolean; testsReason?:
11
11
  import type { PeerId, PeerState } from "./envelope.ts";
12
12
 
13
13
  import { parseHubRoutes, type HubRoute } from "../models/route/config.ts";
14
- import { DEFAULT_STAY_SWITCH, type StaySwitchMode } from "../models/route/stage.ts";
14
+ import { DEFAULT_STAY_SWITCH, type StaySwitchMode } from "../models/route/stage-fallback.ts";
15
15
 
16
16
  export interface ClassPolicy {
17
17
  /** preference order among attached, unpaused peers */
@@ -426,6 +426,8 @@ export function assign(
426
426
  states: Record<PeerId, PeerState>,
427
427
  routing: Routing,
428
428
  opts: InstanceRoutingOptions & {
429
+ /** Precomputed snapshot guidance only; it never changes peer eligibility or performs a read. */
430
+ entryDiagnostic?: string;
429
431
  capabilities?: Record<PeerId, PeerCapabilities>;
430
432
  repository?: string;
431
433
  exclude?: PeerId[];
@@ -469,6 +471,7 @@ export function assign(
469
471
  const instanceMode = hasInstances(opts);
470
472
  const policy = routing.classes[task.class];
471
473
  const trace: string[] = [`class ${task.class}${policy ? "" : " (no [classes] entry: only an explicit owner can take it)"}`, `signals: ${task.signals.join(", ") || "none"}`];
474
+ if (opts.entryDiagnostic) trace.push(`build entry: ${opts.entryDiagnostic}`);
472
475
  // Which file each of this class's values comes from (#269), only when the machine-local overlay sets one.
473
476
  const local = Object.keys(routing.sources ?? {}).filter((key) => key.startsWith(`classes.${task.class}.`)).map((key) => key.slice(`classes.${task.class}.`.length));
474
477
  if (local.length) trace.push(`policy source: ${local.join(", ")} from ${OVERLAY_FILE}; the rest from routing.toml`);
@@ -2,7 +2,7 @@ import { findingsForHead, findingHead, findingTally } from "./review-findings.ts
2
2
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
3
3
  import { evalGapBlockers, evalGateView, evalReportedGap, evalRequiredChecks, readEvalFor, type EvalResult } from "./eval-gate.ts";
4
4
  import { mergeCostFrom } from "./cost-governance.ts";
5
- import { readPrCostHistory, readSdlcPr, stageDefinition, type AutoMergeMode, type PrEvidence, type SdlcConfig, type SdlcGh, type MergeRecord } from "./sdlc.ts";
5
+ import { parsePrEvidence, readPrCostHistory, readSdlcPr, stageDefinition, type AutoMergeMode, type PrEvidence, type SdlcConfig, type SdlcGh, type MergeRecord, type SdlcReceipt } from "./sdlc.ts";
6
6
 
7
7
  /**
8
8
  * #786 T1/T2: the one guarded merge. Given a task and the head its reviewer approved, it re-reads the PR (`readSdlcPr`) and the merge queue
@@ -91,6 +91,44 @@ function checkGates(evidence: PrEvidence, required: readonly string[], extra: re
91
91
  return gates;
92
92
  }
93
93
 
94
+ /** 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> {
96
+ if (!REPO.test(receipt.repo ?? "") || receipt.repo!.startsWith("-") || !Number.isSafeInteger(receipt.pr) || receipt.pr! <= 0) return undefined;
97
+ 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} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
99
+ try {
100
+ const result = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${receipt.pr}`]);
101
+ if (result.code !== 0) return undefined;
102
+ const response = JSON.parse(result.stdout), pr = response?.data?.repository?.pullRequest;
103
+ const commit = pr?.commits?.nodes?.length === 1 ? pr.commits.nodes[0]?.commit : undefined, checks = commit?.statusCheckRollup?.contexts;
104
+ if (response.errors !== undefined || !pr || commit?.oid !== pr.headRefOid || checks?.pageInfo?.hasNextPage !== false || !Array.isArray(checks.nodes)) return undefined;
105
+ const threads = pr.reviewThreads, requests = pr.reviewRequests;
106
+ const threadComplete = threads?.pageInfo?.hasNextPage === false && Array.isArray(threads.nodes) && threads.nodes.every((node: { isResolved?: unknown } | null) => typeof node?.isResolved === "boolean");
107
+ const requestComplete = requests?.pageInfo?.hasNextPage === false && Array.isArray(requests.nodes) && requests.nodes.every((node: { requestedReviewer?: { __typename?: unknown } } | null) => typeof node?.requestedReviewer?.__typename === "string");
108
+ const evidence = parsePrEvidence({ ...pr, statusCheckRollup: checks.nodes, files: [], ...(threadComplete ? { unresolvedThreads: threads.nodes.filter((node: { isResolved: boolean }) => !node.isResolved).length } : {}), reviewRequests: requestComplete ? requests.nodes : undefined });
109
+ evidence.checks = evidence.checks.map((check, index): PrEvidence["checks"][number] => {
110
+ const raw = checks.nodes[index];
111
+ const green = raw.name ? (raw.status === "COMPLETED" && raw.conclusion === "SUCCESS") : raw.state === "SUCCESS";
112
+ return check.state === "passed" && !green ? { ...check, state: "unknown" } : check;
113
+ });
114
+ // Files are outside adoption's decision. Keep their coverage explicitly unknown in the shared evidence shape.
115
+ return { ...evidence, pathsComplete: false, typesComplete: false };
116
+ } catch { return undefined; }
117
+ }
118
+
119
+ /** #1328 T3: adoption observes a completed merge; it never dispatches a merge or invents a reviewer verdict. */
120
+ export function adoptMergeGates(evidence: PrEvidence | undefined, head: string, required: readonly string[]): string[] {
121
+ if (!evidence) return ["PR evidence unavailable; restore GitHub access and retry ahub sdlc adopt-merge"];
122
+ const gates: string[] = [];
123
+ if (evidence.state !== "MERGED") gates.push("PR is not merged; complete the normal review and guarded merge before adopting it");
124
+ if (evidence.head !== head) gates.push("PR head differs from the task's last recorded full head; record the correct task head before retrying ahub sdlc adopt-merge");
125
+ if (evidence.unresolved === null || evidence.unresolved > 0) gates.push("PR review threads are unresolved or unknown; resolve the threads and restore complete GitHub readback before retrying ahub sdlc adopt-merge");
126
+ if (evidence.pendingReviews === null || evidence.pendingReviews > 0) gates.push("PR review requests are pending or unknown; settle the requests and restore complete GitHub readback before retrying ahub sdlc adopt-merge");
127
+ if (evidence.review === "changes_requested") gates.push("PR has a pending change request; settle the review before retrying ahub sdlc adopt-merge");
128
+ gates.push(...checkGates(evidence, required).map(gate => `${gate}; configure required_checks in .agenthub/sdlc.toml and get every required check green at the recorded head before retrying ahub sdlc adopt-merge`));
129
+ return gates;
130
+ }
131
+
94
132
  function queueGates(queue: MergeQueue | undefined, pr: number): string[] {
95
133
  const row = queue?.rows.find(r => r.pr === pr);
96
134
  if (!queue || !row) return ["merge queue unavailable: this PR is not in the open snapshot"];
@@ -254,7 +254,7 @@ export function releaseMetrics(releases: Release[], tasks: Task[]) {
254
254
  const scope = train.scope ?? [...train.history].reverse().find(row => row.event === "cut")?.scope;
255
255
  if (!scope) { unknown.add(release.id); continue; }
256
256
  for (const id of scope) {
257
- const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
257
+ const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "merged outside the hub" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
258
258
  const ms = approved !== null && approved <= event.at ? event.at - approved : null;
259
259
  if (ms === null) unknown.add(release.id);
260
260
  approvalToReleaseMs.push({ release: release.id, task: id, ms });
package/src/hub/sdlc.ts CHANGED
@@ -350,6 +350,30 @@ export function parsePrEvidence(value: unknown): PrEvidence {
350
350
  /** Issue identity and edit times only; no body is fetched or stored. `lastEditedAt` moves on a body edit, not on comments. */
351
351
  export interface SpecEdit { lastEditedAt: string | null; updatedAt: string }
352
352
  export interface SpecAcceptance extends SpecEdit { repo: string; issue: number; acceptedAt: number }
353
+ /** Consent references are complete local task tokens, never numbers extracted from prose. */
354
+ export function localSupersedingTask(value: unknown): number | undefined {
355
+ if (typeof value !== "string") return undefined;
356
+ const match = /^(?:task #|#)?([1-9][0-9]*)$/.exec(value);
357
+ const task = match?.[0] === value ? Number(match[1]) : NaN;
358
+ return Number.isSafeInteger(task) ? task : undefined;
359
+ }
360
+
361
+ /** Validate host-stored consent without importing any other source receipt fields. */
362
+ export function storedSpecAcceptance(value: unknown): SpecAcceptance | undefined {
363
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
364
+ const record = value as Record<string, unknown>;
365
+ const stamp = (v: unknown): v is string => typeof v === "string" && v.length <= 40 && !Number.isNaN(Date.parse(v));
366
+ if (!repo(record.repo) || !id(record.issue) || !stamp(record.updatedAt) || record.lastEditedAt !== null && !stamp(record.lastEditedAt)
367
+ || typeof record.acceptedAt !== "number" || !Number.isFinite(record.acceptedAt)) return undefined;
368
+ return { repo: record.repo, issue: record.issue, updatedAt: record.updatedAt, lastEditedAt: record.lastEditedAt as string | null, acceptedAt: record.acceptedAt };
369
+ }
370
+
371
+ /** Only a host observation of the same issue/body permits copying existing person consent. */
372
+ export function carriedSpecAcceptance(source: SpecAcceptance, destination: { repo: string; issue: number }, edit: SpecEdit | undefined): SpecAcceptance | undefined {
373
+ if (!edit || source.repo.toLowerCase() !== destination.repo.toLowerCase() || source.issue !== destination.issue || source.lastEditedAt !== edit.lastEditedAt) return undefined;
374
+ return { repo: destination.repo, issue: destination.issue, lastEditedAt: source.lastEditedAt, updatedAt: source.updatedAt, acceptedAt: source.acceptedAt };
375
+ }
376
+
353
377
  export type SpecState = "missing" | "current" | "changed" | "unknown";
354
378
  /** Whether the receipt's spec issue is accepted at its current body. `edit` undefined means the readback failed. */
355
379
  export function specState(receipt: SdlcReceipt | undefined, edit: SpecEdit | undefined): SpecState {
@@ -546,16 +570,34 @@ export async function readPlanIssueMetadata(repository: string, number: number,
546
570
  } catch { return undefined; }
547
571
  }
548
572
 
573
+ /** The native CI floor belongs only to this repository; other projects must name their own checks. */
574
+ export function requiredCheckNames(repository: string | undefined, required: readonly string[]): string[] {
575
+ return required.length ? [...new Set(required)] : repository?.toLowerCase() === "staixbwlb/agent-hub" ? ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"] : [];
576
+ }
577
+
578
+ /** Names each non-green required check. Incomplete inventories cannot prove either presence or success. */
579
+ export function requiredCiBlocker(required: readonly string[], checks: PrEvidence["checks"], complete = true): string | undefined {
580
+ const problems = required.flatMap(name => {
581
+ const matches = checks.filter(check => check.name === name);
582
+ const state = !complete ? "unknown" : !matches.length ? "missing" : matches.some(check => check.state === "failed") ? "failed"
583
+ : matches.some(check => check.state === "pending") ? "pending" : matches.length !== 1 ? "duplicate" : matches[0]!.state !== "passed" ? "unknown" : undefined;
584
+ return state ? [`${state} ${name}`] : [];
585
+ });
586
+ return problems.length ? `exact-head full CI is not green: ${problems.join("; ")}` : undefined;
587
+ }
588
+
549
589
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
550
- export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[]): ReviewReadiness | undefined {
590
+ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
551
591
  if (!evidence || evidence.unresolved !== 0) return undefined;
552
- const checks = required.length ? [...required] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
592
+ const checks = requiredCheckNames(repository, required);
593
+ if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
553
594
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
554
595
  const blockers: string[] = [];
555
596
  if (!expected || !sha(expected)) blockers.push("review head missing");
556
597
  else if (evidence.head !== expected) blockers.push("review head changed");
557
598
  if (evidence.state !== "OPEN") blockers.push("review PR is not open");
558
- if (!checks.every(name => { const matched = evidence.checks.filter(check => check.name === name); return matched.length === 1 && matched[0]?.state === "passed"; })) blockers.push("exact-head full CI is not green");
599
+ const ciBlocker = requiredCiBlocker(checks, evidence.checks);
600
+ if (ciBlocker) blockers.push(ciBlocker);
559
601
  return { head: evidence.head, ready: blockers.length === 0, blockers, checks };
560
602
  }
561
603
 
@@ -565,6 +607,8 @@ export interface ReviewReadiness { head?: string; ready: boolean; blockers: stri
565
607
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
566
608
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
567
609
  if (!repo(receipt.repo) || !id(receipt.pr)) return unknown();
610
+ const full = requiredCheckNames(receipt.repo, requiredChecks);
611
+ if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
568
612
  const [owner, name] = receipt.repo.split("/");
569
613
  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} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
570
614
  try {
@@ -585,14 +629,21 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
585
629
  if (!commit || commit.oid !== pr.headRefOid) blockers.push("review head changed");
586
630
  const contexts = commit?.statusCheckRollup?.contexts;
587
631
  const nodes: unknown[] | undefined = contexts?.nodes;
588
- const full = requiredChecks.length ? [...requiredChecks] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
589
632
  let reusedRun: number | undefined;
590
- if (contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100
591
- || !full.every(name => {
592
- const matches = (nodes as { name?: string; context?: string; status?: string; conclusion?: string; state?: string }[]).filter(node => (node?.name ?? node?.context) === name);
593
- return matches.length === 1 && (matches[0]?.name ? matches[0].status === "COMPLETED" && matches[0].conclusion === "SUCCESS" : matches[0]?.state === "SUCCESS");
594
- })) blockers.push("exact-head full CI is not green");
595
- if (blockers.includes("exact-head full CI is not green") && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
633
+ const completeChecks = !(contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100);
634
+ const requiredNodes = completeChecks ? nodes!.filter(node => {
635
+ const raw = node as { name?: unknown; context?: unknown } | null | undefined;
636
+ return full.some(name => (raw?.name ?? raw?.context) === name);
637
+ }) : [];
638
+ const checkEvidence = completeChecks ? parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: requiredNodes }).checks.map((check, index) => {
639
+ const raw = requiredNodes[index] as { name?: unknown; status?: unknown; conclusion?: unknown; state?: unknown } | undefined;
640
+ // Fresh GraphQL admission keeps its original success proof, even when common normalization accepts a legacy shape.
641
+ const success = raw?.name ? raw.status === "COMPLETED" && raw.conclusion === "SUCCESS" : raw?.state === "SUCCESS";
642
+ return check.state === "passed" && !success ? { ...check, state: "unknown" as const } : check;
643
+ }) : [];
644
+ const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
645
+ if (ciBlocker) blockers.push(ciBlocker);
646
+ if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
596
647
  && 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)) {
597
648
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
598
649
  if (reusedRun !== undefined) {
@@ -600,7 +651,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
600
651
  const after = await bounded(args, 10_000, undefined, 512 * 1024);
601
652
  try { if (after.code !== 0 || JSON.stringify(JSON.parse(after.stdout)?.data?.repository?.pullRequest) !== JSON.stringify(pr)) reusedRun = undefined; }
602
653
  catch { reusedRun = undefined; }
603
- if (reusedRun !== undefined) blockers.splice(blockers.indexOf("exact-head full CI is not green"), 1);
654
+ if (reusedRun !== undefined) blockers.splice(blockers.indexOf(ciBlocker!), 1);
604
655
  }
605
656
  }
606
657
  const threads = pr.reviewThreads;