@staix/agent-hub 0.38.0 → 0.40.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 (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.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;
@@ -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
+ }
@@ -60,7 +60,15 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
60
60
  if (!kind) return undefined;
61
61
  let activity = task.history.length - 1;
62
62
  while (activity >= 0 && (task.history[activity]?.sweep || task.history[activity]?.event === "memory reference started")) activity--;
63
- const at = task.history[activity]?.at ?? task.created;
63
+ let at = task.history[activity]?.at ?? task.created;
64
+ if (kind === "idle-owner") {
65
+ // #1454: a pending wait suspends the ladder; once it passes, the ladder restarts from `until`, not from the activity before it.
66
+ const wait = taskWait(task);
67
+ if (wait) {
68
+ if (now < wait.until) return undefined;
69
+ at = Math.max(at, wait.until);
70
+ }
71
+ }
64
72
  const threshold = kind === "ready-unassigned" ? config.ready_min ?? 60 : kind === "unaccepted-assignment" ? config.unaccepted_min : kind === "idle-owner" ? config.idle_min : config.review_min;
65
73
  if (now - at < threshold * 60_000) return undefined;
66
74
  const previous = task.history.flatMap((h) => h.sweep?.kind === kind && h.sweep.activity === activity ? [h.sweep] : []).at(-1);
@@ -68,13 +76,30 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
68
76
  return { kind, activity, step: previous ? (previous.step + 1) as 2 | 3 : 1, at: now };
69
77
  }
70
78
 
79
+ /** #1454: the longest a bounded wait may reach ahead of the moment it is recorded. */
80
+ export const TASK_WAIT_MAX_MS = 14 * 24 * 3_600_000;
81
+ /** #1454: the reason a wait carries is public text; longer text is refused, never cut. */
82
+ export const TASK_WAIT_REASON_MAX = 200;
83
+ /** History events that leave a recorded wait in force: bookkeeping that neither moves the task nor is owner activity on it. Anything else (done, decline, return, reassignment, cancel) ends it. */
84
+ const WAIT_KEEPING_EVENTS = new Set(["wait recorded", "idle sweep", "answer", "reviewer changed", "memory reference started", "ready held", "plan observed", "planner changed", "claim verdict", "invocation", "shell branch bound"]);
85
+ export interface TaskWait { until: number; at: number; by: string; owner: string }
86
+ /** The wait that is still in force on an in_progress task: the latest `wait recorded` entry, for the current owner, with no state-changing entry after it. A passed `until` still counts (the planner groom view lists it); `nextSweep` is what lets the ladder restart. */
87
+ export function taskWait(task: Pick<Task, "state" | "owner" | "history">): TaskWait | undefined {
88
+ if (task.state !== "in_progress" || !task.owner) return undefined;
89
+ const index = task.history.findLastIndex(entry => entry.wait !== undefined);
90
+ const entry = task.history[index];
91
+ if (!entry?.wait || entry.event !== "wait recorded" || entry.wait.owner !== task.owner) return undefined;
92
+ if (task.history.slice(index + 1).some(later => !WAIT_KEEPING_EVENTS.has(later.event))) return undefined;
93
+ return { until: entry.wait.until, at: entry.at, by: entry.by, owner: entry.wait.owner };
94
+ }
95
+
71
96
  /** A planned start is the earliest automatic start time; the card is eligible at that boundary. */
72
97
  export function plannedStartPending(task: Pick<Task, "plannedStart">, now: number): boolean {
73
98
  return task.plannedStart != null && (!Number.isFinite(now) || task.plannedStart > now);
74
99
  }
75
100
 
