@staix/agent-hub 0.51.0 → 0.52.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 (299) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +24 -2
  4. package/docs/agent-notes/adapters.md +1 -0
  5. package/docs/agent-notes/budget.md +8 -2
  6. package/docs/agent-notes/daemon.md +13 -8
  7. package/docs/agent-notes/security-review.md +6 -5
  8. package/docs/agent-notes/tasks.md +5 -2
  9. package/docs/agent-notes/tests.md +4 -3
  10. package/docs/cooperbench.md +1 -1
  11. package/docs/design/adapters.md +4 -0
  12. package/docs/design/cli-output-inventory.md +162 -152
  13. package/docs/design/cli-output.md +4 -3
  14. package/docs/design/guidance-probes.md +1 -0
  15. package/docs/design/roadmap.md +2 -0
  16. package/docs/design/task-board.md +1 -0
  17. package/docs/dogfood.md +14 -0
  18. package/docs/events.md +4 -2
  19. package/docs/memory.md +5 -3
  20. package/docs/operations.md +210 -16
  21. package/docs/quickstart.md +12 -2
  22. package/docs/roles.md +1 -1
  23. package/docs/sdlc.md +26 -3
  24. package/docs/security.md +11 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
  26. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  27. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  28. package/docs/specs/mcp-endpoint.md +63 -0
  29. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  30. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  31. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  32. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  33. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  34. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  35. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  36. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  37. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  38. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  39. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  40. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  41. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  42. package/docs/verification/agy/README.md +17 -0
  43. package/docs/verification/agy/cli-surface.ts +68 -0
  44. package/docs/verification/agy/interactive-bridge.ts +92 -0
  45. package/docs/verification/agy/interactive-session.ts +131 -0
  46. package/docs/verification/agy/launcher-nonce.ts +215 -0
  47. package/docs/verification/agy/native-hooks.ts +210 -0
  48. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  49. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  50. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  51. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  52. package/docs/verification/agy/originals.json +25 -0
  53. package/docs/verification/agy/permission-new-functions.ts +128 -0
  54. package/docs/verification/agy/run-probe.py +108 -0
  55. package/docs/verification/agy/runtime.ts +171 -0
  56. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  57. package/docs/verification/agy/tmux-session.ts +235 -0
  58. package/docs/verified.json +82 -41
  59. package/package.json +3 -3
  60. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  61. package/plugins/agent-hub/compat.json +157 -0
  62. package/plugins/agent-hub/kimi-hook.js +621 -865
  63. package/plugins/agent-hub/server.js +17423 -32962
  64. package/src/adapters/agy/definition.ts +7 -24
  65. package/src/adapters/channel-peer.ts +3 -1
  66. package/src/adapters/claude-channel.ts +38 -257
  67. package/src/adapters/claude-implementer.ts +3 -1
  68. package/src/adapters/codex-appserver.ts +77 -15
  69. package/src/adapters/compat.ts +74 -11
  70. package/src/adapters/configured-acp.ts +23 -163
  71. package/src/adapters/configured-adapter-policy.ts +160 -0
  72. package/src/adapters/configured-pull-entry.ts +53 -0
  73. package/src/adapters/configured-pull.ts +38 -0
  74. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  75. package/src/adapters/declaration-catalog.ts +25 -0
  76. package/src/adapters/declaration-data.ts +342 -0
  77. package/src/adapters/declaration-resolution.ts +53 -0
  78. package/src/adapters/definitions/builtin-metadata.ts +61 -83
  79. package/src/adapters/definitions/jcode-launch.ts +13 -0
  80. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  81. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
  82. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  83. package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
  84. package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
  85. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  86. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  87. package/src/adapters/definitions/native-configuration.ts +18 -0
  88. package/src/adapters/definitions/native-help.ts +24 -0
  89. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  90. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  91. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  92. package/src/adapters/definitions/native-light-cli.ts +18 -0
  93. package/src/adapters/definitions/native-light-preview.ts +10 -0
  94. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  95. package/src/adapters/definitions/qwen.ts +6 -29
  96. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  97. package/src/adapters/external-declarations.ts +31 -0
  98. package/src/adapters/external-modules.ts +4 -29
  99. package/src/adapters/jcode.ts +3 -12
  100. package/src/adapters/native-capabilities.ts +18 -8
  101. package/src/adapters/native-proof-ports.ts +1 -1
  102. package/src/adapters/presets.ts +136 -0
  103. package/src/adapters/qwen-dual.ts +2 -2
  104. package/src/adapters/registry-types.ts +3 -0
  105. package/src/adapters/registry.ts +20 -81
  106. package/src/adapters/reviewer-print.ts +26 -9
  107. package/src/adapters/role-eligibility.ts +2 -1
  108. package/src/cli/accounts-import.ts +72 -0
  109. package/src/cli/agents-latest-table.ts +88 -0
  110. package/src/cli/agents-latest.ts +22 -0
  111. package/src/cli/agents-output.ts +10 -0
  112. package/src/cli/agents-presets.ts +100 -0
  113. package/src/cli/agents.ts +1 -1
  114. package/src/cli/attention.ts +3 -2
  115. package/src/cli/autonomy-homes.ts +7 -2
  116. package/src/cli/budget-renew-guidance.ts +129 -0
  117. package/src/cli/claude-homes.ts +9 -5
  118. package/src/cli/command-context.ts +3 -0
  119. package/src/cli/command-table.ts +123 -0
  120. package/src/cli/commands/accounts.ts +8 -0
  121. package/src/cli/commands/agents.ts +18 -0
  122. package/src/cli/commands/answer.ts +28 -0
  123. package/src/cli/commands/ask.ts +17 -0
  124. package/src/cli/commands/autonomy.ts +83 -0
  125. package/src/cli/commands/backlog.ts +46 -0
  126. package/src/cli/commands/bench.ts +60 -0
  127. package/src/cli/commands/board.ts +48 -0
  128. package/src/cli/commands/broker.ts +9 -0
  129. package/src/cli/commands/budget.ts +96 -0
  130. package/src/cli/commands/capabilities.ts +12 -0
  131. package/src/cli/commands/check-path.ts +55 -0
  132. package/src/cli/commands/completion.ts +8 -0
  133. package/src/cli/commands/console.ts +12 -0
  134. package/src/cli/commands/daemon.ts +8 -0
  135. package/src/cli/commands/deliverables.ts +25 -0
  136. package/src/cli/commands/doctor.ts +249 -0
  137. package/src/cli/commands/down.ts +3 -0
  138. package/src/cli/commands/export.ts +15 -0
  139. package/src/cli/commands/facts.ts +15 -0
  140. package/src/cli/commands/goal.ts +22 -0
  141. package/src/cli/commands/guidance.ts +102 -0
  142. package/src/cli/commands/help.ts +17 -0
  143. package/src/cli/commands/host.ts +45 -0
  144. package/src/cli/commands/init.ts +121 -0
  145. package/src/cli/commands/instructed.ts +19 -0
  146. package/src/cli/commands/instruction-hook.ts +15 -0
  147. package/src/cli/commands/intake.ts +24 -0
  148. package/src/cli/commands/kill.ts +15 -0
  149. package/src/cli/commands/learn.ts +23 -0
  150. package/src/cli/commands/lineage.ts +30 -0
  151. package/src/cli/commands/logs.ts +21 -0
  152. package/src/cli/commands/manager.ts +15 -0
  153. package/src/cli/commands/memory.ts +21 -0
  154. package/src/cli/commands/model.ts +25 -0
  155. package/src/cli/commands/models.ts +40 -0
  156. package/src/cli/commands/native.ts +39 -0
  157. package/src/cli/commands/pause.ts +5 -0
  158. package/src/cli/commands/peer.ts +32 -0
  159. package/src/cli/commands/permission.ts +26 -0
  160. package/src/cli/commands/permit.ts +12 -0
  161. package/src/cli/commands/pet.ts +24 -0
  162. package/src/cli/commands/projects.ts +49 -0
  163. package/src/cli/commands/queue.ts +70 -0
  164. package/src/cli/commands/recovery-run.ts +13 -0
  165. package/src/cli/commands/recovery.ts +130 -0
  166. package/src/cli/commands/release.ts +23 -0
  167. package/src/cli/commands/releases.ts +9 -0
  168. package/src/cli/commands/remember.ts +6 -0
  169. package/src/cli/commands/report.ts +27 -0
  170. package/src/cli/commands/research.ts +53 -0
  171. package/src/cli/commands/reset.ts +89 -0
  172. package/src/cli/commands/restart.ts +5 -0
  173. package/src/cli/commands/results.ts +31 -0
  174. package/src/cli/commands/resume.ts +5 -0
  175. package/src/cli/commands/review.ts +24 -0
  176. package/src/cli/commands/roadmap.ts +21 -0
  177. package/src/cli/commands/role.ts +34 -0
  178. package/src/cli/commands/roles.ts +30 -0
  179. package/src/cli/commands/room.ts +14 -0
  180. package/src/cli/commands/roster.ts +48 -0
  181. package/src/cli/commands/route.ts +9 -0
  182. package/src/cli/commands/say.ts +21 -0
  183. package/src/cli/commands/schedule.ts +17 -0
  184. package/src/cli/commands/sdlc.ts +321 -0
  185. package/src/cli/commands/settings.ts +148 -0
  186. package/src/cli/commands/setup.ts +89 -0
  187. package/src/cli/commands/shared-refusals.ts +25 -0
  188. package/src/cli/commands/smoke.ts +44 -0
  189. package/src/cli/commands/source.ts +64 -0
  190. package/src/cli/commands/specs.ts +13 -0
  191. package/src/cli/commands/status.ts +28 -0
  192. package/src/cli/commands/stop.ts +17 -0
  193. package/src/cli/commands/structure.ts +60 -0
  194. package/src/cli/commands/study.ts +39 -0
  195. package/src/cli/commands/tail.ts +19 -0
  196. package/src/cli/commands/task.ts +114 -0
  197. package/src/cli/commands/title.ts +17 -0
  198. package/src/cli/commands/turns.ts +10 -0
  199. package/src/cli/commands/ui.ts +47 -0
  200. package/src/cli/commands/undo.ts +77 -0
  201. package/src/cli/commands/up.ts +39 -0
  202. package/src/cli/commands/upgrade.ts +5 -0
  203. package/src/cli/commands/usage.ts +33 -0
  204. package/src/cli/commands/version.ts +5 -0
  205. package/src/cli/commands/watch.ts +30 -0
  206. package/src/cli/commands/worktrees.ts +31 -0
  207. package/src/cli/console-state.ts +5 -138
  208. package/src/cli/console-versions.ts +1 -1
  209. package/src/cli/help.ts +37 -15
  210. package/src/cli/identity.ts +23 -4
  211. package/src/cli/launch-check.ts +1 -2
  212. package/src/cli/launch.ts +13 -82
  213. package/src/cli/light-dispatch.ts +29 -0
  214. package/src/cli/main.js +8 -1
  215. package/src/cli/main.ts +233 -2816
  216. package/src/cli/orca-probe.ts +119 -0
  217. package/src/cli/output.ts +31 -2
  218. package/src/cli/preview.ts +10 -5
  219. package/src/cli/recovery-version-preflight.ts +28 -9
  220. package/src/cli/replace-process.ts +22 -0
  221. package/src/cli/report-layout.ts +142 -0
  222. package/src/cli/roadmap-usage.ts +16 -0
  223. package/src/cli/roadmap.ts +3 -16
  224. package/src/cli/sdlc-doctor.ts +27 -0
  225. package/src/cli/sdlc-output.ts +55 -1
  226. package/src/cli/setup-homes.ts +1 -1
  227. package/src/cli/start-agents-run.ts +1 -1
  228. package/src/cli/statusline-tee.ts +25 -4
  229. package/src/cli/terminal-recovery.ts +53 -10
  230. package/src/cli/upgrade-interactive.ts +1 -0
  231. package/src/cli/upgrade-runtime.ts +11 -0
  232. package/src/cli/upgrade.ts +4 -15
  233. package/src/hub/accounts.ts +148 -0
  234. package/src/hub/addons.ts +20 -0
  235. package/src/hub/agent-drift.ts +2 -1
  236. package/src/hub/budget-projection.ts +39 -7
  237. package/src/hub/budget.ts +231 -16
  238. package/src/hub/channel-project.ts +3 -3
  239. package/src/hub/conductor-peer.ts +24 -0
  240. package/src/hub/conductor.ts +2 -21
  241. package/src/hub/config-apply.ts +24 -13
  242. package/src/hub/config-edit.ts +1 -1
  243. package/src/hub/config-tier.ts +2 -0
  244. package/src/hub/config.ts +31 -14
  245. package/src/hub/control-client.ts +48 -0
  246. package/src/hub/daemon.ts +421 -61
  247. package/src/hub/events.ts +3 -0
  248. package/src/hub/home-tag.ts +12 -0
  249. package/src/hub/host.ts +217 -0
  250. package/src/hub/hub-tools.ts +2 -1
  251. package/src/hub/instance-budget.ts +2 -2
  252. package/src/hub/instance-config.ts +15 -126
  253. package/src/hub/instances.ts +22 -6
  254. package/src/hub/instruction-receipt.ts +2 -2
  255. package/src/hub/kimi-usage.ts +38 -11
  256. package/src/hub/lifecycle.ts +86 -4
  257. package/src/hub/mcp-bridge-core.ts +98 -0
  258. package/src/hub/mcp-channel-push.ts +20 -0
  259. package/src/hub/mcp-endpoint-serve.ts +178 -0
  260. package/src/hub/mcp-endpoint.ts +226 -0
  261. package/src/hub/mcp-tool-call.ts +181 -0
  262. package/src/hub/operational-settings.ts +2 -0
  263. package/src/hub/orca-env.ts +6 -0
  264. package/src/hub/orca-state.ts +84 -0
  265. package/src/hub/peers.ts +5 -1
  266. package/src/hub/permission-mode.ts +2 -1
  267. package/src/hub/project.ts +20 -0
  268. package/src/hub/protocol-window.ts +58 -0
  269. package/src/hub/quota-origin.ts +20 -0
  270. package/src/hub/registry.ts +36 -2
  271. package/src/hub/report.ts +1 -1
  272. package/src/hub/research.ts +1 -1
  273. package/src/hub/review-brief.ts +47 -2
  274. package/src/hub/roster.ts +6 -3
  275. package/src/hub/routing.ts +9 -2
  276. package/src/hub/sdlc-check.ts +205 -0
  277. package/src/hub/sdlc-sync.ts +146 -0
  278. package/src/hub/sdlc.ts +33 -4
  279. package/src/hub/settings.ts +7 -4
  280. package/src/hub/start-agents.ts +1 -1
  281. package/src/hub/start-mode.ts +11 -4
  282. package/src/hub/structure-budget.ts +131 -0
  283. package/src/hub/structure-scan.ts +149 -0
  284. package/src/hub/tasks-experiment.ts +455 -0
  285. package/src/hub/tasks-guidance.ts +606 -0
  286. package/src/hub/tasks-roadmap-plan.ts +419 -0
  287. package/src/hub/tasks-roadmap.ts +491 -0
  288. package/src/hub/tasks-study.ts +661 -0
  289. package/src/hub/tasks-survey.ts +192 -0
  290. package/src/hub/tasks.ts +319 -2548
  291. package/src/hub/terminal-open.ts +5 -3
  292. package/src/hub/tooling.ts +3 -19
  293. package/src/hub/usage-rollup.ts +9 -3
  294. package/src/local/tools.ts +5 -0
  295. package/src/ui/index.html +1 -1
  296. package/src/ui/needs.ts +17 -5
  297. package/src/ui/peer-palette.ts +2 -4
  298. package/templates/presets/agents.json +60 -0
  299. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,606 @@
