@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
@@ -0,0 +1,272 @@
1
+ import { createHash } from "node:crypto";
2
+ import { types } from "node:util";
3
+ import type { Board, Task } from "./board.ts";
4
+ import type { JournalDelivery } from "./delivery-journal.ts";
5
+ import { latestDeliverables } from "./deliverables.ts";
6
+ import { isReviewObserverExcluded } from "./memory-policy.ts";
7
+ import { remoteEnvelope } from "./envelope.ts";
8
+ import { EXECUTION_LINK_LIMITS, taskExecutionReference, type ExecutionLinkRecord } from "./execution-links.ts";
9
+ import { executionReferenceKey, parseExecutionReference, type ExecutionReferenceV1 } from "./execution-reference.ts";
10
+ import { LINEAGE_LIMITS, readExecutionLineage, type ExecutionLineageSource, type LineageEdge, type LineageNode, type LineageQuery, type LineageResult } from "./execution-lineage.ts";
11
+
12
+ export interface OwnerLineageQuery {
13
+ taskId?: number; attemptId?: string; root?: ExecutionReferenceV1; task?: { id: number; created: number };
14
+ cursor?: string; nodes?: number; edges?: number; bytes?: number;
15
+ }
16
+ export interface ExecutionLineageOwnerPorts {
17
+ project: string; projectKey: string; cursorKey: string; scope: string; diagnostics: boolean;
18
+ /** Host capability only: raw event paging cannot prove a complete public projection under dynamic field policy. */
19
+ eventProjectionSupported: boolean;
20
+ task(id: number): Task | undefined;
21
+ visible(task: Task): boolean;
22
+ metadata(text: string): boolean;
23
+ links(task: Task): readonly ExecutionLinkRecord[];
24
+ delivery?(id: string): JournalDelivery | undefined;
25
+ attempt: Board["experimentAttempt"];
26
+ events: Board["experimentEvents"];
27
+ receipts: Board["runnerReceipts"];
28
+ attemptStatus: Board["experimentAttemptStatus"];
29
+ }
30
+ const unavailableRoot = (projectKey: string): ExecutionReferenceV1 => ({ v: 1, tool: "ahub", projectKey, kind: "task", id: "unavailable" });
31
+ const integer = (value: unknown, min: number): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
32
+ /** Closed selectors never treat an opaque id as a path, URL or project resolver. */
33
+ export function parseOwnerLineageQuery(input: unknown): OwnerLineageQuery {
34
+ const object = (value: unknown, keys: string[]): Record<string, unknown> => {
35
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) throw new Error("invalid lineage query");
36
+ const fields = Object.getOwnPropertyDescriptors(value);
37
+ if (Object.entries(fields).some(([key, field]) => !keys.includes(key) || !("value" in field))) throw new Error("invalid lineage query");
38
+ return Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
39
+ };
40
+ const raw = object(input, ["taskId", "attemptId", "root", "task", "cursor", "nodes", "edges", "bytes"]);
41
+ if ([raw.taskId, raw.attemptId, raw.root].filter(value => value !== undefined).length !== 1) throw new Error("choose one lineage root");
42
+ if (raw.taskId !== undefined && !integer(raw.taskId, 1) || raw.attemptId !== undefined && (typeof raw.attemptId !== "string" || !/^ra-[a-f0-9]{12}$/.test(raw.attemptId))) throw new Error("invalid lineage root");
43
+ const root = raw.root === undefined ? undefined : parseExecutionReference(raw.root);
44
+ if (root?.tool === "ahub" && (root.kind === "task" && !/^[1-9][0-9]*:[0-9]+$/.test(root.id) || root.kind === "attempt" && !/^ra-[a-f0-9]{12}$/.test(root.id))) throw new Error("invalid lineage root");
45
+ for (const [key, maximum, minimum] of [["nodes", LINEAGE_LIMITS.nodes, 1], ["edges", LINEAGE_LIMITS.edges, 1], ["bytes", LINEAGE_LIMITS.bytes, LINEAGE_LIMITS.minimumBytes]] as const) {
46
+ const value = raw[key];
47
+ if (value !== undefined && (!integer(value, minimum) || value > maximum)) throw new Error("invalid lineage bound");
48
+ }
49
+ let task: OwnerLineageQuery["task"];
50
+ if (raw.task !== undefined) {
51
+ const scope = object(raw.task, ["id", "created"]);
52
+ if (!root || !integer(scope.id, 1) || !integer(scope.created, 0)) throw new Error("invalid lineage task scope");
53
+ task = { id: scope.id, created: scope.created };
54
+ }
55
+ return { ...raw, ...(root ? { root } : {}), ...(task ? { task } : {}) } as OwnerLineageQuery;
56
+ }
57
+
58
+ /** One existing task row and explicit owner lookups only; no Board scan, reverse index or backfill. */
59
+ export function executionOwnerSnapshot(ports: ExecutionLineageOwnerPorts, input: OwnerLineageQuery): { source: ExecutionLineageSource; query: LineageQuery; task?: Task } {
60
+ const source: ExecutionLineageSource = { id: "ahub-owner", revision: "unavailable", projectKey: ports.projectKey, scope: ports.scope, cursorKey: ports.cursorKey,
61
+ authorized: true, diagnostics: ports.diagnostics, health: "missing", nodes: [], edges: [] };
62
+ let root = input.root ?? unavailableRoot(ports.projectKey);
63
+ const query = () => ({ root, ...(input.cursor === undefined ? {} : { cursor: input.cursor }), ...(input.nodes === undefined ? {} : { nodes: input.nodes }), ...(input.edges === undefined ? {} : { edges: input.edges }), ...(input.bytes === undefined ? {} : { bytes: input.bytes }) });
64
+ const fail = (health: ExecutionLineageSource["health"]) => { source.health = health; return { source, query: query() }; };
65
+ try {
66
+ let taskId = input.taskId ?? input.task?.id, attemptRoot = input.attemptId;
67
+ if (input.root) {
68
+ if (root.tool !== "ahub" || root.projectKey !== ports.projectKey) return fail("unsupported");
69
+ if (root.kind === "task") {
70
+ const identity = /^([1-9][0-9]*):([0-9]+)$/.exec(root.id);
71
+ if (!identity || !integer(Number(identity[1]), 1) || !integer(Number(identity[2]), 0)) return fail("unsupported");
72
+ if (taskId !== undefined && taskId !== Number(identity[1])) return fail("missing");
73
+ taskId = Number(identity[1]);
74
+ } else if (root.kind === "attempt") attemptRoot = root.id;
75
+ else if (!input.task) return fail("unsupported");
76
+ }
77
+ if (attemptRoot !== undefined && !/^ra-[a-f0-9]{12}$/.test(attemptRoot)) return fail("unsupported");
78
+ const firstAttempt = attemptRoot ? ports.attempt(attemptRoot) : undefined;
79
+ if (attemptRoot && (!firstAttempt || firstAttempt.project !== ports.project)) return fail("missing");
80
+ if (firstAttempt) {
81
+ if (taskId !== undefined && taskId !== firstAttempt.attempt.taskId) return fail("missing");
82
+ taskId = firstAttempt.attempt.taskId;
83
+ }
84
+ if (taskId === undefined) return fail("unsupported");
85
+ const task = ports.task(taskId);
86
+ if (!task) return fail("missing");
87
+ if (!ports.visible(task)) return fail("withheld");
88
+ if (input.task && input.task.created !== task.created) return fail("missing");
89
+ if ((attemptRoot !== undefined || root.kind === "output") && !ports.eventProjectionSupported) return fail("unsupported");
90
+ if (firstAttempt?.private) return fail("withheld");
91
+ const taskRef = taskExecutionReference(ports.projectKey, task.id, task.created);
92
+ if (input.taskId !== undefined) root = taskRef;
93
+ if (input.attemptId !== undefined) root = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "attempt", id: input.attemptId };
94
+ if (root.kind === "task" && executionReferenceKey(root) !== executionReferenceKey(taskRef)) return fail("missing");
95
+ const nodes = new Map<string, LineageNode>(), edges: LineageEdge[] = [], external = new Map<string, ExecutionReferenceV1>();
96
+ const rootKey = executionReferenceKey(root);
97
+ let rootWithheld = false;
98
+ const withheld = (ref: ExecutionReferenceV1) => { if (executionReferenceKey(ref) === rootKey) rootWithheld = true; };
99
+ let projectedBytes = 0;
100
+ const account = (value: unknown) => {
101
+ projectedBytes += Buffer.byteLength(JSON.stringify(value), "utf8");
102
+ if (projectedBytes > LINEAGE_LIMITS.sourceBytes) { source.health = "unsupported"; throw new Error("lineage source bound"); }
103
+ };
104
+ const add = (ref: ExecutionReferenceV1, state: string, strength: LineageNode["strength"]): boolean => {
105
+ if (!ports.metadata(JSON.stringify(ref))) { withheld(ref); return false; }
106
+ const key = executionReferenceKey(ref);
107
+ if (!nodes.has(key)) { const node = { ref, state, strength }; account(node); nodes.set(key, node); }
108
+ if (nodes.size > LINEAGE_LIMITS.sourceNodes) { source.health = "unsupported"; throw new Error("lineage source bound"); }
109
+ return true;
110
+ };
111
+ const edge = (from: ExecutionReferenceV1, to: ExecutionReferenceV1, relation: LineageEdge["relation"], strength: LineageEdge["strength"]) => {
112
+ if (!nodes.has(executionReferenceKey(from)) || !nodes.has(executionReferenceKey(to))) return;
113
+ const value = { from, to, relation, strength }; account(value); edges.push(value);
114
+ if (edges.length > LINEAGE_LIMITS.sourceEdges) { source.health = "unsupported"; throw new Error("lineage source bound"); }
115
+ };
116
+ if (!add(taskRef, task.state, "host-observed")) return fail("withheld");
117
+ const deliverableRef = (record: NonNullable<Task["history"][number]["deliverables"]>[number]): ExecutionReferenceV1 => ({ v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "deliverable", id: record.id, sha256: record.sha256 });
118
+ const publicOutput = (record: NonNullable<Task["history"][number]["deliverables"]>[number]) => {
119
+ const visible = !record.private && (!record.path || ports.metadata(record.path));
120
+ if (!visible) withheld(deliverableRef(record));
121
+ return visible;
122
+ };
123
+ const current = new Map<string, string>();
124
+ let publicSubmission = false;
125
+ for (const entry of task.history) {
126
+ if (entry.withheld) { for (const output of entry.deliverables ?? []) withheld(deliverableRef(output)); continue; }
127
+ const outputs = (entry.deliverables ?? []).filter(publicOutput);
128
+ // Review copies bind a verdict, not a new submission. Wholly hidden updates do not replace
129
+ // the current public submission or reveal their presence through review currency.
130
+ if (entry.event === "approved" || entry.event === "changes_requested" || !outputs.length) continue;
131
+ const submitted = latestDeliverables([{ event: entry.event, deliverables: outputs }]);
132
+ if (!submitted) continue;
133
+ current.clear(); publicSubmission = true;
134
+ for (const output of submitted) {
135
+ account([output.id, output.sha256]); current.set(output.id, output.sha256);
136
+ if (current.size > LINEAGE_LIMITS.sourceNodes) { source.health = "unsupported"; throw new Error("lineage source bound"); }
137
+ }
138
+ }
139
+ const currentHead = task.refs.commit ?? task.sdlc?.head;
140
+ const head = currentHead && ports.metadata(JSON.stringify({ v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "head", id: currentHead })) ? currentHead : undefined;
141
+ for (const [index, entry] of task.history.entries()) {
142
+ if (entry.withheld) continue;
143
+ const reviewed = entry.event === "approved" || entry.event === "changes_requested", reviewedHead = entry.reviewedHead ?? entry.reviewFindings?.head;
144
+ const outputs = (entry.deliverables ?? []).filter(publicOutput);
145
+ if (reviewed && entry.deliverables?.length && !outputs.length) continue;
146
+ const sameSubmission = outputs.length === current.size && outputs.every(record => current.get(record.id) === record.sha256);
147
+ const currency = !reviewedHead || !head ? `${entry.event}_unknown`
148
+ : reviewedHead !== head || publicSubmission && !sameSubmission ? `${entry.event}_stale`
149
+ : outputs.length && !publicSubmission ? `${entry.event}_unknown` : entry.event;
150
+ const review: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "review", id: `${task.id}:${task.created}:${index}`, ...(reviewedHead ? { revision: reviewedHead } : {}) };
151
+ if (reviewed && (outputs.length || reviewedHead)) {
152
+ add(review, currency, "host-observed");
153
+ if (reviewedHead) {
154
+ const submitted: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "head", id: reviewedHead };
155
+ if (add(submitted, "submitted", "declared")) {
156
+ edge(taskRef, submitted, "produced", "declared");
157
+ edge(submitted, review, "reviewed", "declared");
158
+ }
159
+ }
160
+ }
161
+ for (const output of outputs) {
162
+ const ref: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "deliverable", id: output.id, sha256: output.sha256 };
163
+ if (add(ref, !publicSubmission ? "historical" : current.get(output.id) === output.sha256 ? "recorded" : "stale", "host-observed")) {
164
+ edge(taskRef, ref, "produced", "host-observed");
165
+ if (reviewed) edge(ref, review, "reviewed", "host-observed");
166
+ }
167
+ }
168
+ }
169
+ const links = ports.links(task);
170
+ if (links.length >= EXECUTION_LINK_LIMITS.read) return fail("unsupported");
171
+ const local = (ref: ExecutionReferenceV1, saved = false): boolean => {
172
+ if (ref.tool !== "ahub" || ref.projectKey !== ports.projectKey) return false;
173
+ if (nodes.has(executionReferenceKey(ref))) return true;
174
+ if (ref.kind === "output") {
175
+ if (!ports.eventProjectionSupported) { source.health = "unsupported"; return false; }
176
+ const address = /^(ra-[a-f0-9]{12}):([1-9][0-9]*)$/.exec(ref.id);
177
+ if (!address || ref.revision !== undefined) return false;
178
+ const owner: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "attempt", id: address[1]! };
179
+ return local(owner, saved) && nodes.has(executionReferenceKey(ref));
180
+ }
181
+ if (ref.kind === "dispatch") {
182
+ if (ref.revision !== undefined || ref.sha256 !== undefined) return false;
183
+ const delivery = ports.delivery?.(ref.id);
184
+ if (!delivery) return false;
185
+ const matches = delivery.originals.some(env => env.refs?.task === String(task.id) && (saved || env.id === task.offer?.envelopeId));
186
+ if (!matches) return false;
187
+ if (delivery.originals.some(env => env.private || remoteEnvelope(env) || isReviewObserverExcluded(env))) { withheld(ref); return false; }
188
+ return add(ref, delivery.state, "host-observed") && (edge(taskRef, ref, "dispatched", "host-observed"), true);
189
+ }
190
+ if (ref.kind !== "attempt" || !/^ra-[a-f0-9]{12}$/.test(ref.id) || ref.revision !== undefined || ref.sha256 !== undefined) return false;
191
+ if (!ports.eventProjectionSupported) { source.health = "unsupported"; return false; }
192
+ const attempt = ports.attempt(ref.id);
193
+ if (!attempt || attempt.project !== ports.project || attempt.attempt.taskId !== task.id) return false;
194
+ if (attempt.private) {
195
+ withheld(ref);
196
+ const address = root.kind === "output" && root.revision === undefined ? /^(ra-[a-f0-9]{12}):([1-9][0-9]*)$/.exec(root.id) : null;
197
+ const seq = Number(address?.[2]);
198
+ if (ports.diagnostics && address?.[1] === ref.id && Number.isSafeInteger(seq)) {
199
+ // The task is authorized. Inspect only this indexed event's reference fields for the
200
+ // diagnostic boolean; private event text, identifiers and counts never enter a page.
201
+ const row = ports.events(ref.id, seq - 1, 1).rows.find(item => item.event.seq === seq);
202
+ if (row?.event.kind === "output") {
203
+ const body = row.event.body;
204
+ const sha256 = "id" in body ? body.sha256 : row.observations.find(item => item.eventSeq === seq && item.observation.source === "deliverable")?.observation.values.sha256;
205
+ if (sha256 === undefined || typeof sha256 === "string") withheld({ v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "output", id: `${ref.id}:${seq}`, ...(sha256 ? { sha256 } : {}) });
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+ if (!add(ref, ports.attemptStatus(ref.id), "declared")) return false;
211
+ edge(taskRef, ref, "attempted", "host-observed");
212
+ const protocol: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "protocol", id: attempt.attempt.protocolHash };
213
+ if (add(protocol, "recorded", "declared")) edge(protocol, ref, "attempted", "declared");
214
+ const events = ports.events(ref.id, 0, 50);
215
+ if (!events.done) { source.health = "unsupported"; return false; }
216
+ const receipts = ports.receipts(ref.id).filter(row => !row.private && row.receipt.projectId === ports.project && row.receipt.attemptId === ref.id && row.receipt.protocolHash === attempt.attempt.protocolHash);
217
+ for (const receipt of receipts) {
218
+ const address: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "runner-receipt", id: receipt.receipt.receiptId, sha256: receipt.bodyHash };
219
+ if (add(address, "recorded", "runner-attested")) edge(ref, address, "produced", "runner-attested");
220
+ }
221
+ for (const row of events.rows) {
222
+ if (row.event.kind !== "output") continue;
223
+ const body = row.event.body;
224
+ const observation = row.observations.find(item => item.eventSeq === row.event.seq && item.observation.source === "deliverable" && typeof item.observation.values.deliverableId === "string" && typeof item.observation.values.sha256 === "string");
225
+ const id = "id" in body ? body.id : observation?.observation.values.deliverableId;
226
+ const sha256 = "id" in body ? body.sha256 : observation?.observation.values.sha256;
227
+ if (typeof id !== "string" || sha256 !== undefined && typeof sha256 !== "string") continue;
228
+ const output: ExecutionReferenceV1 = { v: 1, tool: "ahub", projectKey: ports.projectKey, kind: "output", id: `${ref.id}:${row.event.seq}`, ...(sha256 ? { sha256 } : {}) };
229
+ if (row.private || !ports.metadata(JSON.stringify(body))) { withheld(output); continue; }
230
+ const measured = typeof sha256 === "string" && observation?.observation.values.deliverableId === id && observation.observation.values.sha256 === sha256;
231
+ const signed = receipts.some(receipt => receipt.receipt.outputs?.some(item => item.name === id && item.sha256 === sha256));
232
+ const strength = signed ? "runner-attested" : measured ? "host-observed" : "declared";
233
+ if (add(output, "recorded", strength)) edge(ref, output, "produced", strength);
234
+ }
235
+ return true;
236
+ };
237
+ // ponytail: task offers name envelope ids, not journal delivery ids; there is no indexed reverse lookup.
238
+ // Only an explicit scoped dispatch or saved declaration can name a journal row; never scan the journal.
239
+ if (root.kind === "attempt" || root.kind === "dispatch" || root.kind === "output") local(root);
240
+ const admitted = links.filter(link => link.projectKey === ports.projectKey && link.taskId === task.id && link.taskCreated === task.created && ports.metadata(JSON.stringify([link.from, link.reference])));
241
+ // Expand the bounded declared neighborhoods before emitting edges. A protocol/receipt origin
242
+ // can depend on a later attempt declaration; each productive pass adds nodes, never scans owners.
243
+ let beforeExpansion: number;
244
+ do {
245
+ beforeExpansion = nodes.size;
246
+ for (const link of admitted) if (local(link.from, true) && link.reference.tool === "ahub") local(link.reference, true);
247
+ } while (nodes.size > beforeExpansion);
248
+ for (const link of admitted) {
249
+ if (!local(link.from, true)) continue;
250
+ const target = link.reference;
251
+ if (target.tool === "ahub") { if (!local(target, true)) continue; }
252
+ else {
253
+ if (!add(target, "declared", "declared")) continue;
254
+ const key = executionReferenceKey(target);
255
+ if (!external.has(key)) { account(target); external.set(key, target); }
256
+ }
257
+ edge(link.from, target, "declared-external", "declared");
258
+ }
259
+ if (source.health === "unsupported") return fail("unsupported");
260
+ if (!nodes.has(rootKey)) return fail(rootWithheld ? "withheld" : "missing");
261
+ source.nodes = [...nodes.values()]; source.edges = [...new Map(edges.map(edge => [JSON.stringify(edge), edge])).values()]; source.admittedExternalTargets = [...external.values()];
262
+ // The core also binds the visible graph. Hidden history and unprojected task fields are
263
+ // never a source revision: otherwise a private append would invalidate a public cursor.
264
+ source.revision = createHash("sha256").update(JSON.stringify([source.nodes, source.edges, source.admittedExternalTargets])).digest("hex");
265
+ source.health = "ready";
266
+ return { source, query: query(), task };
267
+ } catch { return fail(source.health === "unsupported" ? "unsupported" : "corrupt"); }
268
+ }
269
+ export function readOwnerExecutionLineage(ports: ExecutionLineageOwnerPorts, input: OwnerLineageQuery): LineageResult {
270
+ const { source, query } = executionOwnerSnapshot(ports, input);
271
+ return readExecutionLineage(source, query);
272
+ }
@@ -0,0 +1,164 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { EXECUTION_REFERENCE_LIMITS, executionReferenceKey, executionText, parseExecutionReference, type ExecutionReferenceV1 } from "./execution-reference.ts";
3
+
4
+ /** Snapshot admission is host-owned; never accept these authority flags from a caller or producer. */
5
+ export const LINEAGE_LIMITS = Object.freeze({ nodes: 100, edges: 200, bytes: 256 * 1024, sourceNodes: 2048, sourceEdges: 4096, sourceBytes: 4 * 1024 * 1024, token: 128, state: 64, cursor: 512, minimumBytes: 4096 });
6
+ export type LineageStrength = "declared" | "host-observed" | "runner-attested" | "unknown";
7
+ export type LineageRelation = "dispatched" | "attempted" | "produced" | "reviewed" | "declared-external";
8
+ export interface LineageNode { ref: ExecutionReferenceV1; state: string; strength: LineageStrength }
9
+ export interface LineageEdge { from: ExecutionReferenceV1; to: ExecutionReferenceV1; relation: LineageRelation; strength: LineageStrength }
10
+ export interface ExecutionLineageSource {
11
+ id: string; revision: string; projectKey: string; scope: string;
12
+ /** Host-owned ephemeral signing key, never supplied by a query or persisted by this reader. */
13
+ cursorKey: string;
14
+ authorized: boolean; diagnostics: boolean;
15
+ health: "ready" | "missing" | "corrupt" | "unsupported" | "withheld";
16
+ /** Owner-authorized PUBLIC root neighborhood, complete at this revision. Apply privacy in the
17
+ * owner's indexed read before these arrays or their bounds exist; never pass hidden rows here. */
18
+ nodes: readonly LineageNode[];
19
+ edges: readonly LineageEdge[];
20
+ /** Explicit host admission from saved declared references, privacy-projected independently of producer edges. */
21
+ admittedExternalTargets?: readonly ExecutionReferenceV1[];
22
+ }
23
+ export interface LineageQuery { root: ExecutionReferenceV1; cursor?: string; nodes?: number; edges?: number; bytes?: number }
24
+ export type LineageResult = { state: "unavailable"; reason?: "missing" | "corrupt" | "unsupported" | "withheld" | "cursor_invalid" | "invalid" }
25
+ | { state: "available"; nodes: LineageNode[]; edges: LineageEdge[]; truncated: boolean; cursor?: string };
26
+ const STRENGTHS: readonly string[] = ["declared", "host-observed", "runner-attested", "unknown"];
27
+ const RELATIONS: readonly string[] = ["dispatched", "attempted", "produced", "reviewed", "declared-external"];
28
+ const bytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), "utf8");
29
+ const hash = (value: unknown): string => createHash("sha256").update(JSON.stringify(value)).digest("hex");
30
+ const limit = (value: number | undefined, cap: number, min = 1): number => {
31
+ if (value === undefined) return cap;
32
+ if (!Number.isSafeInteger(value) || value < min || value > cap) throw new Error("invalid limit");
33
+ return value;
34
+ };
35
+
36
+ /** Pure bounded projection. No IO, clocks, probes, model calls, persistence or inference. */
37
+ export function readExecutionLineage(source: ExecutionLineageSource, query: LineageQuery): LineageResult {
38
+ const unavailable = (reason: NonNullable<Extract<LineageResult, { state: "unavailable" }>["reason"]>): LineageResult =>
39
+ ({ state: "unavailable", ...(source.authorized && source.diagnostics ? { reason } : {}) });
40
+ // Authority precedes even a source-health or root read: absent and denied are indistinguishable.
41
+ if (!source.authorized) return { state: "unavailable" };
42
+ if (source.health !== "ready") return unavailable(source.health);
43
+ let root: ExecutionReferenceV1, nodeLimit: number, edgeLimit: number, byteLimit: number;
44
+ try {
45
+ root = parseExecutionReference(query.root);
46
+ nodeLimit = limit(query.nodes, LINEAGE_LIMITS.nodes); edgeLimit = limit(query.edges, LINEAGE_LIMITS.edges);
47
+ byteLimit = limit(query.bytes, LINEAGE_LIMITS.bytes, LINEAGE_LIMITS.minimumBytes);
48
+ } catch { return unavailable("invalid"); }
49
+ try {
50
+ const rootKey = executionReferenceKey(root);
51
+ if (![source.id, source.revision, source.scope].every(value => executionText(value, LINEAGE_LIMITS.token)) ||
52
+ !executionText(source.cursorKey, LINEAGE_LIMITS.token) || Buffer.byteLength(source.cursorKey) < 32 ||
53
+ !executionText(source.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || root.tool !== "ahub" || root.projectKey !== source.projectKey) return unavailable("invalid");
54
+ // ponytail: oversized neighborhoods need source-owner indexed paging, never a larger inbox scan.
55
+ if (source.nodes.length > LINEAGE_LIMITS.sourceNodes || source.edges.length > LINEAGE_LIMITS.sourceEdges ||
56
+ source.admittedExternalTargets !== undefined && (!Array.isArray(source.admittedExternalTargets) || source.admittedExternalTargets.length > LINEAGE_LIMITS.sourceNodes)) return unavailable("unsupported");
57
+ const admittedTargets: ExecutionReferenceV1[] = [], admittedKeys = new Set<string>();
58
+ for (const raw of source.admittedExternalTargets ?? []) {
59
+ const ref = parseExecutionReference(raw), key = executionReferenceKey(ref);
60
+ if (ref.tool === "ahub" || admittedKeys.has(key)) return unavailable("corrupt");
61
+ admittedTargets.push(ref); admittedKeys.add(key);
62
+ }
63
+ const nodes = new Map<string, LineageNode>(), externalKeys = new Set<string>();
64
+ let size = source.admittedExternalTargets === undefined ? 0 : bytes(admittedTargets);
65
+ for (const raw of source.nodes) {
66
+ const ref = parseExecutionReference(raw.ref), key = executionReferenceKey(ref);
67
+ if ((ref.tool === "ahub" ? ref.projectKey !== source.projectKey : !admittedKeys.has(key) || raw.strength !== "declared") || !executionText(raw.state, LINEAGE_LIMITS.state) ||
68
+ !/^[a-z][a-z0-9_-]*$/.test(raw.state) || !STRENGTHS.includes(raw.strength) || nodes.has(key)) return unavailable("corrupt");
69
+ const node = { ref, state: raw.state, strength: raw.strength };
70
+ nodes.set(key, node); size += bytes(node);
71
+ if (ref.tool !== "ahub") externalKeys.add(key);
72
+ }
73
+ if (!nodes.has(rootKey)) return unavailable("missing");
74
+ const edges: LineageEdge[] = [], edgeKeys = new Set<string>();
75
+ const adjacent = new Map<string, string[]>(), targetedExternal = new Set<string>();
76
+ for (const raw of source.edges) {
77
+ const from = parseExecutionReference(raw.from), to = parseExecutionReference(raw.to);
78
+ const fromKey = executionReferenceKey(from), toKey = executionReferenceKey(to);
79
+ if (!nodes.has(fromKey) || !nodes.has(toKey) || from.tool !== "ahub" || from.projectKey !== source.projectKey) return unavailable("corrupt");
80
+ if (to.tool !== "ahub") {
81
+ if (!admittedKeys.has(toKey) || raw.relation !== "declared-external" || raw.strength !== "declared") return unavailable("corrupt");
82
+ targetedExternal.add(toKey);
83
+ }
84
+ if (!RELATIONS.includes(raw.relation) || !STRENGTHS.includes(raw.strength) ||
85
+ (raw.relation === "declared-external" && raw.strength !== "declared")) return unavailable("corrupt");
86
+ const edge = { from, to, relation: raw.relation, strength: raw.strength }, key = JSON.stringify(edge);
87
+ if (edgeKeys.has(key)) continue;
88
+ edgeKeys.add(key); edges.push(edge); size += bytes(edge);
89
+ for (const [a, b] of [[fromKey, toKey], [toKey, fromKey]] as const) {
90
+ const neighbors = adjacent.get(a) ?? []; neighbors.push(b); adjacent.set(a, neighbors);
91
+ }
92
+ }
93
+ if ([...externalKeys].some(key => !targetedExternal.has(key))) return unavailable("corrupt");
94
+ if (size > LINEAGE_LIMITS.sourceBytes) return unavailable("unsupported");
95
+ const seen = new Set([rootKey]), queue = [rootKey];
96
+ for (let i = 0; i < queue.length; i++) for (const key of adjacent.get(queue[i]!) ?? []) {
97
+ if (!seen.has(key)) { seen.add(key); queue.push(key); }
98
+ }
99
+ const visibleNodes = queue.map(key => nodes.get(key)!);
100
+ const visibleEdges = edges.filter(edge => seen.has(executionReferenceKey(edge.from)) && seen.has(executionReferenceKey(edge.to)));
101
+ const binding = hash([source.id, source.revision, source.scope, root, nodeLimit, edgeLimit, byteLimit, admittedTargets, visibleNodes, visibleEdges]);
102
+ const sign = (n: number, e: number): string => createHmac("sha256", source.cursorKey).update(JSON.stringify([binding, n, e])).digest("hex");
103
+ let n = 0, e = 0;
104
+ if (query.cursor !== undefined) {
105
+ if (typeof query.cursor !== "string" || query.cursor.length > LINEAGE_LIMITS.cursor || !/^[A-Za-z0-9_-]+$/.test(query.cursor)) return unavailable("cursor_invalid");
106
+ let cursor: unknown;
107
+ try { cursor = JSON.parse(Buffer.from(query.cursor, "base64url").toString("utf8")); }
108
+ catch { return unavailable("cursor_invalid"); }
109
+ if (!Array.isArray(cursor) || cursor.length !== 4) return unavailable("cursor_invalid");
110
+ const [cursorBinding, nextN, nextE, signature] = cursor;
111
+ if (cursorBinding !== binding || !Number.isSafeInteger(nextN) || !Number.isSafeInteger(nextE) || nextN < 0 || nextE < 0 ||
112
+ nextN > visibleNodes.length || nextE > visibleEdges.length || typeof signature !== "string" ||
113
+ !/^[0-9a-f]{64}$/.test(signature) || !timingSafeEqual(Buffer.from(signature, "hex"), Buffer.from(sign(nextN, nextE), "hex"))) return unavailable("cursor_invalid");
114
+ n = nextN; e = nextE;
115
+ }
116
+ const pageNodes: LineageNode[] = [], pageEdges: LineageEdge[] = [];
117
+ const page = (nextN: number, nextE: number): Extract<LineageResult, { state: "available" }> => {
118
+ const truncated = nextN < visibleNodes.length || nextE < visibleEdges.length;
119
+ return { state: "available", nodes: pageNodes, edges: pageEdges, truncated,
120
+ ...(truncated ? { cursor: Buffer.from(JSON.stringify([binding, nextN, nextE, sign(nextN, nextE)])).toString("base64url") } : {}) };
121
+ };
122
+ while (n < visibleNodes.length && pageNodes.length < nodeLimit) {
123
+ pageNodes.push(visibleNodes[n]!);
124
+ if (bytes(page(n + 1, e)) > byteLimit) { pageNodes.pop(); break; }
125
+ n++;
126
+ }
127
+ while (e < visibleEdges.length && pageEdges.length < edgeLimit) {
128
+ pageEdges.push(visibleEdges[e]!);
129
+ if (bytes(page(n, e + 1)) > byteLimit) { pageEdges.pop(); break; }
130
+ e++;
131
+ }
132
+ if (!pageNodes.length && !pageEdges.length && (n < visibleNodes.length || e < visibleEdges.length)) return unavailable("unsupported");
133
+ return page(n, e);
134
+ } catch { return unavailable("corrupt"); }
135
+ }
136
+
137
+ /** Refuse unsupported reply shapes instead of presenting an incomplete page as a successful graph. */
138
+ export function parseLineageResult(value: unknown): LineageResult {
139
+ const bad = (): never => { throw new Error("lineage reply has an unsupported shape; upgrade and restart the hub, then retry"); };
140
+ try {
141
+ if (!value || typeof value !== "object" || Array.isArray(value) || !Object.hasOwn(value, "state") || Buffer.byteLength(JSON.stringify(value)) > LINEAGE_LIMITS.bytes) return bad();
142
+ const row = value as Record<string, any>;
143
+ if (row.state === "unavailable") {
144
+ if (Object.keys(row).some(key => !["state", "reason"].includes(key)) || row.reason !== undefined && !["missing", "corrupt", "unsupported", "withheld", "cursor_invalid", "invalid"].includes(row.reason)) return bad();
145
+ return value as LineageResult;
146
+ }
147
+ if (row.state !== "available" || !["nodes", "edges", "truncated"].every(key => Object.hasOwn(row, key)) || Object.keys(row).some(key => !["state", "nodes", "edges", "truncated", "cursor"].includes(key)) ||
148
+ !Array.isArray(row.nodes) || row.nodes.length > LINEAGE_LIMITS.nodes || !Array.isArray(row.edges) || row.edges.length > LINEAGE_LIMITS.edges || typeof row.truncated !== "boolean" ||
149
+ row.cursor !== undefined && (typeof row.cursor !== "string" || row.cursor.length > LINEAGE_LIMITS.cursor || !/^[A-Za-z0-9_-]+$/.test(row.cursor)) || row.truncated && row.cursor === undefined || !row.truncated && Object.hasOwn(row, "cursor")) return bad();
150
+ for (const node of row.nodes) {
151
+ if (!node || typeof node !== "object" || Array.isArray(node) || !["ref", "state", "strength"].every(key => Object.hasOwn(node, key)) || Object.keys(node).some(key => !["ref", "state", "strength"].includes(key)) ||
152
+ typeof node.state !== "string" || node.state.length > LINEAGE_LIMITS.state || !/^[a-z][a-z0-9_-]*$/.test(node.state) || !STRENGTHS.includes(node.strength)) return bad();
153
+ parseExecutionReference(node.ref);
154
+ if (node.ref.tool !== "ahub" && node.strength !== "declared") return bad();
155
+ }
156
+ for (const edge of row.edges) {
157
+ if (!edge || typeof edge !== "object" || Array.isArray(edge) || !["from", "to", "relation", "strength"].every(key => Object.hasOwn(edge, key)) || Object.keys(edge).some(key => !["from", "to", "relation", "strength"].includes(key)) ||
158
+ !RELATIONS.includes(edge.relation) || !STRENGTHS.includes(edge.strength) || edge.relation === "declared-external" && edge.strength !== "declared") return bad();
159
+ parseExecutionReference(edge.from); parseExecutionReference(edge.to);
160
+ if (edge.from.tool !== "ahub" || edge.to.tool !== "ahub" && (edge.relation !== "declared-external" || edge.strength !== "declared")) return bad();
161
+ }
162
+ return value as LineageResult;
163
+ } catch { return bad(); }
164
+ }
@@ -0,0 +1,85 @@
1
+ import { createHash } from "node:crypto";
2
+ import { types } from "node:util";
3
+ import { executionReferenceKey, executionText, parseExecutionReference, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
4
+
5
+ export const EXECUTION_LINK_LIMITS = Object.freeze({ perTask: 64, read: 65, referenceBytes: 2048, actor: 32 });
6
+ export interface ExecutionLinkInput {
7
+ taskId: number; taskCreated: number; flowRevision: number;
8
+ from?: ExecutionReferenceV1; reference: ExecutionReferenceV1;
9
+ }
10
+ export interface ExecutionLinkRecord {
11
+ id: string; projectKey: string; taskId: number; taskCreated: number;
12
+ from: ExecutionReferenceV1; reference: ExecutionReferenceV1;
13
+ strength: "declared"; recordedBy: string; recordedAt: number;
14
+ }
15
+ export interface ExecutionLinkFence { by: string; at: number }
16
+ export class ExecutionLinkError extends Error {
17
+ constructor(readonly code: "invalid" | "changed" | "limit" | "corrupt") {
18
+ super({
19
+ invalid: "invalid execution reference metadata; read the current task and supply its identity, revision and bounded ExecutionReferenceV1 fields before retrying",
20
+ changed: "execution reference task authority or revision changed; read the current task and retry with an authorized current role outside private context",
21
+ limit: "execution reference task limit reached; inspect the recorded lineage and reuse an existing reference before adding another",
22
+ corrupt: "execution reference storage is invalid; stop the hub, restore a trusted hub.db backup, then restart and retry",
23
+ }[code]);
24
+ this.name = "ExecutionLinkError";
25
+ }
26
+ }
27
+ const invalid = (): never => { throw new ExecutionLinkError("invalid"); };
28
+ function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
29
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
30
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalid();
31
+ const own = Reflect.ownKeys(value);
32
+ if (own.length > keys.length) return invalid();
33
+ const result: Record<string, unknown> = Object.create(null);
34
+ for (const key of own) {
35
+ if (typeof key !== "string" || !keys.includes(key)) return invalid();
36
+ const field = Object.getOwnPropertyDescriptor(value, key);
37
+ if (!field || !("value" in field) || !field.enumerable) return invalid();
38
+ result[key] = field.value;
39
+ }
40
+ return result;
41
+ }
42
+ export const executionLinkInteger = (value: unknown, minimum = 0): value is number =>
43
+ typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
44
+ export const executionLinkActor = (value: unknown): value is string =>
45
+ typeof value === "string" && value.length <= EXECUTION_LINK_LIMITS.actor && /^[a-z][a-z0-9-]*$/.test(value);
46
+ export function parseExecutionLinkInput(value: unknown): ExecutionLinkInput {
47
+ try {
48
+ const input = object(value, ["taskId", "taskCreated", "flowRevision", "from", "reference"]);
49
+ if (!executionLinkInteger(input.taskId, 1) || !executionLinkInteger(input.taskCreated) || !executionLinkInteger(input.flowRevision)) return invalid();
50
+ return { taskId: input.taskId, taskCreated: input.taskCreated, flowRevision: input.flowRevision,
51
+ ...(Object.hasOwn(input, "from") ? { from: parseExecutionReference(input.from) } : {}), reference: parseExecutionReference(input.reference) };
52
+ } catch { return invalid(); }
53
+ }
54
+ /** Task epoch is an existing source identity. Mutable history revision remains a separate write fence. */
55
+ export function taskExecutionReference(projectKey: string, taskId: number, taskCreated: number): ExecutionReferenceV1 {
56
+ if (!executionLinkInteger(taskId, 1) || !executionLinkInteger(taskCreated)) return invalid();
57
+ try { return parseExecutionReference({ v: 1, tool: "ahub", projectKey, kind: "task", id: `${taskId}:${taskCreated}` }); }
58
+ catch { return invalid(); }
59
+ }
60
+ export function executionLinkReferences(projectKey: string, value: ExecutionLinkInput): { from: ExecutionReferenceV1; reference: ExecutionReferenceV1 } {
61
+ if (!executionText(projectKey, EXECUTION_REFERENCE_LIMITS.projectKey)) return invalid();
62
+ const input = parseExecutionLinkInput(value), from = input.from ?? taskExecutionReference(projectKey, input.taskId, input.taskCreated);
63
+ if (from.tool !== "ahub" || from.projectKey !== projectKey || input.reference.tool === "ahub" && input.reference.projectKey !== projectKey) return invalid();
64
+ return { from, reference: input.reference };
65
+ }
66
+ export const executionReferenceDigest = (ref: ExecutionReferenceV1): string => createHash("sha256").update(executionReferenceKey(ref)).digest("hex");
67
+ /** Actor, time and observed task revision are guards/audit, not dedup identity. */
68
+ export function executionLinkId(projectKey: string, value: ExecutionLinkInput): string {
69
+ const input = parseExecutionLinkInput(value), refs = executionLinkReferences(projectKey, input);
70
+ return createHash("sha256").update(JSON.stringify(["agent-hub.execution-link/v1", projectKey, input.taskId, input.taskCreated, refs.from, refs.reference])).digest("hex");
71
+ }
72
+ /** Stored rows are authenticated by their owner read, not by this address/digest validation. */
73
+ export function parseExecutionLinkRecord(value: unknown): ExecutionLinkRecord {
74
+ try {
75
+ const row = object(value, ["id", "projectKey", "taskId", "taskCreated", "from", "reference", "strength", "recordedBy", "recordedAt"]);
76
+ if (typeof row.id !== "string" || !/^[a-f0-9]{64}$/.test(row.id) || !executionText(row.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey)
77
+ || !executionLinkInteger(row.taskId, 1) || !executionLinkInteger(row.taskCreated) || row.strength !== "declared"
78
+ || !executionLinkActor(row.recordedBy) || !executionLinkInteger(row.recordedAt)) throw new Error();
79
+ const input = { taskId: row.taskId, taskCreated: row.taskCreated, flowRevision: 0, from: parseExecutionReference(row.from), reference: parseExecutionReference(row.reference) };
80
+ const refs = executionLinkReferences(row.projectKey, input);
81
+ if (executionLinkId(row.projectKey, input) !== row.id) throw new Error();
82
+ return { id: row.id, projectKey: row.projectKey, taskId: row.taskId, taskCreated: row.taskCreated, ...refs,
83
+ strength: "declared", recordedBy: row.recordedBy, recordedAt: row.recordedAt };
84
+ } catch { throw new ExecutionLinkError("corrupt"); }
85
+ }
@@ -0,0 +1,36 @@
1
+ import { types } from "node:util";
2
+ /** ExecutionReferenceV1 is an opaque address, never authority or a resolver instruction. */
3
+ export const EXECUTION_PRODUCERS = ["ahub", "ares", "amem", "vmem"] as const;
4
+ export interface ExecutionReferenceV1 {
5
+ v: 1;
6
+ tool: typeof EXECUTION_PRODUCERS[number];
7
+ projectKey: string;
8
+ kind: string;
9
+ id: string;
10
+ revision?: string;
11
+ sha256?: string;
12
+ }
13
+ export const EXECUTION_REFERENCE_LIMITS = Object.freeze({ id: 256, projectKey: 256, revision: 128, kind: 64 });
14
+ const invalid = (): never => { throw new Error("execution reference has invalid fields or bounds; use the ExecutionReferenceV1 contract"); };
15
+ export function executionText(value: unknown, max: number): value is string {
16
+ return typeof value === "string" && value.length > 0 && value.length <= max &&
17
+ Buffer.byteLength(value, "utf8") <= max && !/[\p{Cc}\p{Cs}]/u.test(value);
18
+ }
19
+ export function parseExecutionReference(input: unknown): ExecutionReferenceV1 {
20
+ if (!input || typeof input !== "object" || types.isProxy(input) || Array.isArray(input) ||
21
+ ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length) return invalid();
22
+ const fields = Object.getOwnPropertyDescriptors(input);
23
+ const keys = ["v", "tool", "projectKey", "kind", "id", "revision", "sha256"];
24
+ if (Object.entries(fields).some(([key, field]) => !keys.includes(key) || !("value" in field))) return invalid();
25
+ const get = (key: string): unknown => fields[key]?.value;
26
+ const tool = get("tool"), projectKey = get("projectKey"), kind = get("kind"), id = get("id");
27
+ if (get("v") !== 1 || !EXECUTION_PRODUCERS.includes(tool as ExecutionReferenceV1["tool"]) ||
28
+ !executionText(projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || !executionText(id, EXECUTION_REFERENCE_LIMITS.id) ||
29
+ !executionText(kind, EXECUTION_REFERENCE_LIMITS.kind) || !/^[a-z][a-z0-9._-]*$/.test(kind)) return invalid();
30
+ const revision = get("revision"), sha256 = get("sha256");
31
+ if ((Object.hasOwn(fields, "revision") && !executionText(revision, EXECUTION_REFERENCE_LIMITS.revision)) ||
32
+ (Object.hasOwn(fields, "sha256") && (typeof sha256 !== "string" || !/^[0-9a-f]{64}$/.test(sha256)))) return invalid();
33
+ return { v: 1, tool: tool as ExecutionReferenceV1["tool"], projectKey, kind, id,
34
+ ...(revision === undefined ? {} : { revision: revision as string }), ...(sha256 === undefined ? {} : { sha256: sha256 as string }) };
35
+ }
36
+ export const executionReferenceKey = (ref: ExecutionReferenceV1): string => JSON.stringify(parseExecutionReference(ref));