@staix/agent-hub 0.35.0 → 0.37.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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
@@ -1,5 +1,7 @@
1
1
  import { KINDS, sanitize, type Kind } from "./envelope.ts";
2
2
 
3
+ export const HELD_DELIVERY_PAGE = 32;
4
+ export const MAX_HELD_HINT_ROWS = 32;
3
5
  export const DELIVERY_RETRY_WARNING = sanitize("Hub redelivery warning: An earlier attempt of this delivery is uncertain; check for its effects before acting.");
4
6
  export interface HeldDeliveryHints {
5
7
  count: number;
@@ -10,7 +12,7 @@ export function heldDeliveryHints(rows: readonly HeldDeliveryHints["rows"][numbe
10
12
  const result: HeldDeliveryHints = { count, rows: [], truncated: count > rows.length };
11
13
  for (const row of rows) {
12
14
  const value = { ...row, senders: row.senders.map(sanitize) };
13
- if (result.rows.length >= 32 || Buffer.byteLength(JSON.stringify({ ...result, rows: [...result.rows, value] }), "utf8") > 3500) { result.truncated = true; break; }
15
+ if (result.rows.length >= HELD_DELIVERY_PAGE || Buffer.byteLength(JSON.stringify({ ...result, rows: [...result.rows, value] }), "utf8") > 3500) { result.truncated = true; break; }
14
16
  result.rows.push(value);
15
17
  }
16
18
  return result;
@@ -20,7 +22,7 @@ export function renderHeldHint(value: unknown, now = Date.now(), recipientRetry
20
22
  const held = value as HeldDeliveryHints;
21
23
  const kinds = new Set<string>(KINDS);
22
24
  try {
23
- if (!Number.isSafeInteger(held.count) || held.count < 1 || !Array.isArray(held.rows) || held.rows.length > 32 || held.rows.length > held.count || typeof held.truncated !== "boolean" || Buffer.byteLength(JSON.stringify(held), "utf8") > 4096) return "";
25
+ if (!Number.isSafeInteger(held.count) || held.count < 1 || !Array.isArray(held.rows) || held.rows.length > MAX_HELD_HINT_ROWS || held.rows.length > held.count || typeof held.truncated !== "boolean" || Buffer.byteLength(JSON.stringify(held), "utf8") > 4096) return "";
24
26
  if (held.rows.some(row => !row || typeof row !== "object" || typeof row.id !== "string" || !row.id.length || row.id.length > 256 || !Number.isFinite(row.createdAt) || !Array.isArray(row.senders) || !Array.isArray(row.kinds) || row.senders.some(sender => typeof sender !== "string" || sender.length > 256) || row.kinds.some(kind => !kinds.has(kind)))) return "";
25
27
  } catch { return ""; }
26
28
  if (held.rows.some(row => row.state !== undefined && row.state !== "accepted" && row.state !== "needs_review")) return "";
@@ -7,7 +7,8 @@ import { openHubDatabase } from "./db-schema.ts";
7
7
  import type { BusSnapshot } from "./bus.ts";
8
8
  import type { QueuePressure } from "./queue-backpressure.ts";
9
9
  import { HUB, KINDS, USER, isInvocationKind, type Envelope, type Kind } from "./envelope.ts";
10
- import { heldDeliveryHints } from "./delivery-hints.ts";
10
+ import { HELD_DELIVERY_PAGE, heldDeliveryHints } from "./delivery-hints.ts";
11
+ import { isReviewObserverExcluded } from "./memory-policy.ts";
11
12
  import { processLiveness } from "../pi/process-signature.ts";
12
13
  import { parseRemotePeerId } from "../rooms/application.ts";
13
14
  import { validateDeferredHub } from "./deferred-hub.ts";
@@ -1505,6 +1506,29 @@ export class DeliveryJournal {
1505
1506
  AND json_type(e.value,'$.refs.reviewPackage')='text' AND (?3 IS NULL OR json_extract(e.value,'$.refs.task')=?3)
1506
1507
  LIMIT 1`).get(this.projectId, peer, taskId);
1507
1508
  }
1509
+ /** Observer-only bridge for read-only held inspection; no refresh or delivery receipt. */
1510
+ hasHeldReviewScope(peer: string, includeAccepted: boolean, byteBudget: number): boolean {
1511
+ this.ensureOpen();
1512
+ const states = includeAccepted ? "('needs_review','accepted')" : "('needs_review')";
1513
+ const revision = this.revision();
1514
+ const window = this.db.query(`SELECT length(CAST(originals AS BLOB)) AS bytes FROM deliveries WHERE project_id=? AND peer=? AND state IN ${states} ORDER BY created_at,id LIMIT ?`).all(this.projectId, peer, HELD_DELIVERY_PAGE + 1) as { bytes: number }[];
1515
+ // No durable view receipt exists. A bounded-away row may have been read before
1516
+ // the window shifted, so overflow is unknown/excluded, never proof of absence.
1517
+ let remaining = byteBudget;
1518
+ if (window.length > HELD_DELIVERY_PAGE || window.some(row => { if (row.bytes > remaining) return true; remaining -= row.bytes; return false; })) return true;
1519
+ const metadata = this.db.query(`WITH candidates AS MATERIALIZED (SELECT originals FROM deliveries WHERE project_id=? AND peer=? AND state IN ${states} ORDER BY created_at,id LIMIT ?) SELECT CASE WHEN json_type(d.originals)='array' AND length(CAST(d.originals AS BLOB)) <= ? THEN 1 ELSE 0 END AS readable,e.key AS envelope_key,json_extract(e.value,'$.from') AS sender,json_extract(e.value,'$.kind') AS kind,json_extract(e.value,'$.refs.reviewPackage') AS review_package,json_extract(e.value,'$.refs.reviewResponse') AS review_response FROM candidates d LEFT JOIN json_each(CASE WHEN json_type(d.originals)='array' AND length(CAST(d.originals AS BLOB)) <= ? THEN d.originals ELSE '[]' END) e`).all(this.projectId, peer, HELD_DELIVERY_PAGE, byteBudget, byteBudget) as { readable: number; envelope_key: unknown; sender: unknown; kind: unknown; review_package: unknown; review_response: unknown }[];
1520
+ const excluded = metadata.some(row => {
1521
+ if (row.readable !== 1) return true;
1522
+ if (row.envelope_key === null) return false; // A readable empty original list carries no review input.
1523
+ if (typeof row.sender !== "string" || !KINDS.includes(row.kind as Kind)) return true;
1524
+ return isReviewObserverExcluded({ from: row.sender, kind: row.kind as Kind, refs: {
1525
+ ...(typeof row.review_package === "string" ? { reviewPackage: row.review_package } : {}),
1526
+ ...(typeof row.review_response === "string" ? { reviewResponse: row.review_response } : {}),
1527
+ } });
1528
+ });
1529
+ return excluded || this.revision() !== revision;
1530
+ }
1531
+
1508
1532
  /** Hot roster reads never materialize completed envelope history. */
1509
1533
  pendingPeers(): string[] {
1510
1534
  this.ensureOpen();
@@ -1552,10 +1576,34 @@ export class DeliveryJournal {
1552
1576
  this.ensureOpen();
1553
1577
  const states = includeAccepted ? "('needs_review','accepted')" : "('needs_review')";
1554
1578
  const count = Number((this.db.query(`SELECT COUNT(*) AS n FROM deliveries WHERE project_id = ? AND peer = ? AND state IN ${states}`).get(this.projectId, peer) as { n: number }).n);
1555
- const rows = this.db.query(`SELECT d.id, d.revision, d.created_at, d.state, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.from')) FROM json_each(d.originals) env) AS senders, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.kind')) FROM json_each(d.originals) env) AS kinds FROM deliveries d WHERE d.project_id = ? AND d.peer = ? AND d.state IN ${states} ORDER BY d.created_at, d.id LIMIT 33`).all(this.projectId, peer) as { id: string; revision: number; created_at: number; state: "accepted" | "needs_review"; senders: string; kinds: string }[];
1579
+ const rows = this.db.query(`SELECT d.id, d.revision, d.created_at, d.state, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.from')) FROM json_each(d.originals) env) AS senders, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.kind')) FROM json_each(d.originals) env) AS kinds FROM deliveries d WHERE d.project_id = ? AND d.peer = ? AND d.state IN ${states} ORDER BY d.created_at, d.id LIMIT ?`).all(this.projectId, peer, HELD_DELIVERY_PAGE + 1) as { id: string; revision: number; created_at: number; state: "accepted" | "needs_review"; senders: string; kinds: string }[];
1556
1580
  return heldDeliveryHints(rows.map(row => ({ id: row.id, revision: row.revision, createdAt: row.created_at, ...(includeAccepted ? { state: row.state } : {}), senders: JSON.parse(row.senders) as string[], kinds: JSON.parse(row.kinds) as Kind[] })), count);
1557
1581
  }
1558
1582
 
1583
+ /** Read-only recipient view. Bound raw JSON bytes in SQL before hydrating originals. */
1584
+ heldInbox(peer: string, includeAccepted: boolean, byteBudget: number) {
1585
+ this.ensureOpen();
1586
+ text(peer, "held inbox peer", 256); integer(byteBudget, "held inbox byte budget", 1);
1587
+ const states = includeAccepted ? "('needs_review','accepted')" : "('needs_review')";
1588
+ const count = Number((this.db.query(`SELECT COUNT(*) AS n FROM deliveries WHERE project_id = ? AND peer = ? AND state IN ${states}`).get(this.projectId, peer) as { n: number }).n);
1589
+ const rows: Array<{ id: string; revision: number; state: "needs_review" | "accepted"; originals: Envelope[] }> = [];
1590
+ if (count === 0) return { count, rows, truncated: false };
1591
+ // This read deliberately does not refresh legacy coverage or persist an input receipt.
1592
+ const provenance = this.readReviewInputProvenance();
1593
+ if (!provenance.complete || !provenance.coverageComplete) return { count, rows, truncated: count > 0, unavailable: true };
1594
+ const candidates = this.db.query(`SELECT id,revision,state,length(CAST(originals AS BLOB)) AS bytes FROM deliveries WHERE project_id = ? AND peer = ? AND state IN ${states} ORDER BY created_at,id LIMIT ?`).all(this.projectId, peer, HELD_DELIVERY_PAGE + 1) as { id: string; revision: number; state: "needs_review" | "accepted"; bytes: number }[];
1595
+ let remaining = byteBudget, unavailable = false;
1596
+ for (const candidate of candidates.slice(0, HELD_DELIVERY_PAGE)) {
1597
+ if (!Number.isSafeInteger(candidate.bytes) || candidate.bytes < 0 || candidate.bytes > remaining) { unavailable = true; break; }
1598
+ const row = this.db.query(`SELECT originals FROM deliveries WHERE project_id = ? AND peer = ? AND id = ? AND revision = ? AND state IN ${states} AND length(CAST(originals AS BLOB)) <= ?`).get(this.projectId, peer, candidate.id, candidate.revision, remaining) as { originals: string } | null;
1599
+ if (!row) { unavailable = true; break; }
1600
+ const originals = list(JSON.parse(row.originals), "held inbox originals", 2048).map((env, i) => validateEnvelope(env, `held inbox original ${i}`));
1601
+ rows.push({ id: candidate.id, revision: candidate.revision, state: candidate.state, originals });
1602
+ remaining -= candidate.bytes;
1603
+ }
1604
+ return { count, rows, truncated: rows.length < count, ...(unavailable ? { unavailable: true } : {}) };
1605
+ }
1606
+
1559
1607
  /** Bounded indexed scan; the caller performs a revision-fenced state transition. */
1560
1608
  expiredAccepted(cutoff: number, peers: readonly string[], limit = 256): AcceptedDeliveryCandidate[] {
1561
1609
  this.ensureOpen(); integer(cutoff, "accepted cutoff"); integer(limit, "accepted expiry limit", 1, 1024);
@@ -0,0 +1,51 @@
1
+ import { MAX_HELD_HINT_ROWS } from "./delivery-hints.ts";
2
+ import { BUS_PULL_BUDGET_BYTES_SETTING } from "./operational-settings.ts";
3
+ import { KINDS, sanitize, type Envelope } from "./envelope.ts";
4
+
5
+ export interface DeliveryPublicPolicy {
6
+ publicOnly: boolean;
7
+ taskPrivate(task: string): boolean;
8
+ publicMetadataText(text: string): boolean;
9
+ }
10
+ /** Body-only queue projection, shared by diagnostics and recipient held reads. */
11
+ export function publicDeliveryBodies(originals: readonly Envelope[], policy: DeliveryPublicPolicy) {
12
+ const privateDelivery = originals.some(env => env.private || policy.publicOnly && env.refs?.task && policy.taskPrivate(env.refs.task));
13
+ return originals.map(env => ({ id: env.id, from: env.from, priority: env.priority, kind: env.kind,
14
+ body: privateDelivery ? "[private: inspect the associated task with ahub task show]"
15
+ : policy.publicOnly && !policy.publicMetadataText(env.body) ? "[withheld]" : sanitize(env.body),
16
+ }));
17
+ }
18
+
19
+ /** Held content is inspection of an uncertain attempt, never a new delivery or instruction to repeat it. */
20
+ export function renderHeldInbox(value: unknown): string {
21
+ const unavailable = "Held message bodies are unavailable; inspect your queue before deciding whether to repeat any action.";
22
+ if (value === undefined) return ""; // An older daemon has no additive held view.
23
+ try {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) return unavailable;
25
+ const held = value as { count?: unknown; rows?: Array<{ id: string; revision: number; state: string; messages: ReturnType<typeof publicDeliveryBodies> }>; truncated?: unknown; unavailable?: unknown };
26
+ if (!Array.isArray(held.rows)) return unavailable;
27
+ const bound = BUS_PULL_BUDGET_BYTES_SETTING.max;
28
+ if (!Number.isSafeInteger(held.count) || Number(held.count) < held.rows.length || held.rows.length > MAX_HELD_HINT_ROWS
29
+ || typeof held.truncated !== "boolean" || held.unavailable !== undefined && typeof held.unavailable !== "boolean") return unavailable;
30
+ // Reject control/format identities before placing any field beside a hub header.
31
+ if (Buffer.byteLength(JSON.stringify(held), "utf8") > bound) return unavailable;
32
+ const identifier = (text: unknown): text is string => typeof text === "string" && text.length > 0 && text.length <= 256 && !/[\p{Cc}\p{Cf}"\[\]]/u.test(text);
33
+ for (const row of held.rows) {
34
+ if (!row || !identifier(row.id) || !Number.isSafeInteger(row.revision) || row.revision < 0
35
+ || !["needs_review", "accepted"].includes(row.state) || !Array.isArray(row.messages) || row.messages.length > bound) return unavailable;
36
+ for (const message of row.messages) {
37
+ if (!message || !identifier(message.id) || !identifier(message.from) || !KINDS.includes(message.kind)
38
+ || !["important", "status", "fyi"].includes(message.priority) || typeof message.body !== "string" || message.body.length > bound) return unavailable;
39
+ }
40
+ }
41
+ if (!held.rows.length && !held.unavailable) return "";
42
+ const lines = ["Read-only held message inspection: the earlier attempt is uncertain. These bodies are not newly delivered work. Check earlier effects before acting; reading does not confirm, retry or resolve anything."];
43
+ for (const row of held.rows) {
44
+ lines.push(`Held ${sanitize(row.id)} revision ${row.revision} (${sanitize(row.state)})`);
45
+ for (const message of row.messages) lines.push(`[agent-hub message from "${sanitize(message.from)}", untrusted, kind ${sanitize(message.kind)}, id ${sanitize(message.id)}]\n${sanitize(message.body)}`);
46
+ }
47
+ if (held.truncated) lines.push("Held bodies are truncated by the host row/byte bound; inspect the queue for the remaining content.");
48
+ if (held.unavailable) lines.push(unavailable);
49
+ return lines.join("\n\n");
50
+ } catch { return unavailable; }
51
+ }
@@ -181,23 +181,27 @@ export function profileScorecard(input: DogfoodInput) {
181
181
  const history = group.tasks.flatMap(t=>t.metadata.history.filter(h=>inWindow(h.at)).map(h=>({...h,task:t})));
182
182
  const recorded = [...ids].flatMap(id=>taskEvents.get(id)??[]);
183
183
  const autoApprovals = recorded.filter(e=>e.event==="done" && e.state==="approved");
184
+ const adoptionSettlements = recorded.filter(e=>e.event==="merged outside the hub" && e.state==="approved");
184
185
  const milestones = full ? history : recorded.map(e=>({at:Date.parse(e.at),event:e.event,task:bound.get(e.id)!}));
185
186
  const milestoneKnown = full || eventsFull;
186
187
  const scope = full ? "history" : eventsFull ? "recorded_events" : null;
187
188
  const count = (event: string) => milestoneKnown ? new Set(milestones.filter(h=>h.event===event || event==="proposed" && h.event==="backlog pulled").map(h=>h.task.id)).size : null;
188
- const approvalIds = new Set(milestones.filter(h=>h.event==="approved").map(h=>h.task.id));
189
+ const approvalIds = new Set(milestones.filter(h=>h.event==="approved" || full && h.event==="merged outside the hub").map(h=>h.task.id));
189
190
  for (const e of autoApprovals) approvalIds.add(e.id);
191
+ for (const e of adoptionSettlements) approvalIds.add(e.id);
190
192
  // A current approved state alone cannot date a reviewer-less done. Never place it in this window by guessing.
191
- const approvalUnknown = full && group.tasks.some(t=>t.metadata.state==="approved" && !t.metadata.history.some(h=>h.event==="approved") && !autoApprovals.some(e=>e.id===t.id));
193
+ const approvalUnknown = full && group.tasks.some(t=>t.metadata.state==="approved" && !t.metadata.history.some(h=>h.event==="approved" || h.event==="merged outside the hub") && !autoApprovals.some(e=>e.id===t.id) && !adoptionSettlements.some(e=>e.id===t.id));
192
194
  const leads: number[] = [], first: number[] = [];
193
195
  for (const task of group.tasks) {
194
196
  const all = task.metadata.history.filter(h=>h.at<=input.until).sort((a,b)=>a.at-b.at);
195
197
  const proposed = all.find(h=>h.event==="proposed" || h.event==="backlog pulled");
196
198
  const approval = all.findLast(h=>h.event==="approved" && inWindow(h.at));
197
199
  const automatic = autoApprovals.filter(e=>e.id===task.id).map(e=>Date.parse(e.at)).sort((a,b)=>b-a)[0];
198
- const approvedAt = approval?.at ?? automatic;
200
+ const settlement = all.findLast(h=>(h.event==="approved" || h.event==="merged outside the hub") && inWindow(h.at));
201
+ const adopted = adoptionSettlements.filter(e=>e.id===task.id).map(e=>Date.parse(e.at)).sort((a,b)=>b-a).shift();
202
+ const approvedAt = settlement?.at ?? adopted ?? automatic;
199
203
  if (proposed && approvedAt!==undefined && approvedAt>=proposed.at) leads.push(approvedAt-proposed.at);
200
- // An automatic completion is an approval transition, never a reviewer verdict or first-pass review sample.
204
+ // Automatic completion and merge adoption settle the task, never a reviewer verdict or first-pass review sample.
201
205
  if (approval) { const verdict = all.find(h=>h.event==="approved" || h.event==="changes_requested"); if (verdict) first.push(Number(verdict.event==="approved")); }
202
206
  }
203
207
  const verdicts = milestones.filter(h=>h.event==="approved" || h.event==="changes_requested");
package/src/hub/events.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
2
  import type { TaskAttribution } from "./attribution.ts";
3
3
  import type { PeerId } from "./envelope.ts";
4
- import type { SwitchTrace } from "../models/route/stage.ts";
4
+ import type { StageSwitchTrace as SwitchTrace } from "../models/route/stage-fallback.ts";
5
5
  import type { ScreenRecord } from "./inference.ts";
6
6
 
7
7
  export interface RoleIdentity { id: string; layer: "shipped" | "project"; hash: string }
@@ -16,6 +16,7 @@ export const EVENTS_SCHEMA = 1;
16
16
  export type HubEvent =
17
17
  | { type: "model_change"; peer: string; previousModel: string | null; model: string | null; by: "person"; source: "cli" | "dashboard"; appliesFrom: "next_turn"; afterTurn?: string }
18
18
  | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docsDigest: string; documents: number }
19
+ | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docs: "none" }
19
20
  | { type: "permission_mode"; peer: string; from: import("./permission-mode.ts").PermissionMode; to: import("./permission-mode.ts").PermissionMode }
20
21
  | { type: "role"; peer?: string; task?: number; actor: string; stage: "prepared" | "assigned"; roles: { id: string; layer: "shipped" | "project"; hash: string }[] }
21
22
  /** A settings change (#269): the registry key, the bounded registry values before/after and their source; an optional person reason is sanitized and capped at 400 UTF-8 bytes. */
@@ -35,7 +36,7 @@ export type HubEvent =
35
36
  | { type: "quiet"; id: string; from: string; peers: string[] }
36
37
  | { type: "fact"; peer: string; id: string; files: number; plans: number; unknown: number; named: number; bytes: number; via: "hook" | "steer" | "done"; ms?: number; hookMs?: number; rttMs?: number; accepted?: boolean; unanswered?: boolean; probe?: boolean; coverage?: boolean }
37
38
  | { type: "fact_ack"; peer: string; id: string; via: string; ms: number }
38
- | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace>)
39
+ | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionTarget?: "judge"; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace>)
39
40
  | { type: "cooldown"; peer: string; alias: string; event: "start" | "end"; failures: number; ms?: number }
40
41
  | { type: "route_outcome"; peer: string; decision: string; turnId: string; turn: "completed" | "failed"; task?: number; pii: boolean; latched: boolean; next?: { severity: number; tests: "pass" | "fail" | "none"; repeat: boolean }; advisor?: "approve" | "redo" | "failed" }
41
42
  | { type: "advisor"; peer: string; route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
@@ -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
+ }
@@ -17,6 +17,8 @@ export interface ExecutionLineageSource {
17
17
  * owner's indexed read before these arrays or their bounds exist; never pass hidden rows here. */
18
18
  nodes: readonly LineageNode[];
19
19
  edges: readonly LineageEdge[];
20
+ /** Explicit host admission from saved declared references, privacy-projected independently of producer edges. */
21
+ admittedExternalTargets?: readonly ExecutionReferenceV1[];
20
22
  }
21
23
  export interface LineageQuery { root: ExecutionReferenceV1; cursor?: string; nodes?: number; edges?: number; bytes?: number }
22
24
  export type LineageResult = { state: "unavailable"; reason?: "missing" | "corrupt" | "unsupported" | "withheld" | "cursor_invalid" | "invalid" }
@@ -48,25 +50,37 @@ export function readExecutionLineage(source: ExecutionLineageSource, query: Line
48
50
  const rootKey = executionReferenceKey(root);
49
51
  if (![source.id, source.revision, source.scope].every(value => executionText(value, LINEAGE_LIMITS.token)) ||
50
52
  !executionText(source.cursorKey, LINEAGE_LIMITS.token) || Buffer.byteLength(source.cursorKey) < 32 ||
51
- !executionText(source.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || root.projectKey !== source.projectKey) return unavailable("invalid");
53
+ !executionText(source.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || root.tool !== "ahub" || root.projectKey !== source.projectKey) return unavailable("invalid");
52
54
  // ponytail: oversized neighborhoods need source-owner indexed paging, never a larger inbox scan.
53
- if (source.nodes.length > LINEAGE_LIMITS.sourceNodes || source.edges.length > LINEAGE_LIMITS.sourceEdges) return unavailable("unsupported");
54
- const nodes = new Map<string, LineageNode>();
55
- let size = 0;
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);
56
65
  for (const raw of source.nodes) {
57
66
  const ref = parseExecutionReference(raw.ref), key = executionReferenceKey(ref);
58
- if (ref.projectKey !== source.projectKey || !executionText(raw.state, LINEAGE_LIMITS.state) ||
67
+ if ((ref.tool === "ahub" ? ref.projectKey !== source.projectKey : !admittedKeys.has(key) || raw.strength !== "declared") || !executionText(raw.state, LINEAGE_LIMITS.state) ||
59
68
  !/^[a-z][a-z0-9_-]*$/.test(raw.state) || !STRENGTHS.includes(raw.strength) || nodes.has(key)) return unavailable("corrupt");
60
69
  const node = { ref, state: raw.state, strength: raw.strength };
61
70
  nodes.set(key, node); size += bytes(node);
71
+ if (ref.tool !== "ahub") externalKeys.add(key);
62
72
  }
63
73
  if (!nodes.has(rootKey)) return unavailable("missing");
64
74
  const edges: LineageEdge[] = [], edgeKeys = new Set<string>();
65
- const adjacent = new Map<string, string[]>();
75
+ const adjacent = new Map<string, string[]>(), targetedExternal = new Set<string>();
66
76
  for (const raw of source.edges) {
67
77
  const from = parseExecutionReference(raw.from), to = parseExecutionReference(raw.to);
68
78
  const fromKey = executionReferenceKey(from), toKey = executionReferenceKey(to);
69
- if (!nodes.has(fromKey) || !nodes.has(toKey)) return unavailable("corrupt");
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
+ }
70
84
  if (!RELATIONS.includes(raw.relation) || !STRENGTHS.includes(raw.strength) ||
71
85
  (raw.relation === "declared-external" && raw.strength !== "declared")) return unavailable("corrupt");
72
86
  const edge = { from, to, relation: raw.relation, strength: raw.strength }, key = JSON.stringify(edge);
@@ -76,6 +90,7 @@ export function readExecutionLineage(source: ExecutionLineageSource, query: Line
76
90
  const neighbors = adjacent.get(a) ?? []; neighbors.push(b); adjacent.set(a, neighbors);
77
91
  }
78
92
  }
93
+ if ([...externalKeys].some(key => !targetedExternal.has(key))) return unavailable("corrupt");
79
94
  if (size > LINEAGE_LIMITS.sourceBytes) return unavailable("unsupported");
80
95
  const seen = new Set([rootKey]), queue = [rootKey];
81
96
  for (let i = 0; i < queue.length; i++) for (const key of adjacent.get(queue[i]!) ?? []) {
@@ -83,7 +98,7 @@ export function readExecutionLineage(source: ExecutionLineageSource, query: Line
83
98
  }
84
99
  const visibleNodes = queue.map(key => nodes.get(key)!);
85
100
  const visibleEdges = edges.filter(edge => seen.has(executionReferenceKey(edge.from)) && seen.has(executionReferenceKey(edge.to)));
86
- const binding = hash([source.id, source.revision, source.scope, root, nodeLimit, edgeLimit, byteLimit, visibleNodes, visibleEdges]);
101
+ const binding = hash([source.id, source.revision, source.scope, root, nodeLimit, edgeLimit, byteLimit, admittedTargets, visibleNodes, visibleEdges]);
87
102
  const sign = (n: number, e: number): string => createHmac("sha256", source.cursorKey).update(JSON.stringify([binding, n, e])).digest("hex");
88
103
  let n = 0, e = 0;
89
104
  if (query.cursor !== undefined) {
@@ -118,3 +133,32 @@ export function readExecutionLineage(source: ExecutionLineageSource, query: Line
118
133
  return page(n, e);
119
134
  } catch { return unavailable("corrupt"); }
120
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
+ }