@staix/agent-hub 0.37.0 → 0.39.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 (164) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/guidance-probes.md +365 -0
  15. package/docs/design/task-board.md +151 -5
  16. package/docs/dogfood.md +22 -7
  17. package/docs/events.md +3 -3
  18. package/docs/memory.md +5 -5
  19. package/docs/operations.md +189 -32
  20. package/docs/profiles.md +101 -9
  21. package/docs/quickstart.md +38 -4
  22. package/docs/research.md +6 -3
  23. package/docs/roles.md +52 -0
  24. package/docs/sdlc.md +187 -1
  25. package/docs/security.md +56 -13
  26. package/docs/text-projection.md +1 -0
  27. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  29. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  30. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  31. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  32. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  33. package/docs/verified.json +48 -25
  34. package/package.json +3 -3
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +1989 -474
  37. package/plugins/agent-hub/server.js +2056 -512
  38. package/src/adapters/acp-model-policy.ts +1 -1
  39. package/src/adapters/acp-session-model.ts +35 -0
  40. package/src/adapters/acp.ts +14 -0
  41. package/src/adapters/agy/definition.ts +1 -1
  42. package/src/adapters/agy/hooks.ts +7 -0
  43. package/src/adapters/claude-channel.ts +3 -2
  44. package/src/adapters/claude-implementer.ts +8 -0
  45. package/src/adapters/claude-print-child.ts +26 -2
  46. package/src/adapters/claude-print.ts +4 -0
  47. package/src/adapters/codex-appserver.ts +90 -16
  48. package/src/adapters/codex-review-isolation.ts +2 -0
  49. package/src/adapters/compat.ts +4 -4
  50. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  51. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  52. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  53. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  55. package/src/adapters/definitions/native-quota.ts +122 -0
  56. package/src/adapters/definitions/native-recovery.ts +3 -0
  57. package/src/adapters/definitions/qwen.ts +1 -1
  58. package/src/adapters/kimi-review.ts +23 -0
  59. package/src/adapters/kimi-wire-usage.ts +39 -16
  60. package/src/adapters/local-probe.ts +65 -6
  61. package/src/adapters/local-worker.ts +6 -3
  62. package/src/adapters/pi-state-model.ts +12 -0
  63. package/src/adapters/pi.ts +22 -0
  64. package/src/adapters/print-result-model.ts +24 -0
  65. package/src/adapters/registry-types.ts +10 -1
  66. package/src/adapters/registry.ts +19 -2
  67. package/src/adapters/reviewer-print.ts +130 -15
  68. package/src/adapters/role-eligibility.ts +99 -0
  69. package/src/adapters/same-directory.ts +16 -0
  70. package/src/cli/agy-mcp.ts +18 -7
  71. package/src/cli/console-state.ts +3 -1
  72. package/src/cli/free-text.ts +20 -0
  73. package/src/cli/handoff-args.ts +1 -1
  74. package/src/cli/help.ts +61 -6
  75. package/src/cli/identity.ts +10 -4
  76. package/src/cli/init-prompt.ts +31 -2
  77. package/src/cli/init-roles.ts +156 -0
  78. package/src/cli/init-settings.ts +24 -2
  79. package/src/cli/init.ts +141 -17
  80. package/src/cli/main.ts +216 -56
  81. package/src/cli/model.ts +1 -1
  82. package/src/cli/output.ts +64 -5
  83. package/src/cli/preview.ts +1 -1
  84. package/src/cli/recovery-launch.ts +114 -0
  85. package/src/cli/recovery-package.ts +14 -7
  86. package/src/cli/recovery-version-preflight.ts +104 -0
  87. package/src/cli/role-doctor.ts +39 -0
  88. package/src/cli/sdlc-output.ts +66 -1
  89. package/src/cli/study-output.ts +54 -0
  90. package/src/cli/study.ts +14 -1
  91. package/src/cli/terminal-recovery.ts +14 -0
  92. package/src/cli/upgrade-presentation.ts +4 -0
  93. package/src/cli/upgrade-restore-state.ts +12 -3
  94. package/src/cli/upgrade-runtime.ts +41 -3
  95. package/src/cli/upgrade.ts +8 -4
  96. package/src/hub/advisor-survey.ts +139 -0
  97. package/src/hub/audit-source.ts +66 -0
  98. package/src/hub/board.ts +479 -14
  99. package/src/hub/budget.ts +54 -4
  100. package/src/hub/bus.ts +2 -2
  101. package/src/hub/conductor.ts +14 -8
  102. package/src/hub/config-apply.ts +2 -1
  103. package/src/hub/config-edit-host.ts +77 -5
  104. package/src/hub/considered-findings.ts +47 -0
  105. package/src/hub/control-client.ts +1 -1
  106. package/src/hub/daemon.ts +373 -66
  107. package/src/hub/deliverable-files.ts +17 -1
  108. package/src/hub/dogfood-profile.ts +3 -2
  109. package/src/hub/envelope.ts +6 -1
  110. package/src/hub/events.ts +23 -2
  111. package/src/hub/folder-trigger.ts +11 -4
  112. package/src/hub/guidance-probe-store.ts +345 -14
  113. package/src/hub/guidance-probes.ts +338 -4
  114. package/src/hub/hub-tools.ts +88 -16
  115. package/src/hub/kimi-usage.ts +34 -2
  116. package/src/hub/lifecycle-schema.ts +3 -3
  117. package/src/hub/manager.ts +24 -1
  118. package/src/hub/memory-profile.ts +9 -1
  119. package/src/hub/memory-sync-state.ts +1 -0
  120. package/src/hub/model-overrides.ts +2 -1
  121. package/src/hub/no-writes.ts +2 -0
  122. package/src/hub/operational-authority.ts +8 -2
  123. package/src/hub/operational-view.ts +5 -1
  124. package/src/hub/peers.ts +2 -0
  125. package/src/hub/person-command.ts +25 -0
  126. package/src/hub/plan-conformance.ts +20 -2
  127. package/src/hub/quota-account.ts +34 -0
  128. package/src/hub/recovery-policy.ts +18 -4
  129. package/src/hub/research-evidence.ts +51 -3
  130. package/src/hub/research.ts +77 -13
  131. package/src/hub/restart.ts +14 -0
  132. package/src/hub/review-budget.ts +88 -0
  133. package/src/hub/review-findings.ts +93 -12
  134. package/src/hub/reviewer-pool-config.ts +6 -2
  135. package/src/hub/reviewer-pool.ts +39 -6
  136. package/src/hub/routing.ts +7 -3
  137. package/src/hub/sdlc-merge.ts +1 -1
  138. package/src/hub/sdlc-queue.ts +14 -4
  139. package/src/hub/sdlc-release.ts +1 -1
  140. package/src/hub/sdlc.ts +10 -6
  141. package/src/hub/security-audit.ts +178 -0
  142. package/src/hub/security-pass.ts +115 -0
  143. package/src/hub/settings.ts +11 -5
  144. package/src/hub/source-read.ts +80 -2
  145. package/src/hub/sources.ts +57 -9
  146. package/src/hub/startup-event-seeds.ts +5 -3
  147. package/src/hub/startup-timing.ts +1 -0
  148. package/src/hub/supervision.ts +3 -2
  149. package/src/hub/synthesis-readiness.ts +279 -0
  150. package/src/hub/tasks.ts +1131 -72
  151. package/src/hub/text-projection.ts +11 -1
  152. package/src/local/probe-types.ts +2 -0
  153. package/src/local/probe-workspace.ts +191 -2
  154. package/src/memory/capture.ts +2 -1
  155. package/src/ui/guidance-panel.ts +34 -2
  156. package/src/ui/guidance-view.ts +33 -0
  157. package/src/ui/index.html +3 -0
  158. package/src/ui/office-model.ts +11 -3
  159. package/src/ui/office-space.ts +50 -30
  160. package/src/ui/plugin.ts +31 -14
  161. package/templates/AGENTS.block.md +14 -14
  162. package/templates/profiles/general.json +1 -1
  163. package/templates/profiles/research.json +1 -1
  164. package/templates/profiles/writing.json +1 -1