1
+ // #1830 S4c: the guidance variant and guidance probe methods of `Tasks`, moved whole. `Tasks` builds one `GuidanceDomain` with its deps and an explicit host (the callbacks the moved bodies reach), keeps a one-line delegating method
2
+ // for each member it or a caller still uses, and stays the only board writer. The probe timers and the active map are instance state of this domain, not module state.
3
+ import { pathCandidates } from "@staix/agent-mem";
4
+ import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
5
+ import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
6
+ import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, GUIDANCE_PROBE_LIVE_LIMITS, isLiveGuidanceProbeManifest, guidanceProbeCanonical, parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration, type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding, type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState, type ProbeAdmissionRecheck, type ProbeReservation, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1 } from "./guidance-probes.ts";
7
+ import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts";
8
+ import { executionOwnerSnapshot, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
9
+ import { executionLinkActor, executionReferenceDigest } from "./execution-links.ts";
10
+ import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
11
+ import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText } from "./roles.ts";
12
+ import { matchesPolicyLexically } from "./path-policy.ts";
13
+ import { relative } from "node:path";
14
+ import { looksSecret } from "@staix/agent-mem";
15
+ import { isClosedTaskState, type Task } from "./board.ts";
16
+ import { HUB, USER, type PeerId } from "./envelope.ts";
17
+ import type { PiiVerdict } from "./inference.ts";
18
+ import { ownerRoleOfClass } from "./routing.ts";
19
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
20
+ import type { TasksDeps } from "./tasks.ts";
21
+
22
+ interface GuidanceProbeRuntime {
23
+ id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck;
24
+ requestedRevision: number; variantId?: string;
25
+ ports: GuidanceProbeFakePorts;
26
+ reservation?: ProbeReservation; promise?: Promise<ProbePublicReceipt>; stopPromise?: Promise<void>;
27
+ launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean;
28
+ watch?: { handle: unknown }; failure?: Error;
29
+ }
30
+
31
+ export interface GuidanceHost {
32
+ requireConductor(peer: string, roles: unknown): void;
33
+ lineageMetadata: (text: string) => boolean;
34
+ lineagePorts: (by: PeerId) => ExecutionLineageOwnerPorts | undefined;
35
+ lineageVisible: (by: PeerId, task: Task) => boolean;
36
+ readonly nameable: (t: string) => boolean;
37
+ personOrConductor: (by: PeerId) => boolean;
38
+ readonly publicMetadataText: (text: string) => boolean;
39
+ requestCheck: (by: PeerId, fence?: () => string | undefined) => () => void;
40
+ reviewObserverTurn: (by: PeerId, task?: number) => boolean;
41
+ screenCall: (text: string) => Promise<PiiVerdict>;
42
+ readonly screenOn: () => boolean;
43
+ studyHold: () => string | undefined;
44
+ studyWrite: <T>(write: () => Promise<T>) => Promise<T>;
45
+ }
46
+
47
+ export class GuidanceDomain {
48
+ private guidanceProbeStopping = false;
49
+ private guidanceProbeAdmissions = 0;
50
+ private readonly guidanceProbeActive = new Map<string, GuidanceProbeRuntime>();
51
+ constructor(private readonly d: TasksDeps, private readonly host: GuidanceHost) {}
52
+
53
+ guidanceProbeTimer(): NonNullable<NonNullable<TasksDeps["guidanceProbes"]>["timer"]> {
54
+ return this.d.guidanceProbes?.timer ?? {
55
+ set: (callback, ms) => { const timer = setTimeout(callback, ms); timer.unref?.(); return timer; },
56
+ clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
57
+ };
58
+ }
59
+ /** Owned in-process work only, not persisted held lanes or a quiescence assertion. */
60
+ guidanceProbesPending = (): number => this.guidanceProbeAdmissions + this.guidanceProbeActive.size;
61
+ async stopGuidanceProbes(): Promise<void> {
62
+ this.guidanceProbeStopping = true;
63
+ const active = [...this.guidanceProbeActive.values()];
64
+ for (const entry of active) this.guidanceProbeAbort(entry, "observation", true);
65
+ if (this.guidanceProbesPending() === 0) return;
66
+ await this.guidanceProbeDrain(active);
67
+ if (this.guidanceProbesPending() !== 0) throw new Error("guidance probe admission drain is unconfirmed; retain project storage and explicitly retry after owned callbacks settle");
68
+ }
69
+ async guidanceProbeDrain(active: GuidanceProbeRuntime[]): Promise<void> {
70
+ const settled = Promise.allSettled(active.flatMap(entry => [entry.promise, entry.stopPromise].filter((value): value is Promise<ProbePublicReceipt> | Promise<void> => value !== undefined)));
71
+ let timeout: { handle: unknown } | undefined;
72
+ try {
73
+ await Promise.race([settled, new Promise<never>((_resolve, reject) => {
74
+ timeout = { handle: this.guidanceProbeTimer().set(() => reject(new Error("guidance probe stop is unconfirmed after the owned drain bound; retain the held lane and explicitly drain after its fixture callbacks settle")), GUIDANCE_PROBE_STOP_TIMEOUT_MS) };
75
+ })]);
76
+ if (active.some(entry => this.guidanceProbeActive.get(entry.id) === entry)) throw new Error("guidance probe stop evidence is unknown; retain owned handles and explicitly retry the drain after matching fixture stop evidence");
77
+ } finally { if (timeout !== undefined) this.guidanceProbeTimer().clear(timeout.handle); }
78
+ }
79
+ guidanceProbeClearWatch(entry: GuidanceProbeRuntime): void {
80
+ if (entry.watch !== undefined) { this.guidanceProbeTimer().clear(entry.watch.handle); entry.watch = undefined; }
81
+ }
82
+ guidanceProbeRetire(entry: GuidanceProbeRuntime): void {
83
+ if (this.guidanceProbeActive.get(entry.id) !== entry || !entry.launchSettled || entry.stopRequested && (!entry.stopSettled || !entry.stopKnown)) return;
84
+ this.guidanceProbeClearWatch(entry); this.guidanceProbeActive.delete(entry.id);
85
+ }
86
+ guidanceProbeAbort(entry: GuidanceProbeRuntime, reason: "elapsed" | "observation", explicitStop = false): void {
87
+ if (this.guidanceProbeActive.get(entry.id) !== entry) return;
88
+ this.guidanceProbeClearWatch(entry);
89
+ if (entry.reservation) {
90
+ try { this.d.guidanceProbes!.store.latchHold(entry.reservation, reason); }
91
+ catch { entry.failure = new Error("guidance probe hold bookkeeping is unconfirmed; inspect retained state before any further work"); }
92
+ }
93
+ entry.controller.abort();
94
+ if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; }
95
+ if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return;
96
+ const reservation = entry.reservation, ports = entry.ports;
97
+ entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false;
98
+ entry.stopPromise = (async () => {
99
+ try {
100
+ const result = await ports.stop({ reservation }, new AbortController().signal);
101
+ entry.stopKnown = result?.stopped === "known_fixture" && guidanceProbeCanonical(result.reservation) === guidanceProbeCanonical(reservation);
102
+ if (!entry.stopKnown) entry.failure = new Error("guidance probe stop evidence is unknown; inspect the owned reservation and explicitly drain without replaying it");
103
+ } catch { entry.failure = new Error("guidance probe stop failed; retain owned handles and explicitly drain before closing project storage"); }
104
+ finally { entry.stopSettled = true; this.guidanceProbeRetire(entry); }
105
+ })();
106
+ }
107
+ guidanceProbeWatch(entry: GuidanceProbeRuntime): void {
108
+ if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
109
+ try {
110
+ entry.current();
111
+ const state = this.d.guidanceProbes!.store.read({ projectKey: this.guidanceProject(), id: entry.id });
112
+ if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable");
113
+ const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt;
114
+ if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; }
115
+ const live = state.sessions.find(session => session.slotId === entry.reservation!.slotId)?.live;
116
+ const remaining = Math.min(state.registration.manifest.limits.elapsedMs - elapsed,
117
+ live === undefined ? Infinity : GUIDANCE_PROBE_LIVE_LIMITS.elapsedMs - (now - live.reservedAt));
118
+ if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; }
119
+ entry.watch = { handle: this.guidanceProbeTimer().set(() => {
120
+ if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
121
+ entry.watch = undefined; this.guidanceProbeWatch(entry);
122
+ }, Math.min(GUIDANCE_PROBE_FENCE_INTERVAL_MS, remaining)) };
123
+ } catch { this.guidanceProbeAbort(entry, "observation"); }
124
+ }
125
+ guidanceProbeProjection(state: ProbeStoredState, already = false): ProbePublicStatus {
126
+ const holds = state.admissionHold !== "none" || state.counters.usageUnknown;
127
+ const authoring: ProbePublicStatus["authoring"] = state.sessions.some(item => item.child?.authoring === "uncontrolled") ? "uncontrolled"
128
+ : state.sessions.some(item => item.child?.authoring === "admitted_fixture") ? "admitted_fixture" : "unknown";
129
+ const launchedSessions = state.sessions.filter(item => item.coverage.launchExposed);
130
+ const verifiedCoverage = launchedSessions.length > 0 && launchedSessions.every(item => item.coverage.coverageVerified)
131
+ && state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified)
132
+ && state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified);
133
+ const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration"
134
+ : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : launchedSessions.every(item => item.live !== undefined) ? "live" : "fixture";
135
+ return { ...state.receipt, already, taskId: state.registration.manifest.task.id,
136
+ experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence,
137
+ counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring,
138
+ comparable: state.receipt.state === "closed_fixture" && !holds && verifiedCoverage && authoring === "admitted_fixture" };
139
+ }
140
+ guidanceProbeReceipt(state: ProbeStoredState, already = false): ProbePublicReceipt {
141
+ const { counters: _counters, cancelRequested: _cancelRequested, notNeeded: _notNeeded, comparable: _comparable, authoring: _authoring, ...result } = this.guidanceProbeProjection(state, already);
142
+ return result;
143
+ }
144
+ guidanceProbeState(by: PeerId, id: string, check: () => void): ProbeStoredState {
145
+ check();
146
+ if (!probeSha256(id)) throw new PreEffectToolRefusal("guidance probe id is invalid; use the exact registered content id");
147
+ if (!this.d.guidanceProbes) throw new PreEffectToolRefusal("guidance probe storage is unavailable; restart a supporting hub before retrying");
148
+ const state = this.d.guidanceProbes.store.read({ projectKey: this.guidanceProject(), id });
149
+ if (!state) throw new PreEffectToolRefusal("guidance probe is unavailable; inspect a registered declaration in this project");
150
+ this.guidanceProbeTask(by, state.registration.manifest.task, false); check(); return state;
151
+ }
152
+ guidanceProbeHost(by: PeerId, manifest: GuidanceProbeManifestV1, request: ReturnType<GuidanceDomain["guidanceProbeRequest"]>, history?: ProbeHostBinding): ProbeHostBinding {
153
+ request.check();
154
+ const projectKey = this.guidanceProject();
155
+ if (projectKey !== manifest.projectKey) throw new PreEffectToolRefusal("guidance probe project changed; register within the current project namespace");
156
+ const task = this.guidanceProbeTask(by, manifest.task, history === undefined);
157
+ const binding = { projectKey, actor: by, task: { id: task.id, created: task.created, flowRevision: task.history.length },
158
+ sessionGeneration: request.generation, nativeSession: request.nativeSession, requestConnectionId: request.requestConnectionId };
159
+ // A narrowing cancellation carries its original baseline as history, never a new applicability grant.
160
+ if (history) return { ...binding, role: history.role, baselineGuidance: history.baselineGuidance };
161
+ const role = this.guidanceRole(task);
162
+ return { ...binding, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, baselineGuidance: taskRoleText(role) };
163
+ }
164
+ guidanceProbeSnapshotClear(state: ProbeStoredState["registration"]): boolean {
165
+ return Object.entries(state.snapshots).every(([field, value]) => {
166
+ const text = field === "dataPolicy" ? guidanceProbeCanonical(value) : value as string;
167
+ return this.host.nameable(text) && !looksSecret(text);
168
+ });
169
+ }
170
+ guidanceProbeRenderedClear(text: string): boolean {
171
+ if (!this.host.nameable(text) || looksSecret(text)) return false;
172
+ const policy = [...this.d.deny ?? [], ...this.d.piiPaths ?? []];
173
+ if ([...pathCandidates(text)].some(candidate => matchesPolicyLexically(this.d.cwd, candidate, policy))) return false;
174
+ return !policy.some(entry => {
175
+ const literal = entry.replace(/^\.\//, "").split(/[*?[\]{}]/)[0]!.replace(/\/+$/, "");
176
+ return /[/\s]/.test(literal) && text.includes(literal);
177
+ });
178
+ }
179
+ async guidanceProbeRegister(by: PeerId, value: unknown): Promise<ProbePublicReceipt> {
180
+ const request = this.guidanceProbeRequest(by), registration = parseGuidanceProbeRegistration(value);
181
+ if (!registration) throw new PreEffectToolRefusal("guidance probe declaration is invalid or oversized; use the closed V1 envelope without trimming its snapshots");
182
+ const binding = this.guidanceProbeHost(by, registration.manifest, request);
183
+ if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe inputs are private; register public task-local inputs in a current public session");
184
+ this.guidanceProbeAdmissions++;
185
+ let wrote = false;
186
+ try {
187
+ const saved = this.d.guidanceProbes!.store.register(registration, binding, () => {
188
+ if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe input policy changed; inspect its current public scope before retrying");
189
+ return this.guidanceProbeHost(by, registration.manifest, request);
190
+ });
191
+ wrote = !saved.already;
192
+ const state = this.guidanceProbeState(by, saved.id, request.check);
193
+ return this.guidanceProbeReceipt(state, saved.already);
194
+ } catch (error) {
195
+ if (!wrote && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
196
+ throw new Error("guidance probe registration is unconfirmed; inspect retained state before explicitly retrying");
197
+ }
198
+ finally { this.guidanceProbeAdmissions--; }
199
+ }
200
+ async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
201
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
202
+ request.check();
203
+ const status = this.guidanceProbeProjection(state);
204
+ // T3 (#1226): the sealed receipts can only make the verdict stricter, never grant one the older expression refused. The reasons and the denominator stay in
205
+ // the store's private status; public show keeps just this flag. A store that cannot be read is not comparable.
206
+ if (!status.comparable) return status;
207
+ let sealedComparable = false;
208
+ try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ }
209
+ return sealedComparable ? status : { ...status, comparable: false };
210
+ }
211
+ /**
212
+ * T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches,
213
+ * reserves, writes and prunes nothing. It carries the status, the outcome denominator and the sealed receipts, each re-verified against its own digest by the
214
+ * Store, so a tampered row refuses the whole read instead of being skipped. Output names are model-written, so each receipt passes the same screen as any
215
+ * other public field; one that fails is replaced by its digest alone and the slot says `withheld`. A retained directory is a state, never a path.
216
+ */
217
+ async guidanceProbeReceipts(by: PeerId, id: string): Promise<ProbeReceiptExport> {
218
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
219
+ request.check();
220
+ const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id };
221
+ const status = await this.guidanceProbeShow(by, id);
222
+ let receipts: ProbeReceiptV1[], outcome: ReturnType<GuidanceProbeStore["outcome"]>, retention: Map<string, ProbeRetentionState>;
223
+ try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); }
224
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
225
+ if (!outcome) throw new GuidanceProbeError("storage");
226
+ request.check();
227
+ const bySlot = new Map(receipts.map(item => [item.slotId, item]));
228
+ const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => {
229
+ const session = state.sessions[index]!, receipt = bySlot.get(slot.id);
230
+ const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt);
231
+ return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null,
232
+ receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" };
233
+ });
234
+ // The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused.
235
+ const comparable = status.comparable && outcome.comparability.comparable;
236
+ const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots };
237
+ // What leaves this process is what the consumer's parser will accept: a result that does not round-trip is a storage fault, never a partial answer.
238
+ const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result)));
239
+ if (!checked) throw new GuidanceProbeError("storage");
240
+ return checked;
241
+ }
242
+ /** Every free-text name a receipt carries (output paths, exclusions, the served model) must pass the public-field screen; the digest alone is kept otherwise. */
243
+ guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean {
244
+ const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)];
245
+ return names.every(text => text === "" || this.guidanceFieldAllowed(text));
246
+ }
247
+ async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
248
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
249
+ const host = this.guidanceProbeHost(by, state.registration.manifest, request);
250
+ if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId))
251
+ throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id");
252
+ const dependency = this.d.guidanceProbes!;
253
+ // Match a host-configured content ID, never a mode requested by the caller or carried by imported evidence.
254
+ const live = dependency.live?.id === id ? dependency.live.adapter : undefined;
255
+ if (live && (by === USER || request.nativeSession === null))
256
+ // refusal:by-design human-authority: live starts require an authenticated conductor session
257
+ throw new PreEffectToolRefusal("live guidance probes require the current authenticated conductor native session");
258
+ if (live && !isLiveGuidanceProbeManifest(state.registration.manifest))
259
+ // refusal:by-design operator-knowledge: the operator must supply the preregistered bounded declaration
260
+ throw new PreEffectToolRefusal("live guidance probe requires a bounded baseline and candidate declaration");
261
+ const selectedPorts = live?.ports ?? dependency.fakePorts;
262
+ // refusal:by-design human-authority: only the host operator can select a live registration
263
+ if (!selectedPorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1 for this registration");
264
+ const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision);
265
+ if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession
266
+ || original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it");
267
+ const slot = original ? state.registration.manifest.slots.find(item => item.id === original.slotId)
268
+ : state.registration.manifest.slots.find(item => state.sessions.find(session => session.slotId === item.id)?.state === "planned");
269
+ if (!slot) throw new PreEffectToolRefusal("guidance probe has no eligible slot; inspect its retained terminal or held state");
270
+ if (original && original.variantId !== (variantId ?? null)) throw new PreEffectToolRefusal("guidance probe original selector differs; inspect its original G1 id without rebinding the start");
271
+ const needsVariant = slot.role === "worker" && slot.arm !== "baseline";
272
+ if (needsVariant !== (variantId !== undefined)) throw new PreEffectToolRefusal("guidance probe next worker needs its existing G1 id only; use --variant for the next non-baseline worker");
273
+ const current = (): ProbeAdmissionRecheck => {
274
+ const fresh = this.guidanceProbeHost(by, state.registration.manifest, request);
275
+ if (!this.guidanceProbeSnapshotClear(state.registration)) throw new PreEffectToolRefusal("guidance probe input privacy changed; retain its declaration and use current public inputs");
276
+ return { host: fresh, ...(variantId === undefined ? {} : { child: this.guidanceProbeVariantBinding(by, this.guidanceProbeTask(by, state.registration.manifest.task, true), variantId) }) };
277
+ };
278
+ const prepared = current();
279
+ const active = this.guidanceProbeActive.get(id);
280
+ if (active) {
281
+ if (active.requestedRevision !== revision || active.variantId !== variantId)
282
+ throw new PreEffectToolRefusal("another owned probe attempt is still settling; inspect its state before explicitly starting the next stage");
283
+ const captured = active.current().host;
284
+ if (captured.actor !== host.actor || captured.sessionGeneration !== host.sessionGeneration || captured.nativeSession !== host.nativeSession
285
+ || captured.requestConnectionId !== host.requestConnectionId)
286
+ throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it");
287
+ // Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata.
288
+ if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
289
+ const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, current);
290
+ if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work");
291
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
292
+ }
293
+ const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, ports: selectedPorts, launched: false, launchSettled: false,
294
+ stopRequested: false, stopSettled: false, stopKnown: false };
295
+ this.guidanceProbeActive.set(id, entry);
296
+ const ports: GuidanceProbeFakePorts = {
297
+ launch: async (input, effects, signal) => {
298
+ entry.reservation = input.reservation;
299
+ this.guidanceProbeWatch(entry);
300
+ if (signal.aborted) throw new Error("owned probe was aborted before launch");
301
+ entry.launched = true;
302
+ return selectedPorts.launch(input, effects, signal);
303
+ },
304
+ stop: (input, signal) => selectedPorts.stop(input, signal),
305
+ ...(selectedPorts.discardRetained ? { discardRetained: record => selectedPorts.discardRetained!(record) } : {}),
306
+ };
307
+ let reserved = false, returned = false;
308
+ const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, ...(live ? { mode: "live" as const } : {}), revalidate: current, now: () => this.d.now?.() ?? Date.now(),
309
+ prepareWorkerFrame: live?.prepareWorkerFrame ?? dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
310
+ entry.promise = (async () => {
311
+ try {
312
+ const saved = await runner.start({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
313
+ returned = true;
314
+ if (saved.state === "unknown_held" && entry.launched) {
315
+ this.guidanceProbeAbort(entry, "observation", true);
316
+ if (!entry.stopPromise) throw new Error("owned probe stop was not recorded; retain the held lane and explicitly inspect its outcome");
317
+ await entry.stopPromise;
318
+ }
319
+ request.check();
320
+ if (entry.failure) throw entry.failure;
321
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
322
+ } catch (error) {
323
+ this.guidanceProbeAbort(entry, "observation");
324
+ if (!reserved && !returned && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
325
+ throw new Error("guidance probe attempt outcome is unconfirmed; inspect its retained id without replaying work");
326
+ } finally { entry.launchSettled = true; this.guidanceProbeClearWatch(entry); this.guidanceProbeRetire(entry); }
327
+ })();
328
+ return entry.promise;
329
+ }
330
+ async guidanceProbeCancel(by: PeerId, id: string, revision: number): Promise<ProbePublicReceipt> {
331
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
332
+ if (!probeInteger(revision)) throw new PreEffectToolRefusal("guidance probe cancellation revision is invalid; inspect its current CAS revision");
333
+ const current = () => this.guidanceProbeHost(by, state.registration.manifest, request, state.binding), host = current();
334
+ try {
335
+ const saved = this.d.guidanceProbes!.store.cancelIntent({ key: { projectKey: host.projectKey, id }, expectedRevision: revision, host }, current);
336
+ const entry = this.guidanceProbeActive.get(id);
337
+ if (entry) { this.guidanceProbeAbort(entry, "observation", true); await this.guidanceProbeDrain([entry]); }
338
+ request.check();
339
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
340
+ } catch { throw new Error("guidance probe cancellation is unconfirmed; inspect its retained intent and owned drain before retrying"); }
341
+ }
342
+ guidanceProbeRequest(by: PeerId): { check: () => void; generation: number | string; nativeSession: string | null; requestConnectionId: string } {
343
+ const request = this.guidanceRequest(by, "probe");
344
+ if (!this.host.personOrConductor(by)) throw new PreEffectToolRefusal("guidance probes require the person or current configured conductor; use an admitted operational session");
345
+ const session = this.d.guidanceProbes?.session?.(by);
346
+ if (!session || !probeSessionGeneration(session.generation) || !executionText(session.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
347
+ || session.nativeSession !== null && !executionText(session.nativeSession, EXECUTION_REFERENCE_LIMITS.id))
348
+ throw new PreEffectToolRefusal("guidance probe request session is unavailable; reconnect through a current authenticated project connection");
349
+ const sessionCurrent = session.current;
350
+ const current = () => {
351
+ sessionCurrent(); request();
352
+ if (this.guidanceProbeStopping) throw new PreEffectToolRefusal("guidance probe admission is stopping; inspect retained work after the owned drain");
353
+ if (this.d.reviewOnly?.(by)) throw new PreEffectToolRefusal("guidance probes are unavailable in a review-only context; use a current public operational session");
354
+ if (by !== USER) {
355
+ try { this.host.requireConductor(by, this.d.roles); }
356
+ catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; refresh the configured role before retrying"); }
357
+ if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor is not currently rostered; restore current membership before retrying");
358
+ }
359
+ };
360
+ current(); return { check: current, generation: session.generation, nativeSession: session.nativeSession, requestConnectionId: session.requestConnectionId };
361
+ }
362
+ guidanceProbeTask(by: PeerId, selected: { id: number; created: number; flowRevision: number }, admission: boolean): Task {
363
+ const task = this.guidanceTask(by, { taskId: selected.id, taskCreated: selected.created }, false);
364
+ if (admission && (task.history.length !== selected.flowRevision || !["in_progress", "changes_requested"].includes(task.state)))
365
+ throw new PreEffectToolRefusal(`guidance probe admission is stale or task state is ${task.state}; accept current work in in_progress or changes_requested and reload its revision`);
366
+ return task;
367
+ }
368
+ /** Actual probe actor only; the source owner validates/hydrates G1, never an impersonated read or separate SQL parser. */
369
+ guidanceProbeVariantBinding(by: PeerId, task: Task, variantId: string): ProbeChildBinding {
370
+ if (by !== USER) {
371
+ try { this.host.requireConductor(by, this.d.roles); }
372
+ catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; reconnect in a current operational session"); }
373
+ if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor membership changed; restore current roster membership before retrying");
374
+ }
375
+ const current = this.guidanceProbeTask(by, { id: task.id, created: task.created, flowRevision: task.history.length }, true);
376
+ if (!probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe variant selector is invalid; choose an existing current G1 content id");
377
+ const project = this.guidanceProject(), role = this.guidanceRole(current);
378
+ const experiment = this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(project, current.id, current.created, variantId));
379
+ const record = experiment === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(project, current.id, current.created, experiment)).find(item => item.variant.id === variantId);
380
+ if (!record || record.withdrawn || record.variant.flowRevision !== current.history.length || record.variant.baseline.roleId !== role.id
381
+ || record.variant.baseline.layer !== role.layer || record.variant.baseline.sha256 !== role.hash)
382
+ throw new PreEffectToolRefusal("guidance probe G1 is unavailable, withdrawn or stale; separately admit a current owner/person variant before retrying");
383
+ const guidance = renderGuidanceVariantV1(record.variant);
384
+ if (!this.guidanceProbeRenderedClear(guidance))
385
+ throw new PreEffectToolRefusal("guidance probe handoff text is private; use a current public G1 before retrying");
386
+ return { variantId, candidateSha256: record.variant.candidate.sha256, guidanceSha256: probeHash(guidance), guidance,
387
+ task: { id: current.id, created: current.created, flowRevision: current.history.length },
388
+ role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, authoring: "uncontrolled", sourceSessionId: null };
389
+ }
390
+ guidanceRequest(by: PeerId, mode: "guidance" | "probe" = "guidance"): () => void {
391
+ if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
392
+ throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
393
+ const request = this.host.requestCheck(by, () => this.host.studyHold());
394
+ const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
395
+ const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined;
396
+ const check = () => {
397
+ request();
398
+ if (this.d.privateTurn?.(by) || this.host.reviewObserverTurn(by))
399
+ throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
400
+ if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
401
+ || peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered))
402
+ throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
403
+ };
404
+ check(); return check;
405
+ }
406
+ guidanceTask(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, write: boolean): Task {
407
+ const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId));
408
+ if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying");
409
+ if (task.created !== selector.taskCreated || !this.host.lineageVisible(by, task) || this.host.reviewObserverTurn(by, task.id))
410
+ throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying");
411
+ if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review"
412
+ || !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by))))
413
+ throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying");
414
+ return task;
415
+ }
416
+ guidanceProject(): string {
417
+ const key = this.d.executionLineage?.projectKey;
418
+ if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying");
419
+ return key;
420
+ }
421
+ guidanceRole(task: Task) {
422
+ let role;
423
+ try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); }
424
+ catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); }
425
+ if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant");
426
+ return role;
427
+ }
428
+ guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean {
429
+ const { evidenceRefs, ...text } = record.variant;
430
+ // Opaque evidence addresses never become filesystem/producer lookup instructions.
431
+ return this.host.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.host.lineageMetadata(JSON.stringify(reference)));
432
+ }
433
+ /** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */
434
+ guidanceStorage<T>(operation: "read" | "write", action: () => T): T {
435
+ try { return action(); }
436
+ catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); }
437
+ }
438
+ guidanceFence(by: PeerId, task: Task): GuidanceWriteFence {
439
+ return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
440
+ owner: task.owner, state: task.state, roleId: task.role };
441
+ }
442
+ guidanceFieldAllowed(text: string): boolean {
443
+ try { return this.host.nameable(text) && !looksSecret(text) && this.host.lineageMetadata(JSON.stringify(text)); }
444
+ catch { return false; }
445
+ }
446
+ guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; }
447
+ guidanceExperimentFor(projectKey: string, task: Task, selector: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id"> & { experimentId?: string }): string | undefined {
448
+ return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined);
449
+ }
450
+ guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; }
451
+ guidanceReadFence(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, task: Task, check: () => void): Task {
452
+ check(); const current = this.guidanceTask(by, selector, false);
453
+ if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role])
454
+ !== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed");
455
+ return current;
456
+ }
457
+ guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] {
458
+ const ports = this.host.lineagePorts(by), projectKey = this.guidanceProject();
459
+ return records.map(record => record.variant.evidenceRefs.map(reference => {
460
+ let known = false;
461
+ if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) {
462
+ const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } });
463
+ known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference));
464
+ }
465
+ return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const };
466
+ }));
467
+ }
468
+ guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord {
469
+ return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId),
470
+ status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record),
471
+ rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence };
472
+ }
473
+ guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt {
474
+ const value = saved.record.variant;
475
+ return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already };
476
+ }
477
+ /** Immutable declarations only. Neither creation nor readback changes effective role guidance. */
478
+ async guidanceVariantCreate(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
479
+ const check = this.guidanceRequest(by);
480
+ let variant: Readonly<GuidanceVariantV1>;
481
+ try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); }
482
+ return this.host.studyWrite(async () => {
483
+ const context = () => {
484
+ check();
485
+ const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task);
486
+ if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying");
487
+ const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId));
488
+ const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId));
489
+ try {
490
+ validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
491
+ experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline,
492
+ currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) });
493
+ } catch (error) {
494
+ if (error instanceof GuidanceVariantError) throw new PreEffectToolRefusal("guidance variant or frozen baseline is invalid or changed; reload the task and use a new experiment for a changed baseline");
495
+ throw new Error("guidance validation is unavailable; inspect the task experiment before retrying");
496
+ }
497
+ return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) };
498
+ };
499
+ const before = context();
500
+ if (this.host.screenOn() && (await this.host.screenCall(JSON.stringify(variant))).label !== "clear")
501
+ throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available");
502
+ const current = context();
503
+ if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying");
504
+ check();
505
+ const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task)));
506
+ return this.guidanceReceipt(saved);
507
+ });
508
+ }
509
+ async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
510
+ const check = this.guidanceRequest(by);
511
+ let selector: GuidanceSelector | GuidanceIdSelector;
512
+ try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } }
513
+ catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); }
514
+ return this.host.studyWrite(async () => {
515
+ check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject();
516
+ if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing");
517
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
518
+ const record = experimentId === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId)).find(item => item.variant.id === selector.id);
519
+ if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing");
520
+ check();
521
+ const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task)));
522
+ return this.guidanceReceipt(saved);
523
+ });
524
+ }
525
+ guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean {
526
+ try {
527
+ if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false;
528
+ const value = record.variant, role = this.guidanceRole(task);
529
+ return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer
530
+ && value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true);
531
+ } catch { return false; }
532
+ }
533
+ /** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */
534
+ guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult {
535
+ try {
536
+ const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input);
537
+ check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject();
538
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
539
+ if (experimentId === undefined) return { state: "unavailable" };
540
+ const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId);
541
+ const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records;
542
+ if (!selected.length) return { state: "unavailable" };
543
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check);
544
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
545
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId);
546
+ const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh;
547
+ if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" };
548
+ const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) };
549
+ check();
550
+ return result;
551
+ } catch { return { state: "unavailable" }; }
552
+ }
553
+ /** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */
554
+ guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult {
555
+ try {
556
+ const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input);
557
+ const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector);
558
+ if (experimentId === undefined) return { state: "unavailable" };
559
+ const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id);
560
+ if (!record) return { state: "unavailable" };
561
+ const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check);
562
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
563
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id);
564
+ if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" };
565
+ const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!),
566
+ sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() });
567
+ check(); return result;
568
+ } catch { return { state: "unavailable" }; }
569
+ }
570
+ /** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */
571
+ guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult {
572
+ try {
573
+ const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject();
574
+ const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" };
575
+ const context = { ...this.guidanceCurrent(task), projectKey, actor: by };
576
+ const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : "";
577
+ if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" };
578
+ const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS);
579
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check);
580
+ const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after);
581
+ if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" };
582
+ const records: GuidancePublicRecord[] = [];
583
+ for (const [index, record] of selected.entries()) {
584
+ const candidate = this.guidanceProjection(by, current, record, evidence[index]!);
585
+ const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) };
586
+ if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break;
587
+ records.push(candidate);
588
+ }
589
+ const truncated = records.length < page.length;
590
+ if (truncated && !records.length) return { state: "unavailable" };
591
+ const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated,
592
+ ...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) });
593
+ check(); return result;
594
+ } catch { return { state: "unavailable" }; }
595
+ }
596
+ /** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */
597
+ guidanceVariantApplicable(by: PeerId, input: unknown): boolean {
598
+ try {
599
+ const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected);
600
+ return read.state === "available" && read.record.applicable;
601
+ } catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ }
602
+ try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; }
603
+ const read = this.guidanceVariantRead(by, input);
604
+ return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable;
605
+ }
606
+ }