@staix/agent-hub 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/guidance-probes.md +365 -0
  15. package/docs/design/task-board.md +151 -5
  16. package/docs/dogfood.md +22 -7
  17. package/docs/events.md +3 -3
  18. package/docs/memory.md +5 -5
  19. package/docs/operations.md +189 -32
  20. package/docs/profiles.md +101 -9
  21. package/docs/quickstart.md +38 -4
  22. package/docs/research.md +6 -3
  23. package/docs/roles.md +52 -0
  24. package/docs/sdlc.md +187 -1
  25. package/docs/security.md +56 -13
  26. package/docs/text-projection.md +1 -0
  27. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  29. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  30. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  31. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  32. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  33. package/docs/verified.json +48 -25
  34. package/package.json +3 -3
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +1989 -474
  37. package/plugins/agent-hub/server.js +2056 -512
  38. package/src/adapters/acp-model-policy.ts +1 -1
  39. package/src/adapters/acp-session-model.ts +35 -0
  40. package/src/adapters/acp.ts +14 -0
  41. package/src/adapters/agy/definition.ts +1 -1
  42. package/src/adapters/agy/hooks.ts +7 -0
  43. package/src/adapters/claude-channel.ts +3 -2
  44. package/src/adapters/claude-implementer.ts +8 -0
  45. package/src/adapters/claude-print-child.ts +26 -2
  46. package/src/adapters/claude-print.ts +4 -0
  47. package/src/adapters/codex-appserver.ts +90 -16
  48. package/src/adapters/codex-review-isolation.ts +2 -0
  49. package/src/adapters/compat.ts +4 -4
  50. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  51. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  52. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  53. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  55. package/src/adapters/definitions/native-quota.ts +122 -0
  56. package/src/adapters/definitions/native-recovery.ts +3 -0
  57. package/src/adapters/definitions/qwen.ts +1 -1
  58. package/src/adapters/kimi-review.ts +23 -0
  59. package/src/adapters/kimi-wire-usage.ts +39 -16
  60. package/src/adapters/local-probe.ts +65 -6
  61. package/src/adapters/local-worker.ts +6 -3
  62. package/src/adapters/pi-state-model.ts +12 -0
  63. package/src/adapters/pi.ts +22 -0
  64. package/src/adapters/print-result-model.ts +24 -0
  65. package/src/adapters/registry-types.ts +10 -1
  66. package/src/adapters/registry.ts +19 -2
  67. package/src/adapters/reviewer-print.ts +130 -15
  68. package/src/adapters/role-eligibility.ts +99 -0
  69. package/src/adapters/same-directory.ts +16 -0
  70. package/src/cli/agy-mcp.ts +18 -7
  71. package/src/cli/console-state.ts +3 -1
  72. package/src/cli/free-text.ts +20 -0
  73. package/src/cli/handoff-args.ts +1 -1
  74. package/src/cli/help.ts +61 -6
  75. package/src/cli/identity.ts +10 -4
  76. package/src/cli/init-prompt.ts +31 -2
  77. package/src/cli/init-roles.ts +156 -0
  78. package/src/cli/init-settings.ts +24 -2
  79. package/src/cli/init.ts +141 -17
  80. package/src/cli/main.ts +216 -56
  81. package/src/cli/model.ts +1 -1
  82. package/src/cli/output.ts +64 -5
  83. package/src/cli/preview.ts +1 -1
  84. package/src/cli/recovery-launch.ts +114 -0
  85. package/src/cli/recovery-package.ts +14 -7
  86. package/src/cli/recovery-version-preflight.ts +104 -0
  87. package/src/cli/role-doctor.ts +39 -0
  88. package/src/cli/sdlc-output.ts +66 -1
  89. package/src/cli/study-output.ts +54 -0
  90. package/src/cli/study.ts +14 -1
  91. package/src/cli/terminal-recovery.ts +14 -0
  92. package/src/cli/upgrade-presentation.ts +4 -0
  93. package/src/cli/upgrade-restore-state.ts +12 -3
  94. package/src/cli/upgrade-runtime.ts +41 -3
  95. package/src/cli/upgrade.ts +8 -4
  96. package/src/hub/advisor-survey.ts +139 -0
  97. package/src/hub/audit-source.ts +66 -0
  98. package/src/hub/board.ts +479 -14
  99. package/src/hub/budget.ts +54 -4
  100. package/src/hub/bus.ts +2 -2
  101. package/src/hub/conductor.ts +14 -8
  102. package/src/hub/config-apply.ts +2 -1
  103. package/src/hub/config-edit-host.ts +77 -5
  104. package/src/hub/considered-findings.ts +47 -0
  105. package/src/hub/control-client.ts +1 -1
  106. package/src/hub/daemon.ts +373 -66
  107. package/src/hub/deliverable-files.ts +17 -1
  108. package/src/hub/dogfood-profile.ts +3 -2
  109. package/src/hub/envelope.ts +6 -1
  110. package/src/hub/events.ts +23 -2
  111. package/src/hub/folder-trigger.ts +11 -4
  112. package/src/hub/guidance-probe-store.ts +345 -14
  113. package/src/hub/guidance-probes.ts +338 -4
  114. package/src/hub/hub-tools.ts +88 -16
  115. package/src/hub/kimi-usage.ts +34 -2
  116. package/src/hub/lifecycle-schema.ts +3 -3
  117. package/src/hub/manager.ts +24 -1
  118. package/src/hub/memory-profile.ts +9 -1
  119. package/src/hub/memory-sync-state.ts +1 -0
  120. package/src/hub/model-overrides.ts +2 -1
  121. package/src/hub/no-writes.ts +2 -0
  122. package/src/hub/operational-authority.ts +8 -2
  123. package/src/hub/operational-view.ts +5 -1
  124. package/src/hub/peers.ts +2 -0
  125. package/src/hub/person-command.ts +25 -0
  126. package/src/hub/plan-conformance.ts +20 -2
  127. package/src/hub/quota-account.ts +34 -0
  128. package/src/hub/recovery-policy.ts +18 -4
  129. package/src/hub/research-evidence.ts +51 -3
  130. package/src/hub/research.ts +77 -13
  131. package/src/hub/restart.ts +14 -0
  132. package/src/hub/review-budget.ts +88 -0
  133. package/src/hub/review-findings.ts +93 -12
  134. package/src/hub/reviewer-pool-config.ts +6 -2
  135. package/src/hub/reviewer-pool.ts +39 -6
  136. package/src/hub/routing.ts +7 -3
  137. package/src/hub/sdlc-merge.ts +1 -1
  138. package/src/hub/sdlc-queue.ts +14 -4
  139. package/src/hub/sdlc-release.ts +1 -1
  140. package/src/hub/sdlc.ts +10 -6
  141. package/src/hub/security-audit.ts +178 -0
  142. package/src/hub/security-pass.ts +115 -0
  143. package/src/hub/settings.ts +11 -5
  144. package/src/hub/source-read.ts +80 -2
  145. package/src/hub/sources.ts +57 -9
  146. package/src/hub/startup-event-seeds.ts +5 -3
  147. package/src/hub/startup-timing.ts +1 -0
  148. package/src/hub/supervision.ts +3 -2
  149. package/src/hub/synthesis-readiness.ts +279 -0
  150. package/src/hub/tasks.ts +1131 -72
  151. package/src/hub/text-projection.ts +11 -1
  152. package/src/local/probe-types.ts +2 -0
  153. package/src/local/probe-workspace.ts +191 -2
  154. package/src/memory/capture.ts +2 -1
  155. package/src/ui/guidance-panel.ts +34 -2
  156. package/src/ui/guidance-view.ts +33 -0
  157. package/src/ui/index.html +3 -0
  158. package/src/ui/office-model.ts +11 -3
  159. package/src/ui/office-space.ts +50 -30
  160. package/src/ui/plugin.ts +31 -14
  161. package/templates/AGENTS.block.md +14 -14
  162. package/templates/profiles/general.json +1 -1
  163. package/templates/profiles/research.json +1 -1
  164. package/templates/profiles/writing.json +1 -1