@@ -5,6 +5,8 @@ import { parseEventLine, type StampedEvent } from "./events.ts";
5
5
  const STARTUP_EVENT_BUFFER_BYTES = 64 * 1024;
6
6
  export interface StartupEventSeeds {
7
7
  events: StampedEvent[];
8
+ /** False if any nonblank record was malformed or the journal ended in a partial row. */
9
+ complete: boolean;
8
10
  nativeStopsSeen: Set<string>;
9
11
  claudeNativeUsageSeen: Set<string>;
10
12
  readPasses: number;
@@ -13,7 +15,7 @@ export interface StartupEventSeeds {
13
15
 
14
16
  /** One streaming pass, retaining every accepted row and every historical dedupe key. */
15
17
  export function readStartupEventSeeds(file: string, options: { bufferBytes?: number } = {}): StartupEventSeeds {
16
- const seeds: StartupEventSeeds = { events: [], nativeStopsSeen: new Set(), claudeNativeUsageSeen: new Set(), readPasses: 0, readBytes: 0 };
18
+ const seeds: StartupEventSeeds = { events: [], complete: true, nativeStopsSeen: new Set(), claudeNativeUsageSeen: new Set(), readPasses: 0, readBytes: 0 };
17
19
  if (!existsSync(file)) return seeds;
18
20
  // Host-only chunk-boundary test seam, never a line, history or total-byte ceiling.
19
21
  const bufferBytes = options.bufferBytes ?? STARTUP_EVENT_BUFFER_BYTES;
@@ -22,7 +24,7 @@ export function readStartupEventSeeds(file: string, options: { bufferBytes?: num
22
24
  let parts: string[] = [];
23
25
  const accept = (line: string) => {
24
26
  const event = parseEventLine(line);
25
- if (event === undefined) return;
27
+ if (event === undefined) { if (line.trim()) seeds.complete = false; return; }
26
28
  seeds.events.push(event);
27
29
  // Keep the same predicates as the former three readEvents consumers, including legacy malformed IDs.
28
30
  if (event.type === "native_turn_end" && event.id) seeds.nativeStopsSeen.add(event.id);
@@ -45,7 +47,7 @@ export function readStartupEventSeeds(file: string, options: { bufferBytes?: num
45
47
  }
46
48
  consume(decoder.end());
47
49
  // readEvents also accepts a complete final JSON record without a newline.
48
- if (parts.length) accept(parts.join(""));
50
+ if (parts.length) { seeds.complete = false; accept(parts.join("")); }
49
51
  return seeds;
50
52
  } finally { closeSync(fd); }
51
53
  }
@@ -1,6 +1,7 @@
1
1
  /** Closed labels only: startup diagnostics must never carry paths, task text or errors. */
2
2
  export const STARTUP_PHASES = [
3
3
  "schema", "source", "configuration", "control", "recovery", "journal", "bus", "memory", "model_runtime", "board",
4
+ "task_checks", "task_ports", "task_board", "task_recovery",
4
5
  "task_runtime", "native_stop_seed", "budget", "usage_seed", "usage_rollup", "token_runtime", "token_seed",
5
6
  "services", "transcript_usage_seed", "ready", "post_ready",
6
7
  ] as const;
@@ -1,3 +1,4 @@
1
+ import { queueResolveCommand } from "./person-command.ts";
1
2
  import { isClosedTaskState, type HistoryEntry, type Task, type TaskMoveReason, type TaskStall } from "./board.ts";
2
3
  import { sanitize, type Kind, type Priority } from "./envelope.ts";
3
4
 
@@ -139,11 +140,11 @@ export class SupervisionFeed {
139
140
  return sent;
140
141
  }
141
142
 
142
- needsReview(peer: string, deliveryId: string): boolean {
143
+ needsReview(peer: string, deliveryId: string, command: string | (() => string) = () => queueResolveCommand({ id: deliveryId, peer })): boolean { // a thunk is built only when the notice is sent, not on every tick
143
144
  const conductor = this.recipient();
144
145
  const key = `${conductor}:${peer}:${deliveryId}`;
145
146
  if (!conductor || this.holds.has(key)) return false;
146
- const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; ask the person to resolve it with ahub queue resolve`, "important");
147
+ const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; give the person this command exactly as printed: ${typeof command === "string" ? command : command()}`, "important");
147
148
  if (sent) this.holds.add(key);
148
149
  return sent;
149
150
  }
@@ -0,0 +1,279 @@
1
+ import { createHash } from "node:crypto";
2
+ import { types } from "node:util";
3
+ import { citationKeys } from "./citations.ts";
4
+ import { evidenceLinkCanonical, parseEvidenceLink, type EvidenceLinkV1 } from "./research-evidence.ts";
5
+
6
+ export const SYNTHESIS_LIMITS = Object.freeze({ manifestBytes: 64 * 1024, claims: 50, links: 128, citationKeyChars: 128 });
7
+ export interface SynthesisInventoryBinding { revision: number; sha256: string }
8
+ export interface SynthesisContradictionHistory { ids: readonly string[]; complete: boolean; members?: readonly string[]; binding?: SynthesisInventoryBinding }
9
+ export interface SynthesisManifestClaim {
10
+ claimId: string;
11
+ claimRevision: string;
12
+ inventory: SynthesisInventoryBinding;
13
+ evidence: { id: string; revision: number; citationKey: string }[];
14
+ }
15
+ export interface SynthesisManifestV1 {
16
+ schemaVersion: 1;
17
+ taskId: number;
18
+ taskCreated: number;
19
+ deliverable: { id: string; sha256: string };
20
+ bibliography: { id: string; sha256: string };
21
+ claims: SynthesisManifestClaim[];
22
+ }
23
+ /** Withdrawal remains the host's evidence schema; this projection also accepts ordinary active link rows. */
24
+ export type SynthesisInventoryLink = EvidenceLinkV1 | { link: EvidenceLinkV1; status: "active" | "withdrawn" };
25
+ export interface SynthesisArtifactSnapshot {
26
+ id: string;
27
+ sha256?: string;
28
+ state: "unchanged" | "changed" | "missing" | "unknown";
29
+ /** Guarded complete Markdown/BibTeX text, never included in a readiness result. */
30
+ text?: string;
31
+ }
32
+ export interface SynthesisCurrentClaim {
33
+ claimId: string;
34
+ claimRevision: string;
35
+ inventory?: { links: readonly SynthesisInventoryLink[]; complete: boolean };
36
+ contradictionHistory?: SynthesisContradictionHistory;
37
+ resolutions?: readonly { id: string; revision: number; status: "resolved" | "stale" | "unavailable" | "private" | "withdrawn" }[];
38
+ /** Host-observed person authority, never a manifest field or a model's relation label. */
39
+ judgment?: { present: boolean; verdict?: "supported" | "unsupported" | "unclear"; manifestSha256?: string; disposition?: "resolved" | "qualified" };
40
+ }
41
+ /** Host-screened call-scoped observations only; never deserialize this interface from a tool caller. */
42
+ export interface SynthesisCurrent {
43
+ taskId: number;
44
+ taskCreated: number;
45
+ private?: boolean;
46
+ deliverable?: SynthesisArtifactSnapshot;
47
+ bibliography?: SynthesisArtifactSnapshot;
48
+ claims?: readonly SynthesisCurrentClaim[];
49
+ }
50
+ export type SynthesisNext = "refresh_manifest" | "provide_artifact" | "repair_citations" | "record_evidence" | "resolve_locator" | "record_person_judgment" | "resolve_contradiction" | "read_complete_inventory" | "complete_manifest_claims";
51
+ export interface SynthesisClaimReadiness {
52
+ claimId: string;
53
+ claimRevision: string;
54
+ claim: "current" | "stale" | "unknown";
55
+ inventory: "current" | "stale" | "unknown";
56
+ citationKey: "resolved" | "missing" | "unknown";
57
+ evidenceLink: "present" | "missing" | "stale" | "unknown";
58
+ locator: "resolved" | "stale" | "unavailable" | "unknown";
59
+ /** Fresh source/projection provenance for every active inventory row, including unselected counterevidence. */
60
+ provenance: "resolved" | "stale" | "unavailable" | "unknown";
61
+ judgment: "present" | "missing" | "unknown";
62
+ personVerdict: "supported" | "unsupported" | "unclear" | "unknown";
63
+ contradictionHistory: "complete" | "unknown";
64
+ contradiction: "none" | "open" | "withdrawn" | "resolved" | "qualified" | "unknown";
65
+ selected: number;
66
+ next: SynthesisNext[];
67
+ }
68
+ export type SynthesisReadiness = { taskId: number; status: "private" } | {
69
+ taskId: number;
70
+ status: "ready" | "not_ready" | "stale" | "unknown";
71
+ /** Structural/provenance readiness only, never entailment or fact certification. */
72
+ scope: "structural_provenance";
73
+ manifestSha256: string;
74
+ binding: "current" | "stale" | "unknown";
75
+ /** Coverage of the full currently declared task list only, never undeclared textual/semantic claims. */
76
+ claimCoverage: "complete" | "partial" | "unknown";
77
+ deliverable: SynthesisArtifactSnapshot["state"];
78
+ bibliography: SynthesisArtifactSnapshot["state"];
79
+ citations: { state: "resolved" | "missing" | "unknown"; cited?: number; missing?: number };
80
+ claims: SynthesisClaimReadiness[];
81
+ next: SynthesisNext[];
82
+ };
83
+
84
+ const HASH = /^[a-f0-9]{64}$/, REVISION = /^[a-f0-9]{16}$/, LINK = /^ev:[a-f0-9]{32}$/, DELIVERABLE = /^d-[a-f0-9]{12}$/;
85
+ const sha = (text: string) => createHash("sha256").update(text).digest("hex");
86
+ const invalid = (): never => { throw new Error("invalid synthesis manifest; use bounded task, artifact, claim and evidence bindings"); };
87
+ function object(value: unknown, fields: readonly string[]): Record<string, unknown> {
88
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
89
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return invalid();
90
+ const descriptors = Object.getOwnPropertyDescriptors(value);
91
+ if (Object.entries(descriptors).some(([key, field]) => !fields.includes(key) || !Object.hasOwn(field, "value") || !field.enumerable)) return invalid();
92
+ return value as Record<string, unknown>;
93
+ }
94
+ function array(value: unknown, max: number): unknown[] {
95
+ if (!Array.isArray(value) || types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > max || Object.getOwnPropertySymbols(value).length) return invalid();
96
+ const descriptors = Object.getOwnPropertyDescriptors(value);
97
+ if (Object.keys(descriptors).length !== value.length + 1) return invalid();
98
+ for (let i = 0; i < value.length; i++) if (!descriptors[i] || !Object.hasOwn(descriptors[i]!, "value") || !descriptors[i]!.enumerable) return invalid();
99
+ return value;
100
+ }
101
+ const integer = (value: unknown, min = 1): number => typeof value === "number" && Number.isSafeInteger(value) && value >= min ? value : invalid();
102
+ const token = (value: unknown, pattern: RegExp): string => typeof value === "string" && pattern.test(value) ? value : invalid();
103
+ function claimIdentity(value: unknown, taskId: number, created: number): string {
104
+ const id = token(value, /^claim:[1-9][0-9]{0,15}:(?:0|[1-9][0-9]{0,15}):[1-9][0-9]?$/);
105
+ const slot = Number(id.split(":").at(-1));
106
+ return slot <= SYNTHESIS_LIMITS.claims && id === `claim:${taskId}:${created}:${slot}` ? id : invalid();
107
+ }
108
+ function artifact(value: unknown): SynthesisManifestV1["deliverable"] {
109
+ const row = object(value, ["id", "sha256"]);
110
+ return { id: token(row.id, DELIVERABLE), sha256: token(row.sha256, HASH) };
111
+ }
112
+
113
+ export function parseSynthesisManifest(input: unknown): SynthesisManifestV1 {
114
+ const row = object(input, ["schemaVersion", "taskId", "taskCreated", "deliverable", "bibliography", "claims"]);
115
+ if (row.schemaVersion !== 1) return invalid();
116
+ const taskId = integer(row.taskId), taskCreated = integer(row.taskCreated, 0), seen = new Set<string>(), selected = new Set<string>();
117
+ const claims = array(row.claims, SYNTHESIS_LIMITS.claims).map(value => {
118
+ const claim = object(value, ["claimId", "claimRevision", "inventory", "evidence"]), id = claimIdentity(claim.claimId, taskId, taskCreated);
119
+ if (seen.has(id)) return invalid(); seen.add(id);
120
+ const inventory = object(claim.inventory, ["revision", "sha256"]);
121
+ const evidence = array(claim.evidence, SYNTHESIS_LIMITS.links).map(value => {
122
+ const ref = object(value, ["id", "revision", "citationKey"]), id = token(ref.id, LINK);
123
+ if (selected.has(id) || selected.size >= SYNTHESIS_LIMITS.links) return invalid(); selected.add(id);
124
+ const citationKey = token(ref.citationKey, /^[A-Za-z0-9_:./-]+$/);
125
+ if (citationKey.length > SYNTHESIS_LIMITS.citationKeyChars) return invalid();
126
+ return { id, revision: integer(ref.revision), citationKey };
127
+ });
128
+ return { claimId: id, claimRevision: token(claim.claimRevision, REVISION), inventory: { revision: integer(inventory.revision, 0), sha256: token(inventory.sha256, HASH) }, evidence };
129
+ });
130
+ if (!claims.length) return invalid();
131
+ const parsed: SynthesisManifestV1 = { schemaVersion: 1, taskId, taskCreated, deliverable: artifact(row.deliverable), bibliography: artifact(row.bibliography), claims };
132
+ if (Buffer.byteLength(JSON.stringify(parsed)) > SYNTHESIS_LIMITS.manifestBytes) return invalid();
133
+ return parsed;
134
+ }
135
+ export function synthesisManifestCanonical(input: unknown): string { return JSON.stringify(parseSynthesisManifest(input)); }
136
+ export function synthesisManifestHash(input: unknown): string { return sha(synthesisManifestCanonical(input)); }
137
+
138
+ function inventoryRows(latest: readonly SynthesisInventoryLink[], complete: boolean): { link: EvidenceLinkV1; status: "active" | "withdrawn" }[] | undefined {
139
+ try {
140
+ if (complete !== true) return undefined;
141
+ const seen = new Set<string>(); let identity: string | undefined;
142
+ return array(latest, SYNTHESIS_LIMITS.links).map(value => {
143
+ const wrapped = value && typeof value === "object" && !types.isProxy(value) && Object.hasOwn(value, "link");
144
+ const row = wrapped ? object(value, ["link", "status"]) : undefined;
145
+ if (row && row.status !== "active" && row.status !== "withdrawn") return invalid();
146
+ const link = parseEvidenceLink(row ? row.link : value), incarnation = link.claimId.split(":");
147
+ claimIdentity(link.claimId, link.taskId, Number(incarnation[2]));
148
+ const key = `${link.taskId}|${link.claimId}|${link.claimRevision}`;
149
+ if (seen.has(link.id) || identity !== undefined && identity !== key) return invalid();
150
+ seen.add(link.id); identity = key;
151
+ return { link, status: link.status === "withdrawn" || row?.status === "withdrawn" ? "withdrawn" as const : "active" as const };
152
+ });
153
+ } catch { return undefined; }
154
+ }
155
+ /** Complete latest inventory only, including unselected counterevidence and explicit host withdrawal states. */
156
+ export function inventoryBinding(latest: readonly SynthesisInventoryLink[], complete: boolean, history?: SynthesisContradictionHistory): SynthesisInventoryBinding | undefined {
157
+ const rows = inventoryRows(latest, complete); if (!rows) return undefined;
158
+ let revision = 0;
159
+ for (const row of rows) { revision += row.link.revision; if (!Number.isSafeInteger(revision)) return undefined; }
160
+ const canonical = rows.sort((a, b) => (a.link.id < b.link.id ? -1 : a.link.id > b.link.id ? 1 : a.link.revision - b.link.revision))
161
+ .map(row => ({ link: evidenceLinkCanonical(row.link), status: row.status }));
162
+ if (history) {
163
+ if (history.complete !== true) return undefined;
164
+ if (history.binding) {
165
+ if (!Number.isSafeInteger(history.binding.revision) || history.binding.revision < revision || !HASH.test(history.binding.sha256)) return undefined;
166
+ return { revision: history.binding.revision, sha256: sha(JSON.stringify({ latest: canonical, history: history.binding })) };
167
+ }
168
+ }
169
+ return { revision, sha256: sha(JSON.stringify(canonical)) };
170
+ }
171
+
172
+ function artifactState(expected: SynthesisManifestV1["deliverable"], current: SynthesisArtifactSnapshot | undefined): SynthesisArtifactSnapshot["state"] {
173
+ if (!current) return "unknown";
174
+ if (current.state === "missing") return "missing";
175
+ if (current.id !== expected.id || current.state === "changed" || current.sha256 !== undefined && current.sha256 !== expected.sha256) return "changed";
176
+ if (current.state !== "unchanged" || current.sha256 !== expected.sha256) return "unknown";
177
+ if (current.text !== undefined && sha(current.text) !== expected.sha256) return "changed";
178
+ return "unchanged";
179
+ }
180
+ const unique = <T>(items: T[]): T[] => [...new Set(items)];
181
+ function mergeResolution(prior: SynthesisClaimReadiness["locator"], status: string | undefined): SynthesisClaimReadiness["locator"] {
182
+ if (prior === "stale" || status === "stale" || status === "withdrawn") return "stale";
183
+ if (prior === "unavailable" || status === "unavailable") return "unavailable";
184
+ return prior === "unknown" || status !== "resolved" ? "unknown" : "resolved";
185
+ }
186
+ function declaredClaims(current: SynthesisCurrent): readonly SynthesisCurrentClaim[] | undefined {
187
+ try {
188
+ const rows = array(current.claims, SYNTHESIS_LIMITS.claims), seen = new Set<string>();
189
+ let revision: string | undefined;
190
+ for (const value of rows) {
191
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)) return undefined;
192
+ const row = value as SynthesisCurrentClaim;
193
+ const id = claimIdentity(row.claimId, current.taskId, current.taskCreated), currentRevision = token(row.claimRevision, REVISION);
194
+ if (seen.has(id) || revision !== undefined && currentRevision !== revision) return undefined;
195
+ seen.add(id); revision = currentRevision;
196
+ }
197
+ return rows as SynthesisCurrentClaim[];
198
+ } catch { return undefined; }
199
+ }
200
+
201
+ /** Pure structural/provenance check over current HOST observations; no fact, entailment or model certification. */
202
+ export function checkSynthesis(input: unknown, current: SynthesisCurrent): SynthesisReadiness {
203
+ const manifest = parseSynthesisManifest(input);
204
+ if (current.private === true) return { taskId: manifest.taskId, status: "private" };
205
+ const manifestSha256 = synthesisManifestHash(manifest), sameTask = current.taskId === manifest.taskId && current.taskCreated === manifest.taskCreated;
206
+ const declared = sameTask ? declaredClaims(current) : undefined, safeClaims = declared ?? [];
207
+ if (safeClaims.some(claim => Array.isArray(claim.resolutions) && claim.resolutions.some(row => row?.status === "private"))) return { taskId: manifest.taskId, status: "private" };
208
+ const deliverable = artifactState(manifest.deliverable, current.deliverable), bibliography = artifactState(manifest.bibliography, current.bibliography);
209
+ let citations: Extract<SynthesisReadiness, { scope: string }>["citations"] = { state: "unknown" }, cited = new Set<string>(), missing = new Set<string>();
210
+ if (deliverable === "unchanged" && bibliography === "unchanged" && typeof current.deliverable?.text === "string" && typeof current.bibliography?.text === "string") {
211
+ try { const keys = citationKeys(current.deliverable.text, current.bibliography.text); cited = new Set(keys.cited); missing = new Set(keys.missing); citations = { state: keys.missing.length ? "missing" : "resolved", cited: keys.cited.length, missing: keys.missing.length }; }
212
+ catch { /* Bounded/unknown text never establishes citation completeness. */ }
213
+ }
214
+ const manifestClaims = new Set(manifest.claims.map(claim => claim.claimId));
215
+ const claimCoverage = declared === undefined ? "unknown" : declared.length === manifestClaims.size && declared.every(claim => manifestClaims.has(claim.claimId)) ? "complete" : "partial";
216
+ const claims: SynthesisClaimReadiness[] = manifest.claims.map(claim => {
217
+ const observed = sameTask ? safeClaims.find(row => row.claimId === claim.claimId) : undefined;
218
+ const identity = !sameTask || observed && observed.claimRevision !== claim.claimRevision ? "stale" : observed ? "current" : "unknown";
219
+ const rows = observed?.inventory && identity === "current" ? inventoryRows(observed.inventory.links, observed.inventory.complete) : undefined;
220
+ const matching = rows?.every(row => row.link.claimId === claim.claimId && row.link.claimRevision === claim.claimRevision && row.link.taskId === manifest.taskId);
221
+ const binding = observed?.inventory && matching ? inventoryBinding(observed.inventory.links, observed.inventory.complete, observed.contradictionHistory) : undefined;
222
+ const inventory = identity === "stale" ? "stale" : !binding ? "unknown" : binding.revision === claim.inventory.revision && binding.sha256 === claim.inventory.sha256 ? "current" : "stale";
223
+ let evidenceLink: SynthesisClaimReadiness["evidenceLink"] = rows && matching ? "present" : "unknown";
224
+ let locator: SynthesisClaimReadiness["locator"] = "resolved";
225
+ if (!claim.evidence.length) { evidenceLink = "missing"; locator = "unknown"; }
226
+ const resolutions = observed?.resolutions;
227
+ const completeResolutions = Array.isArray(resolutions) && resolutions.length <= SYNTHESIS_LIMITS.links && new Set(resolutions.map(row => row.id)).size === resolutions.length ? resolutions : [];
228
+ let provenance: SynthesisClaimReadiness["provenance"] = rows && matching ? "resolved" : "unknown";
229
+ for (const row of rows ?? []) if (row.status === "active") {
230
+ const resolution = completeResolutions.find(item => item.id === row.link.id && item.revision === row.link.revision);
231
+ provenance = mergeResolution(provenance, resolution?.status);
232
+ }
233
+ for (const ref of claim.evidence) {
234
+ const row = rows?.find(row => row.link.id === ref.id);
235
+ if (rows && matching && !row) evidenceLink = evidenceLink === "stale" ? "stale" : "missing";
236
+ else if (row && (row.link.revision !== ref.revision || row.status === "withdrawn")) evidenceLink = "stale";
237
+ const resolution = completeResolutions.find(row => row.id === ref.id && row.revision === ref.revision);
238
+ locator = mergeResolution(locator, resolution?.status);
239
+ }
240
+ const citationKey = citations.state === "unknown" ? "unknown" : claim.evidence.length && claim.evidence.every(ref => cited.has(ref.citationKey) && !missing.has(ref.citationKey)) ? "resolved" : "missing";
241
+ const judgment = observed?.judgment?.present === true ? "present" : observed?.judgment?.present === false ? "missing" : "unknown";
242
+ const personVerdict = judgment === "present" && ["supported", "unsupported", "unclear"].includes(observed?.judgment?.verdict ?? "") ? observed!.judgment!.verdict! : "unknown";
243
+ const ever = new Set((rows ?? []).filter(row => row.link.relation === "contradicts").map(row => row.link.id));
244
+ let contradictionHistory: SynthesisClaimReadiness["contradictionHistory"] = rows && matching && rows.every(row => row.link.revision === 1) ? "complete" : "unknown";
245
+ if (observed?.contradictionHistory) {
246
+ try {
247
+ const history = observed.contradictionHistory, ids = array(history.ids, SYNTHESIS_LIMITS.links).map(id => token(id, LINK));
248
+ const members = history.members === undefined ? (rows ?? []).map(row => row.link.id) : array(history.members, SYNTHESIS_LIMITS.links).map(id => token(id, LINK));
249
+ if (history.complete === true && new Set(ids).size === ids.length && new Set(members).size === members.length
250
+ && ids.every(id => members.includes(id)) && rows?.every(row => members.includes(row.link.id)) && [...ever].every(id => ids.includes(id))) {
251
+ for (const id of ids) ever.add(id); contradictionHistory = rows && matching ? "complete" : "unknown";
252
+ } else contradictionHistory = "unknown";
253
+ } catch { contradictionHistory = "unknown"; }
254
+ }
255
+ let contradiction: SynthesisClaimReadiness["contradiction"] = contradictionHistory !== "complete" ? "unknown"
256
+ : rows!.some(row => row.status === "active" && row.link.relation === "contradicts") ? "open"
257
+ : ever.size ? "withdrawn" : "none";
258
+ if ((contradiction === "open" || contradiction === "withdrawn") && identity === "current" && inventory === "current" && evidenceLink === "present" && locator === "resolved" && provenance === "resolved"
259
+ && deliverable === "unchanged" && bibliography === "unchanged"
260
+ && judgment === "present" && observed?.judgment?.manifestSha256 === manifestSha256
261
+ && (observed.judgment.disposition === "resolved" || observed.judgment.disposition === "qualified")) contradiction = observed.judgment.disposition;
262
+ const next: SynthesisNext[] = [];
263
+ if (identity === "stale" || inventory === "stale" || evidenceLink === "stale") next.push("refresh_manifest");
264
+ if (inventory === "unknown") next.push("read_complete_inventory");
265
+ if (contradictionHistory === "unknown") next.push("read_complete_inventory");
266
+ if (citationKey !== "resolved") next.push("repair_citations");
267
+ if (evidenceLink !== "present") next.push("record_evidence");
268
+ if (locator !== "resolved" || provenance !== "resolved") next.push("resolve_locator");
269
+ if (judgment !== "present") next.push("record_person_judgment");
270
+ if (contradiction === "open" || contradiction === "withdrawn" || contradiction === "unknown") next.push("resolve_contradiction");
271
+ return { claimId: claim.claimId, claimRevision: claim.claimRevision, claim: identity, inventory, citationKey, evidenceLink, locator, provenance, judgment, personVerdict, contradictionHistory, contradiction, selected: claim.evidence.length, next: unique(next) };
272
+ });
273
+ const stale = !sameTask || deliverable === "changed" || bibliography === "changed" || claims.some(row => row.claim === "stale" || row.inventory === "stale" || row.evidenceLink === "stale" || row.locator === "stale" || row.provenance === "stale");
274
+ const unknown = claimCoverage === "unknown" || deliverable === "unknown" || bibliography === "unknown" || citations.state === "unknown" || claims.some(row => row.claim === "unknown" || row.inventory === "unknown" || row.evidenceLink === "unknown" || row.locator === "unknown" || row.locator === "unavailable" || row.provenance === "unknown" || row.provenance === "unavailable" || row.judgment === "unknown" || row.contradiction === "unknown");
275
+ const bindingUnknown = claimCoverage === "unknown" || deliverable === "unknown" || bibliography === "unknown" || claims.some(row => row.claim === "unknown" || row.inventory === "unknown" || row.evidenceLink === "unknown" || row.locator === "unknown" || row.locator === "unavailable" || row.provenance === "unknown" || row.provenance === "unavailable" || row.contradictionHistory === "unknown");
276
+ const ready = !stale && !unknown && claimCoverage === "complete" && deliverable === "unchanged" && bibliography === "unchanged" && citations.state === "resolved" && claims.every(row => !row.next.length);
277
+ const next = unique<SynthesisNext>([...(!sameTask || stale ? ["refresh_manifest" as const] : []), ...(claimCoverage !== "complete" ? ["complete_manifest_claims" as const] : []), ...(deliverable !== "unchanged" || bibliography !== "unchanged" ? ["provide_artifact" as const] : []), ...(citations.state !== "resolved" ? ["repair_citations" as const] : []), ...claims.flatMap(row => row.next)]);
278
+ return { taskId: manifest.taskId, status: stale ? "stale" : ready ? "ready" : unknown ? "unknown" : "not_ready", scope: "structural_provenance", manifestSha256, binding: stale ? "stale" : bindingUnknown ? "unknown" : "current", claimCoverage, deliverable, bibliography, citations, claims, next };
279
+ }