76
101
  export interface GroomingItem {
77
- kind: "text-dependency" | "overlap" | "duplicate" | "over-wip" | "stale" | "superseded" | "blocked" | "closed-issue" | "scheduled";
102
+ kind: "text-dependency" | "overlap" | "duplicate" | "over-wip" | "stale" | "superseded" | "blocked" | "closed-issue" | "scheduled" | "wait-passed";
78
103
  task: number;
79
104
  related?: number[];
80
105
  code?: string;
@@ -173,6 +198,8 @@ export function plannerGrooming(tasks: readonly Task[], options: PlannerGrooming
173
198
  if (task.state === "cancelled") continue; // Closed rows contribute supersession evidence only.
174
199
  if ((task.state === "backlog" || task.state === "proposed" && !task.owner) && options.now !== undefined && plannedStartPending(task, options.now))
175
200
  add({ kind: "scheduled", task: task.id });
201
+ // #1454: a wait that has passed is shown here, so a stale one is seen rather than silently restarting the idle ladder.
202
+ if (options.now !== undefined && taskWait(task) && taskWait(task)!.until <= options.now) add({ kind: "wait-passed", task: task.id });
176
203
  const issues = new Set<number>();
177
204
  for (const issue of [task.external?.issue, task.sdlc?.issue]) {
178
205
  if (issue === undefined) continue;
@@ -8,6 +8,7 @@ import type { PeerId } from "./envelope.ts";
8
8
  import { hubGitArgv, hubGitEnv, hubGitSync } from "./git.ts";
9
9
  import { grantablePath } from "./permission-mode.ts";
10
10
  import { realPath } from "./project.ts";
11
+ import type { DependencyPreparation } from "../pi/task-dependencies.ts";
11
12
 
12
13
  /**
13
14
  * #1115: a hub-sandboxed peer (Pi, the local worker) cannot run `git worktree add` or commit, because its profile refuses `.git` writes that
@@ -39,6 +40,9 @@ export interface TaskWorktreePort {
39
40
  available(): TaskWorktreeAvailability;
40
41
  create(input: { peer: PeerId; task: number }): TaskWorktreeResult;
41
42
  describe(peer: PeerId, task: number): Pick<TaskWorktreeEntry, "path" | "branch" | "base"> | undefined;
43
+ prepareDependencies?(input: { peer: PeerId; task: number; current: () => boolean }): Promise<void>;
44
+ preparesDependencies?(peer: PeerId): boolean;
45
+ dependencyState?(peer: PeerId, task: number): DependencyPreparation | undefined;
42
46
  commitAndPush(input: { peer: PeerId; task: number; title: string }): Promise<TaskWorktreeCommit>;
43
47
  remove(input: { peer: PeerId; task: number }): TaskWorktreeRemoval;
44
48
  }
@@ -77,10 +81,42 @@ export class TaskWorktrees implements TaskWorktreePort {
77
81
  private readonly root: string;
78
82
  private chain: Promise<unknown> = Promise.resolve();
79
83
  private cached?: { at: number; value: TaskWorktreeAvailability };
84
+ private dependencyPreparers = new Map<PeerId, (cwd: string, current: () => boolean, base: string) => Promise<DependencyPreparation>>();
85
+ private dependencyRuns = new Map<string, Promise<void>>();
86
+ private dependencyStates = new Map<string, { path: string; state: DependencyPreparation }>();
80
87
  constructor(private readonly o: TaskWorktreeOptions) { this.root = realPath(o.root); }
81
88
 
82
89
  applies = (peer: PeerId): boolean => this.o.applies(peer);
83
90
 
91
+ /** Host adapter registration only; a peer/tool cannot choose an installer or environment. */
92
+ registerDependencyPreparation(peer: PeerId, prepare: (cwd: string, current: () => boolean, base: string) => Promise<DependencyPreparation>): void {
93
+ this.dependencyPreparers.set(peer, prepare);
94
+ }
95
+ preparesDependencies = (peer: PeerId): boolean => this.dependencyPreparers.has(peer);
96
+
97
+ prepareDependencies(input: { peer: PeerId; task: number; current: () => boolean }): Promise<void> {
98
+ const { peer, task, current } = input, prepare = this.dependencyPreparers.get(peer), entry = this.describe(peer, task);
99
+ if (!prepare || !entry || !current()) return Promise.resolve();
100
+ const key = this.key(peer, task), running = this.dependencyRuns.get(key);
101
+ // A repeated accept may supersede the running request's authority. Serialize
102
+ // installs, then prepare under this caller instead of adopting its stale run.
103
+ if (running) return running.then(() => current() ? this.prepareDependencies(input) : undefined);
104
+ this.dependencyStates.delete(key);
105
+ const run = (async () => {
106
+ let state: DependencyPreparation;
107
+ try { state = await prepare(entry.path, current, entry.base); }
108
+ catch { state = { ready: false, reason: "install failed" }; }
109
+ if (current() && this.describe(peer, task)?.path === entry.path) this.dependencyStates.set(key, { path: entry.path, state });
110
+ })().finally(() => { if (this.dependencyRuns.get(key) === run) this.dependencyRuns.delete(key); });
111
+ this.dependencyRuns.set(key, run);
112
+ return run;
113
+ }
114
+
115
+ dependencyState(peer: PeerId, task: number): DependencyPreparation | undefined {
116
+ const saved = this.dependencyStates.get(this.key(peer, task));
117
+ return saved && this.describe(peer, task)?.path === saved.path ? saved.state : undefined;
118
+ }
119
+
84
120
  /** `extra` is merged after the isolation, which strips GIT_INDEX_FILE: only the hub's own private index passes through it. */
85
121
  private git(args: string[], cwd = this.root, timeout = GIT_TIMEOUT_MS, extra: Record<string, string> = {}): Run {
86
122
  const run = hubGitSync(["-C", cwd, "-c", "gc.auto=0", "-c", "maintenance.auto=false", ...args], { encoding: "utf8", timeout, maxBuffer: 8 * 1024 * 1024, env: { ...hubGitEnv(childEnv(), { repositoryIsolation: true }), ...extra } });
@@ -304,6 +340,7 @@ export class TaskWorktrees implements TaskWorktreePort {
304
340
  */
305
341
  remove(input: { peer: PeerId; task: number }): TaskWorktreeRemoval {
306
342
  const { peer, task } = input;
343
+ this.dependencyStates.delete(this.key(peer, task));
307
344
  let records: Record<string, TaskWorktreeEntry>;
308
345
  try { records = this.readRecords(); } catch (error) { return { removed: false, branchDeleted: false, kept: (error as Error).message }; }
309
346
  const entry = records[this.key(peer, task)];