@@ -10,7 +10,10 @@ import { GUIDANCE_PROBE_LIMITS, GUIDANCE_PROBE_SESSION_BYTES, GUIDANCE_PROBE_MOD
10
10
  type ProbeEffectSettlement, type ProbeSessionSettlement, type ProbeUsageObservation, type ProbeCancellation,
11
11
  type ProbeIntegrity, type ProbeChildBinding, type GuidanceProbeFakePorts, type ProbeFakeEffects,
12
12
  type ProbeFakeEffectRequest, type ProbeFakeEffectValue, type ProbeFakeEffectResult, type ProbeFakeObservation, type ProbeSlot, type ProbeStartSelector,
13
- type ProbePreparedFrame, type ProbeSessionCoverage, type ProbeResourceCharges, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
13
+ type ProbePreparedFrame, type ProbeSessionCoverage, type ProbeResourceCharges, type ProbeWorkerFramePreparer,
14
+ PROBE_RETENTION_MS, PROBE_RECEIPT_ROW_BYTES, parseProbeReceipt, probeReceiptDigest, probeOutcomeCounts, classifyProbeComparability, capOutput, type ProbeReceiptV1, type ProbeReceiptLimit,
15
+ type ProbeReceiptState, type ProbeMeasuredSession, type ProbeOutcomeCounts, type ProbeComparability, parseProbeRetained, type ProbeRetainedRecord, type ProbeRetentionFs,
16
+ type ProbePrunePlan, type ProbePruneResult, type ProbePruneKeepReason } from "./guidance-probes.ts";
14
17
 
15
18
  interface Effect { admission: ProbeEffectAdmission; state: "pending" | "settled" | "unknown"; usageHash: string | null; observed: number | null }
16
19
  interface Session extends ProbeSession { host?: ProbeHostBinding; effect: Effect | null }
@@ -54,7 +57,7 @@ const counters = (): ProbeCounters => ({ workerAttempts: 0, editorAttempts: 0, m
54
57
  elapsedHighWaterMs: 0, usageUnknown: false });
55
58
  const sessionCoverage = (frame: ProbePreparedFrame | undefined): ProbeSessionCoverage => ({
56
59
  inputFrameSha256: frame?.sha256 ?? null, inputFrameBytes: frame?.bytes ?? 0, launchExposed: false, preLaunchFailure: false,
57
- modelCalls: 0, modelUsageKnown: 0, toolCalls: 0, toolUsageKnown: 0, usageUnknown: false, coverageVerified: false,
60
+ modelCalls: 0, modelUsageKnown: 0, toolCalls: 0, toolUsageKnown: 0, usageUnknown: false, coverageVerified: false, tokensObserved: 0,
58
61
  });
59
62
  const receipt = (state: Stored, already = false): ProbeReceipt => ({ ...state.receipt, already });
60
63
  const advance = (state: Stored): void => { state.receipt.revision = increment(state.receipt.revision); };
@@ -136,8 +139,13 @@ function skipUnusedRetries(state: Stored, successful: number): void {
136
139
  /** Private same-db ledger. It never reads G1 tables or owns Task authority. */
137
140
  export class GuidanceProbeStore {
138
141
  private readonly db: Database;
139
- constructor(file: string, private readonly now: () => number = Date.now) {
140
- this.db = openHubDatabase(file, { create: true });
142
+ /**
143
+ * `readonly` opens the file on a connection that physically cannot write and creates nothing: every read still works, and any write path (including `reconcile`)
144
+ * fails as storage. It is how a reader proves "a read-only open never writes" (#1226 T3) and the open a future status reader should use.
145
+ */
146
+ constructor(file: string, private readonly now: () => number = Date.now, readonly readOnly = false) {
147
+ this.db = readOnly ? openHubDatabase(file, { readonly: true }) : openHubDatabase(file, { create: true });
148
+ if (readOnly) return;
141
149
  try {
142
150
  this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_manifests (
143
151
  project TEXT NOT NULL,id TEXT NOT NULL,experiment TEXT NOT NULL,manifest TEXT NOT NULL,
@@ -147,6 +155,9 @@ export class GuidanceProbeStore {
147
155
  this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_lanes (project TEXT PRIMARY KEY,manifest_id TEXT NOT NULL,slot_id TEXT)`);
148
156
  this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_sessions (project TEXT NOT NULL,manifest_id TEXT NOT NULL,ordinal INTEGER NOT NULL,
149
157
  slot_id TEXT NOT NULL,body TEXT NOT NULL,PRIMARY KEY(project,manifest_id,slot_id),UNIQUE(project,manifest_id,ordinal))`);
158
+ // T3: one immutable receipt per finished slot. No UPDATE statement exists for this table; a prune never touches it.
159
+ this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_receipts (project TEXT NOT NULL,manifest_id TEXT NOT NULL,slot_id TEXT NOT NULL,
160
+ body TEXT NOT NULL,pruned INTEGER NOT NULL DEFAULT 0,retained TEXT,PRIMARY KEY(project,manifest_id,slot_id))`);
150
161
  } catch (error) {
151
162
  this.db.close();
152
163
  if (error instanceof GuidanceProbeError) throw error;
@@ -157,7 +168,7 @@ export class GuidanceProbeStore {
157
168
  hasRecords(): boolean {
158
169
  try {
159
170
  const row = this.db.query(`SELECT EXISTS(SELECT 1 FROM guidance_probe_manifests)
160
- OR EXISTS(SELECT 1 FROM guidance_probe_sessions) OR EXISTS(SELECT 1 FROM guidance_probe_lanes) AS present`).get() as { present: number };
171
+ OR EXISTS(SELECT 1 FROM guidance_probe_sessions) OR EXISTS(SELECT 1 FROM guidance_probe_lanes) OR EXISTS(SELECT 1 FROM guidance_probe_receipts) AS present`).get() as { present: number };
161
172
  if (row.present !== 0 && row.present !== 1) return fail("storage");
162
173
  return row.present === 1;
163
174
  } catch (error) { if (error instanceof GuidanceProbeError) throw error; return fail("storage"); }
@@ -204,10 +215,12 @@ export class GuidanceProbeStore {
204
215
  || !["planned", "reserved", "running", "failed_known", "closed_fixture", "not_needed", "unknown_held"].includes(session.state)
205
216
  || session.candidateArtifactSha256 !== null && !probeSha256(session.candidateArtifactSha256)) return fail("storage");
206
217
  const fields = Object.keys(session);
207
- if (fields.some(name => !["slotId", "generation", "revision", "state", "candidateArtifactSha256", "child", "host", "effect", "start", "coverage"].includes(name))
218
+ if (fields.some(name => !["slotId", "generation", "revision", "state", "candidateArtifactSha256", "child", "host", "effect", "start", "coverage", "closeCause"].includes(name))
219
+ || session.closeCause !== undefined && !["none", "cancel", "elapsed", "hold", "crash"].includes(session.closeCause)
208
220
  || !Object.hasOwn(session, "effect") || ["planned", "not_needed"].includes(session.state)
209
221
  && (session.effect !== null || session.host !== undefined || session.child !== undefined || session.start !== undefined || session.generation !== 0 || session.revision !== 0 || session.candidateArtifactSha256 !== null)
210
- || !session.coverage || Object.keys(session.coverage).sort().join(",") !== Object.keys(sessionCoverage(undefined)).sort().join(",")
222
+ || !session.coverage || Object.keys(session.coverage).filter(name => name !== "tokensObserved").sort().join(",") !== Object.keys(sessionCoverage(undefined)).filter(name => name !== "tokensObserved").sort().join(",")
223
+ || session.coverage.tokensObserved !== undefined && !probeInteger(session.coverage.tokensObserved)
211
224
  || !probeInteger(session.coverage.inputFrameBytes) || session.coverage.inputFrameSha256 !== null && !probeSha256(session.coverage.inputFrameSha256)
212
225
  || ["launchExposed", "preLaunchFailure", "usageUnknown", "coverageVerified"].some(name => typeof session.coverage[name as keyof ProbeSessionCoverage] !== "boolean")
213
226
  || ["modelCalls", "modelUsageKnown", "toolCalls", "toolUsageKnown"].some(name => !probeInteger(session.coverage[name as keyof ProbeSessionCoverage]))
@@ -463,7 +476,7 @@ export class GuidanceProbeStore {
463
476
  if (input.observed === null) { state.counters.usageUnknown = true; if (session) session.coverage.usageUnknown = true; }
464
477
  else if (input.admission.unit === "model_calls") {
465
478
  state.counters.tokensObservedKnown = increment(state.counters.tokensObservedKnown, input.observed);
466
- if (session) session.coverage.modelUsageKnown = increment(session.coverage.modelUsageKnown);
479
+ if (session) { session.coverage.modelUsageKnown = increment(session.coverage.modelUsageKnown); session.coverage.tokensObserved = increment(session.coverage.tokensObserved ?? 0, input.observed); }
467
480
  if (input.admission.reservedTokens !== undefined && input.observed > input.admission.reservedTokens) state.counters.usageUnknown = true;
468
481
  } else if (input.admission.unit === "tool_calls") {
469
482
  if (session) session.coverage.toolUsageKnown = increment(session.coverage.toolUsageKnown);
@@ -501,6 +514,8 @@ export class GuidanceProbeStore {
501
514
  || session.coverage.launchExposed && !covered;
502
515
  session.coverage.coverageVerified = covered && !unknown;
503
516
  session.state = unknown ? "unknown_held" : input.outcome === "failed_known" ? "failed_known" : "closed_fixture"; session.candidateArtifactSha256 = input.candidateArtifactSha256;
517
+ // The settled session's own cause, fixed here: a later cancel, hold or other session can no longer change what its receipt says.
518
+ session.closeCause = state.cancelRequested || state.receipt.state === "closing" ? "cancel" : state.admissionHold === "elapsed" ? "elapsed" : unknown ? "hold" : "none";
504
519
  if (unknown) state.receipt.state = "unknown_held";
505
520
  else {
506
521
  this.db.query("UPDATE guidance_probe_lanes SET slot_id=NULL WHERE project=? AND manifest_id=? AND slot_id=?").run(input.reservation.key.projectKey, input.reservation.key.id, session.slotId);
@@ -523,7 +538,7 @@ export class GuidanceProbeStore {
523
538
  || session.effect !== null || state.counters.usageUnknown || state.admissionHold !== "none" || state.cancelRequested || state.receipt.state === "closing") return fail("held");
524
539
  if (this.clockLost(reservation.key, state, now)) return receipt(state);
525
540
  elapsed(state, now);
526
- session.coverage.preLaunchFailure = true; session.state = "failed_known"; session.candidateArtifactSha256 = null;
541
+ session.coverage.preLaunchFailure = true; session.state = "failed_known"; session.candidateArtifactSha256 = null; session.closeCause = "none";
527
542
  this.db.query("UPDATE guidance_probe_lanes SET slot_id=NULL WHERE project=? AND manifest_id=? AND slot_id=?").run(reservation.key.projectKey, reservation.key.id, session.slotId);
528
543
  const index = state.sessions.indexOf(session), failed = state.registration.manifest.slots[index + 1]?.retryOf !== session.slotId;
529
544
  if (failed) {
@@ -554,6 +569,288 @@ export class GuidanceProbeStore {
554
569
  hold(state, reason); advance(state); this.save(reservation.key, state); return receipt(state);
555
570
  });
556
571
  }
572
+ // ---- T3 (#1226): host-observed receipts. Contract: docs/design/guidance-probes.md "T3 receipts, reconcile and cleanup contract". ----
573
+
574
+ /** Bounded, validated hydration of every sealed receipt of one experiment. A malformed, edited or misplaced row is storage corruption, never skipped. */
575
+ private readReceipts(key: ProbeKey): ProbeReceiptV1[] {
576
+ const rows = this.db.query(`SELECT CASE WHEN typeof(slot_id)='text' AND length(CAST(slot_id AS BLOB))<=256 THEN slot_id END AS slot_id,
577
+ CASE WHEN typeof(body)='text' AND length(CAST(body AS BLOB))<=${PROBE_RECEIPT_ROW_BYTES} THEN body END AS body FROM guidance_probe_receipts
578
+ WHERE project=? AND manifest_id=? ORDER BY slot_id LIMIT ?`).all(key.projectKey, key.id, GUIDANCE_PROBE_LIMITS.slots + 1) as Row[];
579
+ if (rows.length > GUIDANCE_PROBE_LIMITS.slots) return fail("storage");
580
+ const experiment = this.db.query("SELECT experiment FROM guidance_probe_manifests WHERE project=? AND id=?").get(key.projectKey, key.id) as Row | null;
581
+ const sealed = rows.map(row => {
582
+ if (typeof row.slot_id !== "string" || typeof row.body !== "string") return fail("storage");
583
+ const value = parseProbeReceipt(JSON.parse(row.body));
584
+ if (!value || value.slotId !== row.slot_id || !experiment || value.experimentId !== experiment.experiment) return fail("storage");
585
+ return value;
586
+ });
587
+ return sealed;
588
+ }
589
+ /** Every sealed receipt of an experiment, cross-checked against the session rows it describes. Read-only: it never repairs. */
590
+ receipts(key: ProbeKey): ProbeReceiptV1[] {
591
+ try {
592
+ return this.db.transaction(() => {
593
+ const state = this.readStored(key); if (!state) return [];
594
+ const sealed = this.readReceipts(key);
595
+ for (const value of sealed) {
596
+ const session = state.sessions.find(item => item.slotId === value.slotId);
597
+ // A receipt describes a session that reached a settled state, at the generation and revision it was reserved at.
598
+ const settled = session && !["planned", "not_needed", "reserved", "running"].includes(session.state);
599
+ // A receipt describes a settled session at the generation AND revision it was reserved at, and its state must be one that session could produce.
600
+ if (!session || !settled || value.generation !== session.generation || value.revision !== session.revision
601
+ || value.state === "succeeded" && (session.state !== "closed_fixture" || !session.coverage.coverageVerified)
602
+ || value.state === "failed" && session.state !== "failed_known"
603
+ || value.state === "unavailable" && !["failed_known", "unknown_held"].includes(session.state)) return fail("storage");
604
+ }
605
+ return sealed;
606
+ })();
607
+ } catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
608
+ }
609
+ /**
610
+ * Seal one finished session's receipt, once. It carries only what the host measured; the Store adds the fields only it can know (the trusted-clock
611
+ * span, the experiment's runtime fingerprints) and decides the final state, so a caller can ask for a success but never force one. Identical content
612
+ * replays as the stored receipt; different content for a sealed slot latches the observation hold. There is no update path.
613
+ */
614
+ sealReceipt(reservation: ProbeReservation, measured: ProbeMeasuredSession): ProbeReceiptV1 {
615
+ // A conflicting replay must persist its hold, and a throw inside the transaction would roll that back. So the transaction returns the conflict
616
+ // as a value and the refusal is raised only after the hold has committed.
617
+ const result = this.transaction(() => this.sealWithin(reservation, measured));
618
+ if (result === "conflict") return fail("held");
619
+ return result;
620
+ }
621
+ /**
622
+ * Settle a session and seal its receipt in ONE `BEGIN IMMEDIATE` transaction, so a settled session never exists without its receipt and no state
623
+ * between the two is visible. Anything that fails inside (including the seal) rolls the settlement back too: the session stays reserved or running,
624
+ * which the explicit reconcile at daemon start records as unknown. The caller may then settle it as unknown with a fallback measurement.
625
+ */
626
+ settleAndSeal(input: ProbeSessionSettlement, usage: "known_fixture" | "unknown", measured: ProbeMeasuredSession): { receipt: ProbeReceipt; sealed: ProbeReceiptV1 | undefined } {
627
+ const result = this.transaction(() => {
628
+ const settled = this.settleObservedSession(input, usage);
629
+ const session = this.get(input.reservation.key).sessions.find(item => item.slotId === input.reservation.slotId);
630
+ // A settlement that only latched a hold (a lost clock) leaves the session running: there is nothing to seal yet, the hold stays committed, and the
631
+ // explicit reconcile at daemon start records the session as unknown.
632
+ if (!session || ["planned", "not_needed", "reserved", "running"].includes(session.state)) return { receipt: settled, sealed: undefined };
633
+ return { receipt: settled, sealed: this.sealWithin(input.reservation, measured) };
634
+ });
635
+ if (result.sealed === "conflict") return fail("held");
636
+ return { receipt: result.receipt, sealed: result.sealed };
637
+ }
638
+ /** The pre-launch variant: the host attests no launch happened, and the session settles as failed with an `unavailable` receipt in the same transaction. */
639
+ settlePreLaunchAndSeal(reservation: ProbeReservation, now: number, measured: ProbeMeasuredSession): { receipt: ProbeReceipt; sealed: ProbeReceiptV1 } {
640
+ const result = this.transaction(() => {
641
+ const settled = this.settlePreLaunchFailure(reservation, now);
642
+ return { receipt: settled, sealed: this.sealWithin(reservation, measured) };
643
+ });
644
+ if (result.sealed === "conflict") return fail("held");
645
+ return { receipt: result.receipt, sealed: result.sealed };
646
+ }
647
+ private sealWithin(reservation: ProbeReservation, measured: ProbeMeasuredSession): ProbeReceiptV1 | "conflict" {
648
+ {
649
+ const key = reservation.key, state = this.get(key);
650
+ const session = state.sessions.find(item => item.slotId === reservation.slotId);
651
+ if (!session || session.generation !== reservation.generation || session.revision !== reservation.revision || ["planned", "not_needed", "reserved", "running"].includes(session.state)) return fail("changed");
652
+ const manifest = state.registration.manifest;
653
+ const wallEnd = this.now();
654
+ const existing = this.readReceipts(key).find(item => item.slotId === reservation.slotId);
655
+ const built = this.buildReceipt(state, session, measured, wallEnd);
656
+ if (existing) {
657
+ const { digest: _a, ...left } = existing, { digest: _b, ...right } = built;
658
+ // Replays are allowed to differ only by the instant they were built at; every measured fact must match.
659
+ const { startedAt: _s1, endedAt: _e1, elapsedMs: _m1, expiresAt: _x1, ...stableLeft } = left;
660
+ const { startedAt: _s2, endedAt: _e2, elapsedMs: _m2, expiresAt: _x2, ...stableRight } = right;
661
+ if (canonical(stableLeft) === canonical(stableRight)) return existing;
662
+ hold(state, "observation"); advance(state); this.save(key, state);
663
+ return "conflict";
664
+ }
665
+ if (manifest.slots.every(slot => slot.id !== reservation.slotId)) return fail("changed");
666
+ // Only a receipt that reads back is written: one the hydration would refuse (a name past the bound, a record over the row bound) would turn a finished
667
+ // session into permanent storage corruption for its experiment. Refusing here keeps the settle atomic, and the host seals its conservative receipt instead.
668
+ if (!parseProbeReceipt(JSON.parse(canonical(built)))) return fail("invalid");
669
+ const retained = measured.retained ? parseProbeRetained(measured.retained) : undefined;
670
+ if (measured.retained && !retained) return fail("invalid");
671
+ this.db.query("INSERT INTO guidance_probe_receipts(project,manifest_id,slot_id,body,pruned,retained) VALUES(?,?,?,?,0,?)")
672
+ .run(key.projectKey, key.id, reservation.slotId, canonical(built), retained ? canonical(retained) : null);
673
+ return built;
674
+ }
675
+ }
676
+ private buildReceipt(state: Stored, session: Session, measured: ProbeMeasuredSession, wallEnd: number): ProbeReceiptV1 {
677
+ const manifest = state.registration.manifest, slot = manifest.slots.find(item => item.id === session.slotId)!;
678
+ // The session's own start, host-measured. It can never precede the experiment's first reservation or follow the end.
679
+ const first = state.firstReservedAt ?? wallEnd, endedAt = Math.max(wallEnd, first);
680
+ const startedAt = probeInteger(measured.startedAt) ? Math.min(Math.max(measured.startedAt, first), endedAt) : first;
681
+ const limits = new Set<ProbeReceiptLimit>(measured.limits);
682
+ const coverage = session.coverage;
683
+ // Derived from this session's settled facts, the manifest (immutable) and the host's measurement only. Mutable experiment state (running token totals,
684
+ // the current hold, a later cancel) is never read here, so an identical replay after another session ran is byte-identical.
685
+ const cause = session.closeCause ?? (session.state === "unknown_held" ? "hold" : "none");
686
+ if (coverage.usageUnknown || coverage.modelUsageKnown !== coverage.modelCalls || coverage.toolUsageKnown !== coverage.toolCalls) limits.add("usage_unknown");
687
+ if (measured.servedModel === null) limits.add("served_model_unobserved");
688
+ else if (measured.servedModel !== manifest.model.requested) limits.add("served_model_mismatch");
689
+ if (!measured.teardownVerified) limits.add("teardown_unverified");
690
+ if (measured.runtime === null) limits.add("coverage_unverified");
691
+ if (!coverage.coverageVerified) limits.add("coverage_unverified");
692
+ if (measured.output.excluded.length > 0) limits.add("output_truncated");
693
+ // The declared storage bound is the ceiling at runtime too: what the session left behind beyond it is a non-success and is never retained.
694
+ if (measured.scratchBytes > manifest.limits.scratchBytes || measured.output.totalBytes > manifest.limits.outputBytes) limits.add("storage_over_cap");
695
+ // Order matters: what the host cannot vouch for comes first. A session whose teardown was not verified, or that a crash left behind, is `unknown`
696
+ // whatever else is true of it (a cancel or an elapsed hold that was latched before the crash does not make it `cancelled` or `timed_out`).
697
+ let outcome: ProbeReceiptState;
698
+ if (!measured.teardownVerified || cause === "crash") outcome = "unknown";
699
+ else if (cause === "cancel" || measured.cancelled) outcome = "cancelled";
700
+ else if (cause === "elapsed" || measured.timedOut) outcome = "timed_out";
701
+ // `unavailable` means the session could not start. Once any model or tool call ran, a confinement error is a failure or an unknown, never unavailable.
702
+ else if (measured.unavailable && coverage.modelCalls === 0 && coverage.toolCalls === 0) outcome = "unavailable";
703
+ else if (session.state === "failed_known") outcome = "failed";
704
+ else if (session.state === "unknown_held") outcome = "unknown";
705
+ else outcome = "succeeded";
706
+ // A success needs every condition of the contract's Sealing section; any gap downgrades it, it never stays a success.
707
+ if (outcome === "succeeded" && (limits.size > 0 || measured.servedModel !== manifest.model.requested || session.state !== "closed_fixture")) outcome = "unknown";
708
+ const output = capOutput(measured.output, manifest.limits.outputBytes);
709
+ const body: Omit<ProbeReceiptV1, "digest"> = { v: 1, experimentId: manifest.experimentId, slotId: session.slotId, generation: session.generation, revision: session.revision,
710
+ requestedModel: manifest.model.requested, servedModel: measured.servedModel, inputFrameSha256: coverage.inputFrameSha256,
711
+ workerEffectiveInputSha256: slot.role === "worker" ? measured.workerEffectiveInputSha256 : null, nonGuidanceInputSha256: slot.role === "worker" ? measured.nonGuidanceInputSha256 : null,
712
+ guidanceSha256: slot.arm === "baseline" ? manifest.guidance.baselineSha256 : session.child?.guidanceSha256 ?? null,
713
+ // The host's own fingerprints at seal time, never the declaration's: copying the manifest would make a drifted runtime unrecordable. Null when unread.
714
+ runtimeSha256: measured.runtime?.runtimeSha256 ?? null, toolsetSha256: measured.runtime?.toolsetSha256 ?? null, modelConfigSha256: measured.runtime?.modelConfigSha256 ?? null,
715
+ startedAt, endedAt, elapsedMs: endedAt - startedAt, state: outcome,
716
+ usage: { modelCalls: coverage.modelCalls, modelUsageKnown: coverage.modelUsageKnown, toolCalls: coverage.toolCalls, toolUsageKnown: coverage.toolUsageKnown,
717
+ // This session's own observed tokens, not the experiment's running total. Unknown (null) when any call went unobserved or none was recorded.
718
+ tokensObserved: coverage.usageUnknown || coverage.modelUsageKnown !== coverage.modelCalls || coverage.tokensObserved === undefined ? null : coverage.tokensObserved },
719
+ limits: [...limits].sort(), output, expiresAt: endedAt + PROBE_RETENTION_MS };
720
+ return { ...body, digest: probeReceiptDigest(body) };
721
+ }
722
+ /**
723
+ * Read-only: where each sealed slot's retained output stands, as a state and never a path (a physical location is private to the host, and the producer
724
+ * export must not carry one). A slot with no row is absent from the map, which the reader reads as `none`.
725
+ */
726
+ retentionStates(key: ProbeKey): Map<string, "none" | "retained" | "pruned"> {
727
+ try {
728
+ return this.db.transaction(() => {
729
+ const result = new Map<string, "none" | "retained" | "pruned">();
730
+ for (const [slotId, entry] of this.retainedRows(key)) result.set(slotId, entry.pruned ? "pruned" : entry.record ? "retained" : "none");
731
+ return result;
732
+ })();
733
+ } catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
734
+ }
735
+ /** Private status: the outcome denominator and the comparability verdict with its reasons. Read-only; T4 decides what becomes public. */
736
+ outcome(key: ProbeKey): { counts: ProbeOutcomeCounts; comparability: ProbeComparability } | undefined {
737
+ try {
738
+ return this.db.transaction(() => {
739
+ const state = this.readStored(key); if (!state) return undefined;
740
+ const sealed = this.receipts(key), manifest = state.registration.manifest;
741
+ const slots = state.sessions.map((session, index) => ({ slotId: session.slotId, role: manifest.slots[index]!.role, arm: manifest.slots[index]!.arm,
742
+ reserved: !["planned", "not_needed"].includes(session.state), coverageVerified: session.coverage.coverageVerified, ...(session.child ? { authoring: session.child.authoring } : {}) }));
743
+ return { counts: probeOutcomeCounts(state.sessions, sealed),
744
+ comparability: classifyProbeComparability({ slots, receipts: sealed, runtime: manifest.runtime, holds: state.admissionHold !== "none" || state.counters.usageUnknown }) };
745
+ })();
746
+ } catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
747
+ }
748
+ /** Retained records of one experiment, validated. A row whose record does not parse is storage corruption. */
749
+ private retainedRows(key: ProbeKey): Map<string, { record: ProbeRetainedRecord | undefined; pruned: boolean }> {
750
+ const rows = this.db.query(`SELECT slot_id, pruned, CASE WHEN retained IS NULL OR (typeof(retained)='text' AND length(CAST(retained AS BLOB))<=${PROBE_RECEIPT_ROW_BYTES}) THEN retained END AS retained,
751
+ (retained IS NULL OR (typeof(retained)='text' AND length(CAST(retained AS BLOB))<=${PROBE_RECEIPT_ROW_BYTES})) AS retained_valid
752
+ FROM guidance_probe_receipts WHERE project=? AND manifest_id=? LIMIT ?`).all(key.projectKey, key.id, GUIDANCE_PROBE_LIMITS.slots + 1) as Row[];
753
+ const result = new Map<string, { record: ProbeRetainedRecord | undefined; pruned: boolean }>();
754
+ for (const row of rows) {
755
+ if (typeof row.slot_id !== "string" || (row.pruned !== 0 && row.pruned !== 1) || row.retained_valid !== 1) return fail("storage");
756
+ const record = row.retained === null ? undefined : parseProbeRetained(JSON.parse(row.retained as string));
757
+ if (row.retained !== null && !record) return fail("storage");
758
+ result.set(row.slot_id, { record, pruned: row.pruned === 1 });
759
+ }
760
+ return result;
761
+ }
762
+ /**
763
+ * Read-only: exactly what a prune would remove now and why anything is kept. An active, held, closing or unfinished experiment is never prunable,
764
+ * and an output is prunable only after its own `expiresAt`. The digest binds this plan; `prune` refuses any other.
765
+ */
766
+ previewPrune(key: ProbeKey, fs: ProbeRetentionFs): ProbePrunePlan {
767
+ try {
768
+ return this.db.transaction(() => {
769
+ // Expiry is decided on the Store's own trusted clock, never a caller's: a caller cannot pull a retention date forward.
770
+ const now = this.now();
771
+ const state = this.readStored(key); if (!state) return fail("changed");
772
+ const sealed = this.receipts(key), retained = this.retainedRows(key);
773
+ // Prunable once no session is in flight and the experiment is finished: terminal, or stopped by the person's or conductor's cancel (a crash-reconciled
774
+ // or hold-latched experiment is `unknown_held` until then). `usageUnknown` alone never blocks: it describes the measurements, not whether work is running.
775
+ const inFlight = state.sessions.some(item => ["reserved", "running"].includes(item.state));
776
+ const finished = ["closed_fixture", "failed_fixture"].includes(state.receipt.state) || state.cancelRequested;
777
+ const blocked: ProbePruneKeepReason | undefined = inFlight ? "experiment_active" : finished ? undefined : state.receipt.state === "unknown_held" ? "experiment_held" : "experiment_active";
778
+ const slots = sealed.map(receipt => {
779
+ const entry = retained.get(receipt.slotId);
780
+ const none = (reason: ProbePruneKeepReason) => ({ slotId: receipt.slotId, expiresAt: receipt.expiresAt, remove: [] as { relative: string; bytes: number }[], keep: [{ relative: ".", reason }] });
781
+ if (!entry?.record) return none("no_retained_output");
782
+ if (entry.pruned) return none("already_pruned");
783
+ if (blocked) return none(blocked);
784
+ if (now < receipt.expiresAt) return none("not_expired");
785
+ const seen = fs.preview(entry.record);
786
+ return { slotId: receipt.slotId, expiresAt: receipt.expiresAt, remove: seen.remove, keep: seen.keep.map(item => ({ relative: item.relative, reason: item.reason as ProbePruneKeepReason })) };
787
+ });
788
+ const body = { key, slots };
789
+ return { digest: probeHash(canonical(body)), retainedBytes: slots.reduce((sum, item) => sum + item.remove.reduce((n, file) => n + file.bytes, 0), 0), slots };
790
+ })();
791
+ } catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
792
+ }
793
+ /**
794
+ * Remove retained output and workspace bytes only, never a receipt or a manifest. Takes the digest of the plan the person saw and refuses if the owned
795
+ * set has changed since. Each slot is marked pruned only after its files were removed; a file kept for a changed identity keeps the slot retained.
796
+ */
797
+ prune(key: ProbeKey, planDigest: string, fs: ProbeRetentionFs): ProbePruneResult {
798
+ if (!probeSha256(planDigest)) return fail("invalid");
799
+ const outcome = this.transaction(() => {
800
+ const plan = this.previewPrune(key, fs);
801
+ if (plan.digest !== planDigest) return fail("changed");
802
+ const retained = this.retainedRows(key), pruned: string[] = [], kept: { slotId: string; relative: string; reason: ProbePruneKeepReason }[] = [];
803
+ for (const slot of plan.slots) {
804
+ const entry = retained.get(slot.slotId);
805
+ if (slot.remove.length === 0 || !entry?.record) { for (const item of slot.keep) kept.push({ slotId: slot.slotId, ...item }); continue; }
806
+ const removed = fs.remove(entry.record);
807
+ for (const item of removed.kept) kept.push({ slotId: slot.slotId, relative: item.relative, reason: item.reason as ProbePruneKeepReason });
808
+ if (removed.kept.length === 0) {
809
+ this.db.query("UPDATE guidance_probe_receipts SET pruned=1 WHERE project=? AND manifest_id=? AND slot_id=?").run(key.projectKey, key.id, slot.slotId);
810
+ pruned.push(slot.slotId);
811
+ }
812
+ }
813
+ return { pruned, kept, planDigest };
814
+ });
815
+ return outcome;
816
+ }
817
+
818
+ /**
819
+ * Explicit, idempotent crash reconcile, called once by the host at daemon start. A session left reserved or running by a crash is recorded as
820
+ * unknown_held with an unknown receipt: the host cannot vouch for it. It never launches, retries or restarts anything, and a second call writes nothing.
821
+ * Opening the Store and every read never write; this is the only path that does. One bad experiment never hides the others: every key is visited, a
822
+ * failure is handed to `onFailure` (the host logs its cause) and the loop moves on, and with no callback the first failure is thrown only AFTER every key was
823
+ * tried, so a caller can never mistake a partial pass for a full one.
824
+ */
825
+ reconcile(now: number = this.now(), onFailure?: (key: ProbeKey | undefined, error: unknown) => void): { reconciled: number; failed: number } {
826
+ let reconciled = 0, failed = 0, first: unknown;
827
+ const note = (key: ProbeKey | undefined, error: unknown): void => { failed++; first ??= error; onFailure?.(key, error); };
828
+ const keys = this.db.query(`SELECT CASE WHEN typeof(project)='text' AND length(CAST(project AS BLOB))<=256 THEN project END AS projectKey,
829
+ CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=64 THEN id END AS id FROM guidance_probe_manifests ORDER BY project,id`).all() as ProbeKey[];
830
+ for (const key of keys) {
831
+ if (typeof key.projectKey !== "string" || !probeSha256(key.id)) { try { fail("storage"); } catch (error) { note(undefined, error); } continue; }
832
+ try { reconciled += this.transaction(() => {
833
+ const state = this.get(key); let count = 0;
834
+ const sealed = new Set(this.readReceipts(key).map(item => item.slotId));
835
+ for (const session of state.sessions) {
836
+ if (!["reserved", "running"].includes(session.state) || sealed.has(session.slotId)) continue;
837
+ session.state = "unknown_held"; session.closeCause = "crash"; session.coverage.coverageVerified = false; session.coverage.usageUnknown = true;
838
+ state.counters.usageUnknown = true; state.receipt.state = "unknown_held";
839
+ if (state.admissionHold === "none") state.admissionHold = "usage";
840
+ this.save(key, state);
841
+ const built = this.buildReceipt(state, session, { startedAt: now, servedModel: null, workerEffectiveInputSha256: null, nonGuidanceInputSha256: null, teardownVerified: false, runtime: null,
842
+ cancelled: false, timedOut: false, unavailable: false, limits: ["teardown_unverified"], scratchBytes: 0, output: { v: 1, entries: [], excluded: [], totalBytes: 0 } }, Math.max(now, state.lastWall ?? 0));
843
+ this.db.query("INSERT INTO guidance_probe_receipts(project,manifest_id,slot_id,body,pruned) VALUES(?,?,?,?,0)").run(key.projectKey, key.id, session.slotId, canonical(built));
844
+ count++;
845
+ }
846
+ if (count > 0) { advance(state); this.save(key, state); }
847
+ return count;
848
+ }); } catch (error) { note(key, error); }
849
+ }
850
+ if (failed > 0 && !onFailure) throw first;
851
+ return { reconciled, failed };
852
+ }
853
+
557
854
  /** Recovery only. O(historical experiments + <=9 sessions each); future keyset/budget upgrade if measured slow. */
558
855
  integrity(): ProbeIntegrity {
559
856
  try { return this.db.transaction(() => this.integritySnapshot())(); }
@@ -570,8 +867,11 @@ export class GuidanceProbeStore {
570
867
  for (const component of [key, state.registration.manifest, state.binding, state.counters, state.receipt,
571
868
  { firstReservedAt: state.firstReservedAt, lastWall: state.lastWall, admissionHold: state.admissionHold, cancelRequested: state.cancelRequested }]) digest.update(canonical(component)).update("\n");
572
869
  for (const session of state.sessions) digest.update(sessionCanonical(session)).update("\n");
870
+ // `receipts` also cross-checks each row against its session (generation, revision, state), so a receipt moved or edited to fit another session fails here.
871
+ for (const sealed of this.receipts(key)) digest.update(sealed.digest).update("\n");
573
872
  }
574
- const orphan = this.db.query(`SELECT EXISTS(SELECT 1 FROM guidance_probe_sessions s LEFT JOIN guidance_probe_manifests m ON m.project=s.project AND m.id=s.manifest_id WHERE m.id IS NULL)
873
+ const orphan = this.db.query(`SELECT EXISTS(SELECT 1 FROM guidance_probe_receipts r LEFT JOIN guidance_probe_manifests m ON m.project=r.project AND m.id=r.manifest_id WHERE m.id IS NULL)
874
+ OR EXISTS(SELECT 1 FROM guidance_probe_sessions s LEFT JOIN guidance_probe_manifests m ON m.project=s.project AND m.id=s.manifest_id WHERE m.id IS NULL)
575
875
  OR EXISTS(SELECT 1 FROM guidance_probe_lanes l LEFT JOIN guidance_probe_manifests m ON m.project=l.project AND m.id=l.manifest_id WHERE m.id IS NULL) AS invalid`).get() as { invalid: number };
576
876
  if (orphan.invalid) return fail("storage");
577
877
  for (const lane of this.lanes()) digest.update(canonical(lane)).update("\n");
@@ -579,6 +879,12 @@ export class GuidanceProbeStore {
579
879
  }
580
880
  }
581
881
 
882
+ /** What the host can honestly say about a session whose adapter measured nothing: it never saw teardown or the runtime, so it cannot vouch for it. */
883
+ function unmeasuredSession(startedAt: number, servedModel: string | null): ProbeMeasuredSession {
884
+ return { startedAt, servedModel, workerEffectiveInputSha256: null, nonGuidanceInputSha256: null, teardownVerified: false, runtime: null, cancelled: false, timedOut: false,
885
+ unavailable: false, limits: ["teardown_unverified"], scratchBytes: 0, output: { v: 1, entries: [], excluded: [], totalBytes: 0 } };
886
+ }
887
+
582
888
  /** Host test composition only. No wire/config runner selection or independent caller authority. */
583
889
  export class GuidanceProbeFixtureHost {
584
890
  constructor(private readonly store: GuidanceProbeStore, private readonly options: {
@@ -618,6 +924,14 @@ export class GuidanceProbeFixtureHost {
618
924
  const result = this.store.reserveSession({ ...input, preparedFrame }, this.options.revalidate);
619
925
  if (result.kind === "existing") return result.receipt;
620
926
  const reservation = result.reservation;
927
+ // Output the port retained for a measurement that is not sealed with its record has no row, so no prune could ever reach it: it is discarded by the port,
928
+ // by the identity the port captured. It never throws into the host and never touches a record the port did not create.
929
+ let observed: ProbeFakeObservation | undefined, sealedRetained = false;
930
+ const discard = (): void => {
931
+ const retained = observed?.measured?.retained;
932
+ if (!retained || sealedRetained) return;
933
+ try { ports.discardRetained?.(retained); } catch { /* the port's own identity check is the only authority; a failure leaves the directory, never a wrong delete */ }
934
+ };
621
935
  try {
622
936
  this.options.onReserved?.(reservation);
623
937
  const state = this.store.read(input.key)!;
@@ -634,6 +948,8 @@ export class GuidanceProbeFixtureHost {
634
948
  },
635
949
  });
636
950
  if (signal.aborted || this.store.exposeLaunch(reservation, this.options.revalidate).state !== "active" || signal.aborted) return fail("held");
951
+ // The session's own start on the trusted clock, taken where the launch was exposed. It is the host's sample, never the adapter's.
952
+ const startedAt = this.options.now();
637
953
  let launch: { kind: "observed"; observation: ProbeFakeObservation } | { kind: "failed"; error: unknown };
638
954
  try {
639
955
  const launched = ports.launch({ reservation, slot, manifest: state.registration.manifest,
@@ -654,14 +970,29 @@ export class GuidanceProbeFixtureHost {
654
970
  await Promise.allSettled([...pendingEffects]);
655
971
  if (launch.kind === "failed") throw launch.error;
656
972
  const observation = launch.observation;
973
+ observed = observation;
657
974
  const matched = this.matchObservation(observation, reservation, frame, slot.role === "worker");
658
975
  if (!matched) this.store.latchHold(reservation, "observation");
659
- return this.store.settleObservedSession({ reservation, outcome: matched ? observation.outcome : "unknown",
660
- candidateArtifactSha256: matched ? observation.candidateArtifactSha256 : null, now: this.options.now() }, matched ? observation.usage : "unknown");
976
+ // Settlement and receipt are one transaction (the contract's Sealing step 3): a session is never visible as settled without its receipt. An
977
+ // observation that carries no measurement, or that did not match, is sealed with the conservative one: teardown not verified, nothing observed.
978
+ const measured: ProbeMeasuredSession = matched && observation.measured ? { ...observation.measured, startedAt } : unmeasuredSession(startedAt, matched ? observation.servedModel : null);
979
+ const settled = this.store.settleAndSeal({ reservation, outcome: matched ? observation.outcome : "unknown",
980
+ candidateArtifactSha256: matched ? observation.candidateArtifactSha256 : null, now: this.options.now() }, matched ? observation.usage : "unknown", measured);
981
+ // Sealed with its own record: the receipt row now owns the directory. Anything else (an unmatched observation sealed conservatively, or a settlement that
982
+ // latched a lost clock and sealed nothing) leaves the directory with no owner, so it is discarded.
983
+ sealedRetained = matched && settled.sealed !== undefined && measured.retained !== undefined;
984
+ discard();
985
+ return settled.receipt;
661
986
  } catch {
987
+ discard();
662
988
  const saved = this.store.read(input.key)?.sessions.find(item => item.slotId === reservation.slotId);
663
- if (saved && !saved.coverage.launchExposed) this.store.settlePreLaunchFailure(reservation, this.options.now());
664
- else this.store.settleObservedSession({ reservation, outcome: "unknown", candidateArtifactSha256: null, now: this.options.now() }, "unknown");
989
+ // A failed atomic settle rolled the settlement and the receipt back together, so the session is still open here. Settle it as unknown WITH its
990
+ // conservative receipt; if even that cannot be written, latch the observation hold so the experiment cannot present a clean result. A session left
991
+ // open is recorded as unknown by the explicit reconcile at daemon start.
992
+ try {
993
+ if (saved && !saved.coverage.launchExposed) this.store.settlePreLaunchAndSeal(reservation, this.options.now(), { ...unmeasuredSession(this.options.now(), null), unavailable: true });
994
+ else this.store.settleAndSeal({ reservation, outcome: "unknown", candidateArtifactSha256: null, now: this.options.now() }, "unknown", unmeasuredSession(this.options.now(), null));
995
+ } catch { try { this.store.latchHold(reservation, "observation"); } catch { /* the reconcile at daemon start is the last net */ } }
665
996
  throw new GuidanceProbeError("held");
666
997
  }
667
998
  }