@staix/agent-hub 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +802 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +11 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +112 -148
  19. package/docs/quickstart.md +9 -3
  20. package/docs/research.md +1 -1
  21. package/docs/sdlc.md +5 -3
  22. package/docs/security.md +21 -1
  23. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  24. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  25. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  26. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  27. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  29. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  30. package/docs/verified.json +24 -24
  31. package/package.json +3 -4
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +2373 -1436
  34. package/plugins/agent-hub/server.js +2445 -1497
  35. package/src/adapters/channel-peer.ts +7 -1
  36. package/src/adapters/compat.ts +1 -1
  37. package/src/adapters/local-probe.ts +174 -0
  38. package/src/adapters/local-worker.ts +232 -21
  39. package/src/cli/console-state.ts +25 -6
  40. package/src/cli/console-versions.ts +99 -0
  41. package/src/cli/console.ts +13 -1
  42. package/src/cli/help.ts +2 -1
  43. package/src/cli/install-paths.ts +7 -2
  44. package/src/cli/main.ts +60 -4
  45. package/src/cli/runtime-version-warning.ts +2 -2
  46. package/src/cli/sdlc-output.ts +9 -5
  47. package/src/hub/config-apply.ts +4 -2
  48. package/src/hub/config-trust.ts +6 -1
  49. package/src/hub/control-client.ts +5 -2
  50. package/src/hub/daemon.ts +169 -9
  51. package/src/hub/events.ts +3 -2
  52. package/src/hub/guidance-probe-store.ts +713 -0
  53. package/src/hub/guidance-probes.ts +358 -0
  54. package/src/hub/inference.ts +18 -5
  55. package/src/hub/operational-authority.ts +13 -1
  56. package/src/hub/peers.ts +5 -0
  57. package/src/hub/ports.ts +1 -1
  58. package/src/hub/progress.ts +23 -16
  59. package/src/hub/report.ts +2 -0
  60. package/src/hub/research.ts +1 -0
  61. package/src/hub/restart.ts +7 -0
  62. package/src/hub/sdlc-release-authorization.ts +139 -17
  63. package/src/hub/sdlc-release-policy.ts +100 -0
  64. package/src/hub/sdlc-release.ts +59 -7
  65. package/src/hub/tasks.ts +317 -6
  66. package/src/local/probe-errors.ts +28 -0
  67. package/src/local/probe-sandbox.ts +224 -0
  68. package/src/local/probe-types.ts +108 -0
  69. package/src/local/probe-workspace.ts +237 -0
  70. package/src/local/sandbox.ts +71 -2
  71. package/src/local/tools.ts +135 -9
  72. package/src/models/route/advisor-trigger.ts +88 -0
  73. package/src/models/route/config.ts +21 -17
  74. package/src/models/route/conversation-view.ts +179 -0
  75. package/src/models/route/decision-evidence.ts +1 -1
  76. package/src/models/route/decision.ts +114 -19
  77. package/src/models/route/escalation-control.ts +30 -0
  78. package/src/models/route/hub-prompts.ts +97 -0
  79. package/src/models/route/judge-choice.ts +155 -0
  80. package/src/models/route/judge-replies.ts +102 -0
  81. package/src/models/route/labels.ts +14 -70
  82. package/src/models/route/observation-signals.ts +250 -0
  83. package/src/models/route/plan-execute-choice.ts +27 -0
  84. package/src/models/route/relay-selector.ts +2 -2
  85. package/src/models/route/runtime.ts +115 -52
  86. package/src/models/route/turn-state.ts +77 -0
  87. package/src/omniroute/client.ts +3 -0
  88. package/src/ui/plugin.ts +70 -20
  89. package/src/version.ts +4 -0
  90. package/templates/adec/README.md +32 -0
  91. package/templates/adec/ahub.plan-execute.json +23 -0
  92. package/templates/adec/ahub.stage.json +23 -0
  93. package/LICENSES/Apache-2.0.txt +0 -204
  94. package/src/models/route/advisor.ts +0 -102
  95. package/src/models/route/escalation.ts +0 -82
  96. package/src/models/route/judge.ts +0 -23
  97. package/src/models/route/normalize.ts +0 -103
  98. package/src/models/route/plan-execute.ts +0 -52
  99. package/src/models/route/prompts.ts +0 -8
  100. package/src/models/route/signals.ts +0 -247
  101. package/src/models/route/state.ts +0 -54
  102. package/src/models/route/text.ts +0 -61
@@ -0,0 +1,713 @@
1
+ import { openHubDatabase, type Database } from "./db-schema.ts";
2
+ import { createHash } from "node:crypto";
3
+ import { GUIDANCE_ROLE_MAX_BYTES } from "./guidance-variants.ts";
4
+ import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
5
+ import { GUIDANCE_PROBE_LIMITS, GUIDANCE_PROBE_SESSION_BYTES, GUIDANCE_PROBE_MODEL, GuidanceProbeError, guidanceProbeCanonical, guidanceProbeManifestKey,
6
+ parseGuidanceProbeRegistration, guidanceProbeWorkerFrame, guidanceProbeNonGuidanceInputHash, probeHash, probeInteger, probeSha256, probeSessionGeneration,
7
+ type ProbeRegistrationV1, type ProbeHostBinding, type ProbeKey, type ProbeReceipt, type ProbeStoredState,
8
+ type ProbeCounters, type ProbeSession, type ProbeSessionAdmission, type ProbeAdmissionRecheck,
9
+ type ProbeReservation, type ProbeReservationResult, type ProbeEffectAdmission, type ProbeEffectAdmissionResult,
10
+ type ProbeEffectSettlement, type ProbeSessionSettlement, type ProbeUsageObservation, type ProbeCancellation,
11
+ type ProbeIntegrity, type ProbeChildBinding, type GuidanceProbeFakePorts, type ProbeFakeEffects,
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";
14
+
15
+ interface Effect { admission: ProbeEffectAdmission; state: "pending" | "settled" | "unknown"; usageHash: string | null; observed: number | null }
16
+ interface Session extends ProbeSession { host?: ProbeHostBinding; effect: Effect | null }
17
+ interface EffectLifetime { open(): boolean; track(): () => void }
18
+ interface Stored extends Omit<ProbeStoredState, "sessions"> { sessions: Session[]; lastWall: number | null }
19
+ interface Lane { project: string; manifestId: string; slotId: string | null }
20
+ type Row = Record<string, unknown>;
21
+ const fail = (reason: ConstructorParameters<typeof GuidanceProbeError>[0]): never => { throw new GuidanceProbeError(reason); };
22
+ const canonical = guidanceProbeCanonical;
23
+ function sessionCanonical(session: Session): string {
24
+ if (session.host) canonical(session.host);
25
+ if (session.child) canonical(session.child);
26
+ if (session.effect) canonical(session.effect);
27
+ const { host: _host, child: _child, effect: _effect, ...metadata } = session; canonical(metadata);
28
+ return canonical(session, GUIDANCE_PROBE_SESSION_BYTES);
29
+ }
30
+ const same = (a: unknown, b: unknown): boolean => canonical(a) === canonical(b);
31
+ const sameAdmission = (a: ProbeEffectAdmission, b: ProbeEffectAdmission): boolean => {
32
+ const { now: _a, ...left } = a, { now: _b, ...right } = b; return same(left, right);
33
+ };
34
+ const sameChild = (a: ProbeChildBinding | undefined, b: ProbeChildBinding | undefined): boolean => {
35
+ if (!a || !b) return a === b;
36
+ const { authoring: _a, sourceSessionId: _b, ...left } = a, { authoring: _c, sourceSessionId: _d, ...right } = b;
37
+ return same(left, right);
38
+ };
39
+ const taskEpoch = (a: ProbeHostBinding, b: ProbeHostBinding): boolean => a.projectKey === b.projectKey && a.task.id === b.task.id && a.task.created === b.task.created;
40
+ const invariant = (a: ProbeHostBinding, b: ProbeHostBinding): boolean => taskEpoch(a, b) && same(a.task, b.task) && same(a.role, b.role) && a.baselineGuidance === b.baselineGuidance;
41
+ const checkedInteger = (value: unknown): number => probeInteger(value) ? value : fail("storage");
42
+ const checkedHash = (value: unknown): string => probeSha256(value) ? value : fail("storage");
43
+ function json<T>(value: unknown): T { if (typeof value !== "string") return fail("storage"); return JSON.parse(value) as T; }
44
+ function host(value: ProbeHostBinding): void {
45
+ canonical(value);
46
+ if (!value || typeof value.actor !== "string" || !value.actor || !probeSessionGeneration(value.sessionGeneration)
47
+ || !executionText(value.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
48
+ || typeof value.baselineGuidance !== "string" || Buffer.byteLength(value.baselineGuidance) > GUIDANCE_ROLE_MAX_BYTES
49
+ || !probeSha256(value.role?.baselineSha256) || !probeInteger(value.task?.id) || value.task.id === 0
50
+ || !probeInteger(value.task.created) || !probeInteger(value.task.flowRevision)) fail("changed");
51
+ }
52
+ const counters = (): ProbeCounters => ({ workerAttempts: 0, editorAttempts: 0, modelCalls: 0, toolCalls: 0,
53
+ tokensReserved: 0, tokensObservedKnown: 0, inputBytes: 0, scratchBytes: 0, outputBytes: 0,
54
+ elapsedHighWaterMs: 0, usageUnknown: false });
55
+ const sessionCoverage = (frame: ProbePreparedFrame | undefined): ProbeSessionCoverage => ({
56
+ 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,
58
+ });
59
+ const receipt = (state: Stored, already = false): ProbeReceipt => ({ ...state.receipt, already });
60
+ const advance = (state: Stored): void => { state.receipt.revision = increment(state.receipt.revision); };
61
+ function hold(state: Stored, reason: Exclude<Stored["admissionHold"], "none">): void {
62
+ if (state.admissionHold === "none") state.admissionHold = reason;
63
+ state.receipt.state = "unknown_held";
64
+ if (reason !== "elapsed") state.counters.usageUnknown = true;
65
+ }
66
+ function increment(value: number, amount = 1): number { if (!probeInteger(value) || !probeInteger(amount) || amount > Number.MAX_SAFE_INTEGER - value) return fail("budget"); return value + amount; }
67
+ function charge(state: Stored, name: keyof Omit<ProbeCounters, "usageUnknown">, amount: number, maximum: number): void {
68
+ const next = increment(state.counters[name], amount); if (next > maximum) fail("budget"); state.counters[name] = next;
69
+ }
70
+ /** Closed host-only resource reservation, copied before authority callbacks or effects. */
71
+ function resourceCharges(value: unknown, reason: "invalid" | "storage" = "invalid"): ProbeResourceCharges | undefined {
72
+ if (value === undefined) return undefined;
73
+ try {
74
+ const copied: unknown = JSON.parse(canonical(value));
75
+ if (!copied || typeof copied !== "object" || Array.isArray(copied)) return fail(reason);
76
+ const fields = copied as Record<string, unknown>;
77
+ if (Object.keys(fields).some(name => !["inputBytes", "scratchBytes", "outputBytes"].includes(name))
78
+ || Object.values(fields).some(amount => !probeInteger(amount))) return fail(reason);
79
+ return fields as ProbeResourceCharges;
80
+ } catch { return fail(reason); }
81
+ }
82
+ function chargeResources(state: Stored, extra: ProbeResourceCharges | undefined): void {
83
+ if (!extra) return;
84
+ for (const name of ["inputBytes", "scratchBytes", "outputBytes"] as const) {
85
+ const amount = extra[name];
86
+ if (amount !== undefined) charge(state, name, amount, state.registration.manifest.limits[name]);
87
+ }
88
+ if (state.counters.scratchBytes > GUIDANCE_PROBE_LIMITS.storageBytes - state.counters.outputBytes) fail("budget");
89
+ }
90
+ function elapsed(state: Stored, now: number, first = false): void {
91
+ if (!probeInteger(now) || state.lastWall !== null && now < state.lastWall) fail("held");
92
+ if (state.firstReservedAt === null && first) state.firstReservedAt = now;
93
+ if (state.firstReservedAt !== null) {
94
+ const age = now - state.firstReservedAt;
95
+ if (!probeInteger(age) || age < state.counters.elapsedHighWaterMs || age > state.registration.manifest.limits.elapsedMs) fail("budget");
96
+ state.counters.elapsedHighWaterMs = age;
97
+ }
98
+ state.lastWall = now;
99
+ }
100
+ function boundChild(state: Stored, input: ProbeSessionAdmission, session: Session): void {
101
+ const slot = state.registration.manifest.slots.find(item => item.id === session.slotId)!;
102
+ if (slot.role !== "worker" || slot.arm === "baseline") { if (input.child) fail("changed"); return; }
103
+ const child = input.child;
104
+ if (!child || !probeSha256(child.variantId) || !probeSha256(child.candidateSha256) || !probeSha256(child.guidanceSha256) || !same(child.task, input.host.task)
105
+ || !same(child.role, input.host.role) || typeof child.guidance !== "string" || Buffer.byteLength(child.guidance) > GUIDANCE_ROLE_MAX_BYTES
106
+ || probeHash(child.guidance) !== child.guidanceSha256) return fail("changed");
107
+ if (session.child) { if (!same(session.child, child)) fail("changed"); return; }
108
+ const producerStage = slot.arm === "successor" ? "compose" : slot.arm === "candidate2" ? "proposal2" : "proposal1";
109
+ const source = state.sessions.findLast(item => state.registration.manifest.slots.find(slot => slot.id === item.slotId)?.stage === producerStage
110
+ && item.state === "closed_fixture" && item.coverage.coverageVerified);
111
+ const controlled = source?.state === "closed_fixture" && source.candidateArtifactSha256 === child.candidateSha256;
112
+ session.child = { ...child, authoring: controlled ? "admitted_fixture" : "uncontrolled", sourceSessionId: controlled ? source.slotId : null };
113
+ charge(state, "inputBytes", Buffer.byteLength(child.guidance), state.registration.manifest.limits.inputBytes);
114
+ }
115
+ function snapshotBytes(registration: ProbeRegistrationV1): number {
116
+ return Object.entries(registration.snapshots).reduce((total, [key, value]) => total + Buffer.byteLength(key === "dataPolicy" ? canonical(value) : value as string), 0);
117
+ }
118
+ function completedRetryChain(state: Stored, start: number): boolean {
119
+ for (let index = start; index < state.sessions.length; index++) {
120
+ const session = state.sessions[index]!;
121
+ if (session.state === "closed_fixture" || session.state === "not_needed") return true;
122
+ if (session.state !== "failed_known" || state.registration.manifest.slots[index + 1]?.retryOf !== session.slotId) return false;
123
+ }
124
+ return false;
125
+ }
126
+ function skipUnusedRetries(state: Stored, successful: number): void {
127
+ let previous = state.sessions[successful]!.slotId;
128
+ for (let index = successful + 1; index < state.sessions.length; index++) {
129
+ if (state.registration.manifest.slots[index]!.retryOf !== previous) break;
130
+ const session = state.sessions[index]!;
131
+ if (session.state !== "planned") return fail("storage");
132
+ session.state = "not_needed"; previous = session.slotId;
133
+ }
134
+ }
135
+
136
+ /** Private same-db ledger. It never reads G1 tables or owns Task authority. */
137
+ export class GuidanceProbeStore {
138
+ private readonly db: Database;
139
+ constructor(file: string, private readonly now: () => number = Date.now) {
140
+ this.db = openHubDatabase(file, { create: true });
141
+ try {
142
+ this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_manifests (
143
+ project TEXT NOT NULL,id TEXT NOT NULL,experiment TEXT NOT NULL,manifest TEXT NOT NULL,
144
+ task_input TEXT NOT NULL,baseline_context TEXT NOT NULL,data_policy TEXT NOT NULL,system_policy TEXT NOT NULL,improver_context TEXT,
145
+ binding TEXT NOT NULL,counters TEXT NOT NULL,revision INTEGER NOT NULL,state TEXT NOT NULL,first_reserved INTEGER,last_wall INTEGER,admission_hold TEXT NOT NULL,cancel_requested INTEGER NOT NULL,
146
+ PRIMARY KEY(project,id),UNIQUE(project,experiment))`);
147
+ this.db.run(`CREATE TABLE IF NOT EXISTS guidance_probe_lanes (project TEXT PRIMARY KEY,manifest_id TEXT NOT NULL,slot_id TEXT)`);
148
+ 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
+ slot_id TEXT NOT NULL,body TEXT NOT NULL,PRIMARY KEY(project,manifest_id,slot_id),UNIQUE(project,manifest_id,ordinal))`);
150
+ } catch (error) {
151
+ this.db.close();
152
+ if (error instanceof GuidanceProbeError) throw error;
153
+ throw new GuidanceProbeError("storage");
154
+ }
155
+ }
156
+ close(): void { this.db.close(); }
157
+ hasRecords(): boolean {
158
+ try {
159
+ 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 };
161
+ if (row.present !== 0 && row.present !== 1) return fail("storage");
162
+ return row.present === 1;
163
+ } catch (error) { if (error instanceof GuidanceProbeError) throw error; return fail("storage"); }
164
+ }
165
+ private transaction<T>(action: () => T): T {
166
+ try { return this.db.transaction(action).immediate(); }
167
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
168
+ }
169
+ private readStored(key: ProbeKey): Stored | undefined {
170
+ checkedHash(key.id);
171
+ const columns = ["manifest", "task_input", "baseline_context", "data_policy", "system_policy", "improver_context", "binding", "counters"];
172
+ const projected = columns.map(name => `CASE WHEN typeof(${name})='text' AND length(CAST(${name} AS BLOB))<=${GUIDANCE_PROBE_LIMITS.recordBytes} THEN ${name} END AS ${name}`).join(",");
173
+ const row = this.db.query(`SELECT ${projected},CASE WHEN typeof(experiment)='text' AND length(CAST(experiment AS BLOB))<=256 THEN experiment END AS experiment,
174
+ CASE WHEN typeof(revision)='integer' THEN revision END AS revision,
175
+ CASE WHEN state IN ('declared','active','closing','closed_fixture','failed_fixture','unknown_held') THEN state END AS state,
176
+ CASE WHEN first_reserved IS NULL OR typeof(first_reserved)='integer' THEN first_reserved END AS first_reserved,
177
+ (first_reserved IS NULL OR typeof(first_reserved)='integer') AS first_reserved_valid,
178
+ CASE WHEN last_wall IS NULL OR typeof(last_wall)='integer' THEN last_wall END AS last_wall,
179
+ (last_wall IS NULL OR typeof(last_wall)='integer') AS last_wall_valid,
180
+ CASE WHEN admission_hold IN ('none','elapsed','observation','usage') THEN admission_hold END AS admission_hold,
181
+ CASE WHEN typeof(cancel_requested)='integer' AND cancel_requested IN (0,1) THEN cancel_requested END AS cancel_requested
182
+ FROM guidance_probe_manifests WHERE project=? AND id=?`).get(key.projectKey, key.id) as Row | null;
183
+ if (!row) return undefined;
184
+ const registration = parseGuidanceProbeRegistration({ manifest: json(row.manifest), snapshots: {
185
+ task: row.task_input, baselineContext: row.baseline_context, dataPolicy: json(row.data_policy), systemPolicy: row.system_policy,
186
+ ...(row.improver_context === null ? {} : { improverContext: row.improver_context }) } });
187
+ if (!registration || guidanceProbeManifestKey(registration.manifest) !== key.id || registration.manifest.projectKey !== key.projectKey
188
+ || registration.manifest.experimentId !== row.experiment || canonical(registration.manifest) !== row.manifest) return fail("storage");
189
+ const binding = json<ProbeHostBinding>(row.binding); host(binding);
190
+ if (binding.projectKey !== key.projectKey || !same(binding.task, registration.manifest.task) || !same(binding.role, registration.manifest.role)
191
+ || probeHash(binding.baselineGuidance) !== registration.manifest.guidance.baselineSha256) return fail("storage");
192
+ const totals = json<ProbeCounters>(row.counters), expected = counters();
193
+ if (!same(Object.keys(totals).sort(), Object.keys(expected).sort()) || typeof totals.usageUnknown !== "boolean"
194
+ || Object.entries(totals).some(([name, value]) => name !== "usageUnknown" && !probeInteger(value))) return fail("storage");
195
+ 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,
196
+ CASE WHEN typeof(ordinal)='integer' THEN ordinal END AS ordinal,CASE WHEN typeof(body)='text' AND length(CAST(body AS BLOB))<=? THEN body END AS body
197
+ FROM guidance_probe_sessions WHERE project=? AND manifest_id=? ORDER BY ordinal LIMIT ?`)
198
+ .all(GUIDANCE_PROBE_SESSION_BYTES, key.projectKey, key.id, GUIDANCE_PROBE_LIMITS.slots + 1) as Row[];
199
+ if (rows.length !== registration.manifest.slots.length || rows.length > GUIDANCE_PROBE_LIMITS.slots) return fail("storage");
200
+ const starts = new Set<number>();
201
+ const sessions = rows.map((item, index) => {
202
+ const session = json<Session>(item.body), slot = registration.manifest.slots[index]!;
203
+ if (item.ordinal !== index || item.slot_id !== slot.id || session.slotId !== slot.id || !probeInteger(session.generation) || !probeInteger(session.revision)
204
+ || !["planned", "reserved", "running", "failed_known", "closed_fixture", "not_needed", "unknown_held"].includes(session.state)
205
+ || session.candidateArtifactSha256 !== null && !probeSha256(session.candidateArtifactSha256)) return fail("storage");
206
+ const fields = Object.keys(session);
207
+ if (fields.some(name => !["slotId", "generation", "revision", "state", "candidateArtifactSha256", "child", "host", "effect", "start", "coverage"].includes(name))
208
+ || !Object.hasOwn(session, "effect") || ["planned", "not_needed"].includes(session.state)
209
+ && (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(",")
211
+ || !probeInteger(session.coverage.inputFrameBytes) || session.coverage.inputFrameSha256 !== null && !probeSha256(session.coverage.inputFrameSha256)
212
+ || ["launchExposed", "preLaunchFailure", "usageUnknown", "coverageVerified"].some(name => typeof session.coverage[name as keyof ProbeSessionCoverage] !== "boolean")
213
+ || ["modelCalls", "modelUsageKnown", "toolCalls", "toolUsageKnown"].some(name => !probeInteger(session.coverage[name as keyof ProbeSessionCoverage]))
214
+ || session.coverage.modelUsageKnown > session.coverage.modelCalls || session.coverage.toolUsageKnown > session.coverage.toolCalls
215
+ || session.coverage.launchExposed && (!session.coverage.inputFrameSha256 || session.coverage.inputFrameBytes === 0)
216
+ || session.coverage.preLaunchFailure && (session.state !== "failed_known" || session.coverage.launchExposed || session.coverage.modelCalls !== 0 || session.coverage.toolCalls !== 0)
217
+ || session.coverage.coverageVerified && !["closed_fixture", "failed_known"].includes(session.state)
218
+ || session.coverage.coverageVerified && (!session.coverage.launchExposed || session.coverage.preLaunchFailure || !session.coverage.inputFrameSha256
219
+ || session.coverage.modelCalls < 1 || session.coverage.modelUsageKnown !== session.coverage.modelCalls || session.coverage.toolUsageKnown !== session.coverage.toolCalls || session.coverage.usageUnknown)) return fail("storage");
220
+ if (session.state === "not_needed") {
221
+ const prior = rows[index - 1];
222
+ const priorState = prior ? json<Session>(prior.body).state : undefined;
223
+ if (registration.manifest.slots[index]!.retryOf !== registration.manifest.slots[index - 1]?.id
224
+ || !["closed_fixture", "not_needed"].includes(priorState ?? "")) return fail("storage");
225
+ }
226
+ if (session.host) { host(session.host); if (!invariant(binding, session.host)) return fail("storage"); }
227
+ else if (!["planned", "not_needed"].includes(session.state)) return fail("storage");
228
+ if (session.host) {
229
+ const start = session.start;
230
+ if (!start || Object.keys(start).sort().join(",") !== "actor,inputFrameBytes,inputFrameSha256,nativeSession,requestConnectionId,requestedRevision,sessionGeneration,slotId,variantId"
231
+ || !probeInteger(start.requestedRevision) || start.requestedRevision >= checkedInteger(row.revision) || starts.has(start.requestedRevision)
232
+ || start.slotId !== session.slotId || start.actor !== session.host.actor || !executionText(start.actor, EXECUTION_REFERENCE_LIMITS.id)
233
+ || !probeSessionGeneration(start.sessionGeneration) || start.sessionGeneration !== session.host.sessionGeneration
234
+ || start.nativeSession !== session.host.nativeSession || start.nativeSession !== null && !executionText(start.nativeSession, EXECUTION_REFERENCE_LIMITS.id)
235
+ || start.requestConnectionId !== session.host.requestConnectionId || !executionText(start.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
236
+ || start.variantId !== (session.child?.variantId ?? null) || start.variantId !== null && !probeSha256(start.variantId)
237
+ || start.inputFrameSha256 !== session.coverage.inputFrameSha256 || start.inputFrameBytes !== session.coverage.inputFrameBytes) return fail("storage");
238
+ starts.add(start.requestedRevision);
239
+ }
240
+ if (session.child && (!probeSha256(session.child.variantId) || !probeSha256(session.child.candidateSha256) || !probeSha256(session.child.guidanceSha256) || !same(session.child.task, binding.task)
241
+ || !same(session.child.role, binding.role) || typeof session.child.guidance !== "string" || Buffer.byteLength(session.child.guidance) > GUIDANCE_ROLE_MAX_BYTES
242
+ || probeHash(session.child.guidance) !== session.child.guidanceSha256 || !["admitted_fixture", "uncontrolled"].includes(session.child.authoring))) return fail("storage");
243
+ if (session.effect) {
244
+ const effect = session.effect, admission = effect.admission;
245
+ if (admission) resourceCharges(admission.charges, "storage");
246
+ if (!admission || !["pending", "settled", "unknown"].includes(effect.state) || !probeInteger(admission.sequence) || !probeInteger(admission.amount)
247
+ || !probeSha256(admission.descriptorSha256) || !same(admission.reservation.key, key) || admission.reservation.slotId !== slot.id
248
+ || admission.reservation.generation !== session.generation || admission.reservation.revision !== session.revision
249
+ || !["model_calls", "tool_calls", "tokens", "input_bytes", "scratch_bytes", "output_bytes"].includes(admission.unit)
250
+ || effect.usageHash !== null && !probeSha256(effect.usageHash) || effect.observed !== null && !probeInteger(effect.observed)) return fail("storage");
251
+ }
252
+ sessionCanonical(session); return session;
253
+ });
254
+ if (sessions.reduce((sum, item) => increment(sum, item.coverage.modelCalls), 0) !== totals.modelCalls
255
+ || sessions.reduce((sum, item) => increment(sum, item.coverage.toolCalls), 0) !== totals.toolCalls) return fail("storage");
256
+ if (row.first_reserved_valid !== 1 || row.last_wall_valid !== 1 || !["declared", "active", "closing", "closed_fixture", "failed_fixture", "unknown_held"].includes(row.state as string)) return fail("storage");
257
+ if (!["none", "elapsed", "observation", "usage"].includes(row.admission_hold as string)
258
+ || row.admission_hold !== "none" && !["unknown_held", "closing"].includes(row.state as string)) return fail("storage");
259
+ if (row.cancel_requested !== 0 && row.cancel_requested !== 1 || row.cancel_requested === 1 && !["closing", "unknown_held"].includes(row.state as string)) return fail("storage");
260
+ return { registration, binding, receipt: { id: key.id, revision: checkedInteger(row.revision), state: row.state as ProbeReceipt["state"], already: false },
261
+ counters: totals, firstReservedAt: row.first_reserved === null ? null : checkedInteger(row.first_reserved),
262
+ lastWall: row.last_wall === null ? null : checkedInteger(row.last_wall), admissionHold: row.admission_hold as Stored["admissionHold"],
263
+ cancelRequested: row.cancel_requested === 1, notNeeded: sessions.filter(item => item.state === "not_needed").length, sessions };
264
+ }
265
+ read(key: ProbeKey): ProbeStoredState | undefined {
266
+ try { const state = this.readStored(key); if (!state) return undefined; const { lastWall: _, ...result } = state; return result; }
267
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
268
+ }
269
+ /** Host-private selector only, after Tasks' current outer admission; never a current-authority attestation. */
270
+ startSelector(key: ProbeKey, requestedRevision: number): ProbeStartSelector | undefined {
271
+ if (!probeInteger(requestedRevision)) return fail("invalid");
272
+ const start = this.read(key)?.sessions.find(item => item.start?.requestedRevision === requestedRevision)?.start;
273
+ return start ? { ...start } : undefined;
274
+ }
275
+ private get(key: ProbeKey): Stored { return this.readStored(key) ?? fail("changed"); }
276
+ private save(key: ProbeKey, state: Stored): void {
277
+ this.db.query("UPDATE guidance_probe_manifests SET counters=?,revision=?,state=?,first_reserved=?,last_wall=?,admission_hold=?,cancel_requested=? WHERE project=? AND id=?")
278
+ .run(canonical(state.counters), state.receipt.revision, state.receipt.state, state.firstReservedAt, state.lastWall, state.admissionHold, state.cancelRequested ? 1 : 0, key.projectKey, key.id);
279
+ for (const session of state.sessions) this.db.query("UPDATE guidance_probe_sessions SET body=? WHERE project=? AND manifest_id=? AND slot_id=?")
280
+ .run(sessionCanonical(session), key.projectKey, key.id, session.slotId);
281
+ }
282
+ private clockLost(key: ProbeKey, state: Stored, now: number): boolean {
283
+ if (probeInteger(now) && (state.lastWall === null || now >= state.lastWall)
284
+ && (state.firstReservedAt === null || now >= state.firstReservedAt && now - state.firstReservedAt >= state.counters.elapsedHighWaterMs
285
+ && now - state.firstReservedAt < state.registration.manifest.limits.elapsedMs)) return false;
286
+ if (probeInteger(now) && (state.lastWall === null || now >= state.lastWall) && state.firstReservedAt !== null && now >= state.firstReservedAt) {
287
+ state.lastWall = now; state.counters.elapsedHighWaterMs = Math.max(state.counters.elapsedHighWaterMs, now - state.firstReservedAt);
288
+ }
289
+ hold(state, "elapsed"); advance(state); this.save(key, state); return true;
290
+ }
291
+ private *lanes(project?: string): Generator<Lane> {
292
+ const identifier = (name: string, bytes: number) => `typeof(${name})='text' AND length(CAST(${name} AS BLOB))<=${bytes}`;
293
+ const projectValid = identifier("project", EXECUTION_REFERENCE_LIMITS.id), manifestValid = identifier("manifest_id", GUIDANCE_PROBE_LIMITS.hashLength), slotValid = identifier("slot_id", EXECUTION_REFERENCE_LIMITS.id);
294
+ const rows = this.db.query(`SELECT (${projectValid}) AS project_valid,(${manifestValid}) AS manifest_valid,
295
+ (slot_id IS NULL OR (${slotValid})) AS slot_valid,(slot_id IS NULL) AS slot_is_null,
296
+ CASE WHEN ${projectValid} THEN project END AS project,CASE WHEN ${manifestValid} THEN manifest_id END AS manifest_id,
297
+ CASE WHEN ${slotValid} THEN slot_id END AS slot_id FROM guidance_probe_lanes ${project === undefined ? "ORDER BY project" : "WHERE project=? LIMIT 2"}`)
298
+ .iterate(...(project === undefined ? [] : [project])) as Iterable<Row>;
299
+ for (const row of rows) {
300
+ if (row.project_valid !== 1 || row.manifest_valid !== 1 || row.slot_valid !== 1
301
+ || !executionText(row.project, EXECUTION_REFERENCE_LIMITS.id) || /\p{Cf}/u.test(row.project) || !probeSha256(row.manifest_id)
302
+ || row.slot_is_null !== 0 && row.slot_is_null !== 1
303
+ || row.slot_is_null === 0 && (!executionText(row.slot_id, EXECUTION_REFERENCE_LIMITS.id) || /\p{Cf}/u.test(row.slot_id))) return fail("storage");
304
+ const lane: Lane = { project: row.project, manifestId: row.manifest_id, slotId: row.slot_is_null === 1 ? null : row.slot_id as string };
305
+ const linked = this.get({ projectKey: lane.project, id: lane.manifestId });
306
+ if (!["active", "closing", "unknown_held"].includes(linked.receipt.state)) return fail("storage");
307
+ if (lane.slotId !== null && !linked.sessions.some(item => item.slotId === lane.slotId && ["reserved", "running", "unknown_held"].includes(item.state))) return fail("storage");
308
+ yield lane;
309
+ }
310
+ }
311
+ register(value: ProbeRegistrationV1, binding: ProbeHostBinding, revalidate: () => ProbeHostBinding): ProbeReceipt {
312
+ const registration = parseGuidanceProbeRegistration(value); if (!registration) return fail("invalid"); host(binding);
313
+ const manifest = registration.manifest, id = guidanceProbeManifestKey(manifest), key = { projectKey: manifest.projectKey, id };
314
+ if (manifest.projectKey !== binding.projectKey || !same(manifest.task, binding.task) || !same(manifest.role, binding.role)
315
+ || probeHash(binding.baselineGuidance) !== manifest.guidance.baselineSha256) return fail("changed");
316
+ const bytes = increment(snapshotBytes(registration), Buffer.byteLength(binding.baselineGuidance));
317
+ if (bytes > manifest.limits.inputBytes) {
318
+ const error = new GuidanceProbeError("budget");
319
+ error.message = "probe budget limits.inputBytes is too small for retained snapshots plus baseline guidance; raise it before registering this declaration";
320
+ throw error;
321
+ }
322
+ return this.transaction(() => {
323
+ if (!same(binding, revalidate())) return fail("changed");
324
+ const existing = this.db.query("SELECT CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=64 THEN id END AS id FROM guidance_probe_manifests WHERE project=? AND experiment=?").get(key.projectKey, manifest.experimentId) as { id: unknown } | null;
325
+ if (existing) { if (!probeSha256(existing.id)) return fail("storage"); if (existing.id !== id) return fail("changed"); const state = this.get(key); if (!invariant(state.binding, binding)) return fail("changed"); return receipt(state, true); }
326
+ const totals = counters(); totals.inputBytes = bytes;
327
+ const snap = registration.snapshots;
328
+ this.db.query(`INSERT INTO guidance_probe_manifests(project,id,experiment,manifest,task_input,baseline_context,data_policy,system_policy,improver_context,binding,counters,revision,state,admission_hold,cancel_requested)
329
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(key.projectKey, id, manifest.experimentId, canonical(manifest), snap.task, snap.baselineContext,
330
+ canonical(snap.dataPolicy), snap.systemPolicy, snap.improverContext ?? null, canonical(binding), canonical(totals), 0, "declared", "none", 0);
331
+ manifest.slots.forEach((slot, index) => this.db.query("INSERT INTO guidance_probe_sessions(project,manifest_id,ordinal,slot_id,body) VALUES(?,?,?,?,?)")
332
+ .run(key.projectKey, id, index, slot.id, canonical({ slotId: slot.id, generation: 0, revision: 0, state: "planned", candidateArtifactSha256: null, effect: null, coverage: sessionCoverage(undefined) })));
333
+ return { id, revision: 0, state: "declared", already: false };
334
+ });
335
+ }
336
+ reserveSession(input: ProbeSessionAdmission, revalidate: () => ProbeAdmissionRecheck): ProbeReservationResult {
337
+ return this.transaction(() => {
338
+ const fresh = revalidate(); if (!same(fresh.host, input.host) || !sameChild(fresh.child, input.child)) return fail("changed");
339
+ const state = this.get(input.key);
340
+ if (!invariant(state.binding, input.host) || !probeInteger(input.expectedRevision)) return fail("changed");
341
+ const replay = state.sessions.find(item => item.start?.requestedRevision === input.expectedRevision);
342
+ if (replay) {
343
+ const expected: ProbeStartSelector = { requestedRevision: input.expectedRevision, slotId: replay.slotId, variantId: input.child?.variantId ?? null,
344
+ inputFrameSha256: replay.start!.inputFrameSha256, inputFrameBytes: replay.start!.inputFrameBytes,
345
+ actor: input.host.actor, sessionGeneration: input.host.sessionGeneration, nativeSession: input.host.nativeSession, requestConnectionId: input.host.requestConnectionId };
346
+ if (!same(replay.start, expected) || !sameChild(replay.child, input.child)) return fail("changed");
347
+ if (input.preparedFrame && (input.preparedFrame.slotId !== replay.slotId || input.preparedFrame.sha256 !== expected.inputFrameSha256
348
+ || input.preparedFrame.bytes !== expected.inputFrameBytes)) return fail("changed");
349
+ return { kind: "existing", receipt: receipt(state, true) };
350
+ }
351
+ if (state.receipt.revision !== input.expectedRevision) return fail("changed");
352
+ if (state.cancelRequested || ["closing", "closed_fixture", "failed_fixture", "unknown_held"].includes(state.receipt.state) || state.counters.usageUnknown) return fail("held");
353
+ const lanes = [...this.lanes(input.key.projectKey)]; if (lanes.length > 1) return fail("storage");
354
+ const lane = lanes[0]; if (lane && (lane.manifestId !== input.key.id || lane.slotId !== null)) return fail("held");
355
+ const index = state.sessions.findIndex(item => item.state === "planned"), session = state.sessions[index]; if (!session) return fail("held");
356
+ const slot = state.registration.manifest.slots[index]!, previous = state.sessions[index - 1];
357
+ const frame = input.preparedFrame;
358
+ if (frame && (frame.slotId !== slot.id || !probeSha256(frame.sha256) || !probeInteger(frame.bytes) || frame.bytes === 0)) return fail("invalid");
359
+ if (frame) charge(state, "inputBytes", frame.bytes, state.registration.manifest.limits.inputBytes);
360
+ if (previous && !["closed_fixture", "not_needed"].includes(previous.state) && !(previous.state === "failed_known" && slot.retryOf === previous.slotId)) return fail("held");
361
+ if (slot.retryOf && previous?.state !== "failed_known") return fail("held");
362
+ // No fake launch can begin when a first model/tool call already cannot be admitted.
363
+ const limits = state.registration.manifest.limits;
364
+ if (state.counters.modelCalls >= limits.modelCalls || limits.elapsedMs === 0
365
+ || limits.tokens !== undefined && state.counters.tokensReserved >= limits.tokens) return fail("budget");
366
+ const now = this.now();
367
+ if (this.clockLost(input.key, state, now)) return { kind: "existing", receipt: receipt(state) };
368
+ elapsed(state, now, true); boundChild(state, input, session);
369
+ charge(state, slot.role === "worker" ? "workerAttempts" : "editorAttempts", 1, slot.role === "worker" ? GUIDANCE_PROBE_LIMITS.workerAttempts : GUIDANCE_PROBE_LIMITS.editorAttempts);
370
+ session.host = input.host; session.generation = increment(session.generation); session.revision = increment(session.revision); session.state = "reserved";
371
+ session.coverage = sessionCoverage(frame);
372
+ session.start = { requestedRevision: input.expectedRevision, slotId: slot.id, variantId: input.child?.variantId ?? null,
373
+ inputFrameSha256: frame?.sha256 ?? null, inputFrameBytes: frame?.bytes ?? 0,
374
+ actor: input.host.actor, sessionGeneration: input.host.sessionGeneration, nativeSession: input.host.nativeSession, requestConnectionId: input.host.requestConnectionId };
375
+ state.receipt.state = "active"; advance(state);
376
+ this.db.query("INSERT INTO guidance_probe_lanes(project,manifest_id,slot_id) VALUES(?,?,?) ON CONFLICT(project) DO UPDATE SET slot_id=excluded.slot_id")
377
+ .run(input.key.projectKey, input.key.id, slot.id);
378
+ this.save(input.key, state);
379
+ return { kind: "granted", reservation: { key: input.key, slotId: slot.id, generation: session.generation, revision: session.revision } };
380
+ });
381
+ }
382
+ private owned(state: Stored, reservation: ProbeReservation): Session {
383
+ const session = state.sessions.find(item => item.slotId === reservation.slotId);
384
+ if (!session || session.generation !== reservation.generation || session.revision !== reservation.revision || !["reserved", "running"].includes(session.state)) return fail("changed");
385
+ return session;
386
+ }
387
+ checkInvocation(reservation: ProbeReservation, revalidate: () => ProbeAdmissionRecheck): ProbeReceipt {
388
+ return this.transaction(() => {
389
+ const state = this.get(reservation.key), session = this.owned(state, reservation), fresh = revalidate();
390
+ if (!same(fresh.host, session.host) || !sameChild(fresh.child, session.child) || !invariant(state.binding, fresh.host)) return fail("changed");
391
+ if (state.cancelRequested || state.receipt.state !== "active" || state.admissionHold !== "none") return fail("held");
392
+ const now = this.now();
393
+ if (this.clockLost(reservation.key, state, now)) return receipt(state);
394
+ elapsed(state, now); this.save(reservation.key, state); return receipt(state);
395
+ });
396
+ }
397
+ /** Persisted trusted-host marker immediately before crossing the fake-port launch boundary. */
398
+ exposeLaunch(reservation: ProbeReservation, revalidate: () => ProbeAdmissionRecheck): ProbeReceipt {
399
+ return this.transaction(() => {
400
+ const state = this.get(reservation.key), session = this.owned(state, reservation), fresh = revalidate();
401
+ if (!same(fresh.host, session.host) || !sameChild(fresh.child, session.child) || !invariant(state.binding, fresh.host)
402
+ || state.cancelRequested || state.receipt.state !== "active" || state.admissionHold !== "none"
403
+ || !session.coverage.inputFrameSha256 || session.coverage.inputFrameBytes === 0) return fail("held");
404
+ if (session.coverage.launchExposed) return receipt(state, true);
405
+ const now = this.now();
406
+ if (this.clockLost(reservation.key, state, now)) return receipt(state);
407
+ elapsed(state, now);
408
+ session.coverage.launchExposed = true; advance(state); this.save(reservation.key, state); return receipt(state);
409
+ });
410
+ }
411
+ admitEffect(input: ProbeEffectAdmission, revalidate: () => ProbeAdmissionRecheck): ProbeEffectAdmissionResult {
412
+ return this.transaction(() => {
413
+ const state = this.get(input.reservation.key), session = this.owned(state, input.reservation), fresh = revalidate();
414
+ if (!same(fresh.host, session.host) || !sameChild(fresh.child, session.child) || !invariant(state.binding, fresh.host)) return fail("changed");
415
+ if (state.cancelRequested || state.receipt.state !== "active" || state.counters.usageUnknown || !probeInteger(input.sequence) || !probeSha256(input.descriptorSha256) || !probeInteger(input.amount)) return fail("held");
416
+ if (["model_calls", "tool_calls"].includes(input.unit) && input.amount !== 1) return fail("invalid");
417
+ const previous = session.effect;
418
+ if (previous && input.sequence === previous.admission.sequence) {
419
+ if (!sameAdmission(input, previous.admission)) return fail("changed");
420
+ return { kind: "existing", state: previous.state };
421
+ }
422
+ if (input.sequence !== (previous ? increment(previous.admission.sequence) : 0) || previous?.state === "pending" || previous?.state === "unknown") return fail("held");
423
+ if (previous?.admission.unit === "model_calls" && previous.usageHash === null) {
424
+ hold(state, "usage"); advance(state); this.save(input.reservation.key, state);
425
+ return { kind: "existing", state: "unknown" };
426
+ }
427
+ const now = this.now();
428
+ if (this.clockLost(input.reservation.key, state, now)) return { kind: "existing", state: "unknown" };
429
+ elapsed(state, now);
430
+ const limits = state.registration.manifest.limits;
431
+ const names = { model_calls: ["modelCalls", limits.modelCalls], tool_calls: ["toolCalls", limits.toolCalls], tokens: ["tokensReserved", limits.tokens], input_bytes: ["inputBytes", limits.inputBytes], scratch_bytes: ["scratchBytes", limits.scratchBytes], output_bytes: ["outputBytes", limits.outputBytes] } as const;
432
+ const target = names[input.unit]; if (!target || target[1] === undefined) return fail("budget");
433
+ const extra = resourceCharges(input.charges);
434
+ charge(state, target[0], input.amount, target[1]);
435
+ chargeResources(state, extra);
436
+ if (input.unit === "model_calls") {
437
+ if (limits.tokens !== undefined && !probeInteger(input.reservedTokens)) return fail("budget");
438
+ if (input.reservedTokens !== undefined) charge(state, "tokensReserved", input.reservedTokens, limits.tokens ?? Number.MAX_SAFE_INTEGER);
439
+ } else if (input.reservedTokens !== undefined) return fail("invalid");
440
+ const admitted = { ...input, ...(extra === undefined ? {} : { charges: extra }), now };
441
+ session.effect = { admission: admitted, state: "pending", usageHash: null, observed: null }; session.state = "running";
442
+ if (input.unit === "model_calls") session.coverage.modelCalls = increment(session.coverage.modelCalls, input.amount);
443
+ else if (input.unit === "tool_calls") session.coverage.toolCalls = increment(session.coverage.toolCalls, input.amount);
444
+ advance(state); this.save(input.reservation.key, state); return { kind: "granted", admission: admitted };
445
+ });
446
+ }
447
+ private effect(state: Stored, admission: ProbeEffectAdmission): { session: Session; effect: Effect } {
448
+ const session = state.sessions.find(item => item.slotId === admission.reservation.slotId);
449
+ if (!session || !session.effect || !same(session.effect.admission, admission)) return fail("changed");
450
+ return { session, effect: session.effect };
451
+ }
452
+ recordUsage(input: ProbeUsageObservation): ProbeReceipt {
453
+ return this.transaction(() => {
454
+ const state = this.get(input.admission.reservation.key);
455
+ const session = state.sessions.find(item => item.slotId === input.admission.reservation.slotId), effect = session?.effect;
456
+ const expectedHash = probeHash(canonical({ admission: input.admission, observed: input.observed }));
457
+ if (!effect || !same(effect.admission, input.admission) || !probeSha256(input.observationSha256) || input.observationSha256 !== expectedHash
458
+ || input.observed !== null && !probeInteger(input.observed) || effect.usageHash !== null && effect.usageHash !== input.observationSha256) {
459
+ hold(state, "usage");
460
+ } else if (effect.usageHash === input.observationSha256) return receipt(state, true);
461
+ else {
462
+ effect.usageHash = input.observationSha256; effect.observed = input.observed;
463
+ if (input.observed === null) { state.counters.usageUnknown = true; if (session) session.coverage.usageUnknown = true; }
464
+ else if (input.admission.unit === "model_calls") {
465
+ state.counters.tokensObservedKnown = increment(state.counters.tokensObservedKnown, input.observed);
466
+ if (session) session.coverage.modelUsageKnown = increment(session.coverage.modelUsageKnown);
467
+ if (input.admission.reservedTokens !== undefined && input.observed > input.admission.reservedTokens) state.counters.usageUnknown = true;
468
+ } else if (input.admission.unit === "tool_calls") {
469
+ if (session) session.coverage.toolUsageKnown = increment(session.coverage.toolUsageKnown);
470
+ if (input.observed > input.admission.amount) state.counters.usageUnknown = true;
471
+ }
472
+ if (state.counters.usageUnknown && session) session.coverage.usageUnknown = true;
473
+ if (state.counters.usageUnknown) hold(state, "usage");
474
+ }
475
+ advance(state); this.save(input.admission.reservation.key, state); return receipt(state);
476
+ });
477
+ }
478
+ settleEffect(input: ProbeEffectSettlement): ProbeReceipt {
479
+ return this.transaction(() => {
480
+ const state = this.get(input.admission.reservation.key), { effect } = this.effect(state, input.admission);
481
+ if (effect.state !== "pending") {
482
+ if (effect.state === input.outcome) return receipt(state, true); return fail("changed");
483
+ }
484
+ effect.state = input.outcome;
485
+ if (input.outcome === "unknown" || input.admission.unit === "model_calls" && effect.usageHash === null) hold(state, "usage");
486
+ advance(state); this.save(input.admission.reservation.key, state); return receipt(state);
487
+ });
488
+ }
489
+ settleSession(input: ProbeSessionSettlement): ProbeReceipt {
490
+ return this.transaction(() => {
491
+ const state = this.get(input.reservation.key), session = this.owned(state, input.reservation);
492
+ const now = this.now();
493
+ if (this.clockLost(input.reservation.key, state, now)) return receipt(state);
494
+ elapsed(state, now);
495
+ if (input.candidateArtifactSha256 !== null && !probeSha256(input.candidateArtifactSha256)) return fail("invalid");
496
+ const covered = session.coverage.launchExposed && !!session.coverage.inputFrameSha256 && session.coverage.modelCalls > 0
497
+ && session.coverage.modelUsageKnown === session.coverage.modelCalls && session.coverage.toolUsageKnown === session.coverage.toolCalls
498
+ && !session.coverage.usageUnknown;
499
+ if (session.coverage.launchExposed && !covered) hold(state, "usage");
500
+ const unknown = state.cancelRequested || state.admissionHold !== "none" || state.receipt.state === "closing" || input.outcome === "unknown" || state.counters.usageUnknown || session.effect?.state === "pending" || session.effect?.state === "unknown"
501
+ || session.coverage.launchExposed && !covered;
502
+ session.coverage.coverageVerified = covered && !unknown;
503
+ session.state = unknown ? "unknown_held" : input.outcome === "failed_known" ? "failed_known" : "closed_fixture"; session.candidateArtifactSha256 = input.candidateArtifactSha256;
504
+ if (unknown) state.receipt.state = "unknown_held";
505
+ else {
506
+ 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);
507
+ const index = state.sessions.indexOf(session);
508
+ if (session.state === "closed_fixture") skipUnusedRetries(state, index);
509
+ const failed = session.state === "failed_known" && state.registration.manifest.slots[index + 1]?.retryOf !== session.slotId;
510
+ if (failed || state.sessions.every((_, index) => completedRetryChain(state, index))) {
511
+ state.receipt.state = failed ? "failed_fixture" : "closed_fixture";
512
+ this.db.query("DELETE FROM guidance_probe_lanes WHERE project=? AND manifest_id=? AND slot_id IS NULL").run(input.reservation.key.projectKey, input.reservation.key.id);
513
+ }
514
+ }
515
+ advance(state); this.save(input.reservation.key, state); return receipt(state);
516
+ });
517
+ }
518
+ /** Trusted host can attest no launch only before invoking the port. */
519
+ settlePreLaunchFailure(reservation: ProbeReservation, now: number): ProbeReceipt {
520
+ return this.transaction(() => {
521
+ const state = this.get(reservation.key), session = this.owned(state, reservation);
522
+ if (session.coverage.launchExposed || session.coverage.modelCalls !== 0 || session.coverage.toolCalls !== 0
523
+ || session.effect !== null || state.counters.usageUnknown || state.admissionHold !== "none" || state.cancelRequested || state.receipt.state === "closing") return fail("held");
524
+ if (this.clockLost(reservation.key, state, now)) return receipt(state);
525
+ elapsed(state, now);
526
+ session.coverage.preLaunchFailure = true; session.state = "failed_known"; session.candidateArtifactSha256 = null;
527
+ 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
+ const index = state.sessions.indexOf(session), failed = state.registration.manifest.slots[index + 1]?.retryOf !== session.slotId;
529
+ if (failed) {
530
+ state.receipt.state = "failed_fixture";
531
+ this.db.query("DELETE FROM guidance_probe_lanes WHERE project=? AND manifest_id=? AND slot_id IS NULL").run(reservation.key.projectKey, reservation.key.id);
532
+ }
533
+ advance(state); this.save(reservation.key, state); return receipt(state);
534
+ });
535
+ }
536
+ settleObservedSession(input: ProbeSessionSettlement, usage: "known_fixture" | "unknown"): ProbeReceipt {
537
+ if (usage !== "known_fixture") this.latchHold(input.reservation, "usage");
538
+ return this.settleSession(input);
539
+ }
540
+ cancelIntent(input: ProbeCancellation, revalidate: () => ProbeHostBinding): ProbeReceipt {
541
+ return this.transaction(() => {
542
+ const state = this.get(input.key), fresh = revalidate();
543
+ if (!same(input.host, fresh) || !taskEpoch(state.binding, fresh) || state.receipt.revision !== input.expectedRevision) return fail("changed");
544
+ if (state.cancelRequested || ["closing", "closed_fixture", "failed_fixture"].includes(state.receipt.state)) return receipt(state, true);
545
+ state.cancelRequested = true; state.receipt.state = "closing"; advance(state); this.save(input.key, state); return receipt(state);
546
+ });
547
+ }
548
+ /** Narrow already-owned bookkeeping only. No effect admission, lane release or hold-reset. */
549
+ latchHold(reservation: ProbeReservation, reason: Exclude<Stored["admissionHold"], "none">): ProbeReceipt {
550
+ return this.transaction(() => {
551
+ const state = this.get(reservation.key), session = state.sessions.find(item => item.slotId === reservation.slotId);
552
+ if (!session || session.generation !== reservation.generation || session.revision !== reservation.revision
553
+ || !["elapsed", "observation", "usage"].includes(reason)) return fail("changed");
554
+ hold(state, reason); advance(state); this.save(reservation.key, state); return receipt(state);
555
+ });
556
+ }
557
+ /** Recovery only. O(historical experiments + <=9 sessions each); future keyset/budget upgrade if measured slow. */
558
+ integrity(): ProbeIntegrity {
559
+ try { return this.db.transaction(() => this.integritySnapshot())(); }
560
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
561
+ }
562
+ private integritySnapshot(): ProbeIntegrity {
563
+ const digest = createHash("sha256");
564
+ let experiments = 0, sessions = 0;
565
+ // ponytail: keys stream, each payload remains bounded; no experiment-count cap or incomplete digest.
566
+ for (const key of this.db.query(`SELECT CASE WHEN typeof(project)='text' AND length(CAST(project AS BLOB))<=256 THEN project END AS projectKey,
567
+ 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`).iterate() as Iterable<ProbeKey>) {
568
+ if (typeof key.projectKey !== "string") return fail("storage");
569
+ const state = this.get(key); experiments++; sessions += state.sessions.length;
570
+ for (const component of [key, state.registration.manifest, state.binding, state.counters, state.receipt,
571
+ { firstReservedAt: state.firstReservedAt, lastWall: state.lastWall, admissionHold: state.admissionHold, cancelRequested: state.cancelRequested }]) digest.update(canonical(component)).update("\n");
572
+ for (const session of state.sessions) digest.update(sessionCanonical(session)).update("\n");
573
+ }
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)
575
+ 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
+ if (orphan.invalid) return fail("storage");
577
+ for (const lane of this.lanes()) digest.update(canonical(lane)).update("\n");
578
+ return { experiments, sessions, digest: digest.digest("hex") };
579
+ }
580
+ }
581
+
582
+ /** Host test composition only. No wire/config runner selection or independent caller authority. */
583
+ export class GuidanceProbeFixtureHost {
584
+ constructor(private readonly store: GuidanceProbeStore, private readonly options: {
585
+ ports?: GuidanceProbeFakePorts;
586
+ revalidate: () => ProbeAdmissionRecheck;
587
+ now: () => number;
588
+ prepareEditorFrame?: (state: ProbeStoredState, slot: ProbeSlot) => string | Promise<string>;
589
+ prepareWorkerFrame?: ProbeWorkerFramePreparer;
590
+ onReserved?: (reservation: ProbeReservation) => void;
591
+ }) {}
592
+ async start(input: ProbeSessionAdmission, signal: AbortSignal): Promise<ProbeReceipt> {
593
+ const ports = this.options.ports;
594
+ // Production T1 stops here, before even selecting/binding a child or reserving a slot.
595
+ if (!ports) return fail("runner");
596
+ if (signal.aborted) return fail("held");
597
+ const current = this.store.read(input.key); if (!current) return fail("changed");
598
+ const original = this.store.startSelector(input.key, input.expectedRevision);
599
+ const slot = current.registration.manifest.slots.find(item => item.id === (original?.slotId ?? current.sessions.find(item => item.state === "planned")?.slotId));
600
+ if (!slot) return fail("held");
601
+ const selectedGuidance = slot.arm === "baseline" ? current.binding.baselineGuidance : input.child?.guidance;
602
+ let preparedInput: string | undefined, preparedNonGuidance: string | undefined;
603
+ if (slot.role === "worker" && typeof selectedGuidance === "string" && this.options.prepareWorkerFrame) {
604
+ const prepared = await this.options.prepareWorkerFrame(current, slot, selectedGuidance);
605
+ if (!prepared || !probeSha256(prepared.nonGuidanceInputSha256) || typeof prepared.inputFrame !== "string") return fail("invalid");
606
+ preparedInput = prepared.inputFrame; preparedNonGuidance = prepared.nonGuidanceInputSha256;
607
+ }
608
+ let preparedEditor: string | undefined;
609
+ if (slot.role !== "worker" && this.options.prepareEditorFrame) {
610
+ const prepared = this.options.prepareEditorFrame(current, slot);
611
+ preparedEditor = typeof prepared === "string" ? prepared : await prepared;
612
+ }
613
+ const inputFrame = preparedInput !== undefined ? preparedInput : slot.role === "worker" && typeof selectedGuidance === "string"
614
+ ? guidanceProbeWorkerFrame(current.registration.snapshots.task, current.registration.snapshots.baselineContext, current.registration.snapshots.systemPolicy, selectedGuidance)
615
+ : preparedEditor;
616
+ if (typeof inputFrame !== "string" || Buffer.byteLength(inputFrame) === 0) return fail("invalid");
617
+ const preparedFrame: ProbePreparedFrame = { slotId: slot.id, sha256: probeHash(inputFrame), bytes: Buffer.byteLength(inputFrame) };
618
+ const result = this.store.reserveSession({ ...input, preparedFrame }, this.options.revalidate);
619
+ if (result.kind === "existing") return result.receipt;
620
+ const reservation = result.reservation;
621
+ try {
622
+ this.options.onReserved?.(reservation);
623
+ const state = this.store.read(input.key)!;
624
+ const snapshots = state.registration.snapshots, frame = { inputFrame, nonGuidanceInputSha256: preparedNonGuidance ?? guidanceProbeNonGuidanceInputHash(snapshots.task, snapshots.baselineContext, snapshots.systemPolicy) };
625
+ let effectsOpen = true;
626
+ const pendingEffects = new Set<Promise<void>>();
627
+ const effects = this.effects(reservation, signal, {
628
+ open: () => effectsOpen,
629
+ track: () => {
630
+ let resolve!: () => void;
631
+ const joined = new Promise<void>(complete => { resolve = complete; });
632
+ pendingEffects.add(joined);
633
+ return () => { if (pendingEffects.delete(joined)) resolve(); };
634
+ },
635
+ });
636
+ if (signal.aborted || this.store.exposeLaunch(reservation, this.options.revalidate).state !== "active" || signal.aborted) return fail("held");
637
+ let launch: { kind: "observed"; observation: ProbeFakeObservation } | { kind: "failed"; error: unknown };
638
+ try {
639
+ const launched = ports.launch({ reservation, slot, manifest: state.registration.manifest,
640
+ inputFrame: frame.inputFrame, inputSha256: probeHash(frame.inputFrame), nonGuidanceInputSha256: frame.nonGuidanceInputSha256, purpose: "guidance_probe" }, effects, signal);
641
+ launch = await launched.then(observation => {
642
+ effectsOpen = false;
643
+ return { kind: "observed" as const, observation };
644
+ }, error => {
645
+ effectsOpen = false;
646
+ return { kind: "failed" as const, error };
647
+ });
648
+ } catch (error) {
649
+ effectsOpen = false;
650
+ launch = { kind: "failed", error };
651
+ }
652
+ // No effect may be admitted after the port settles. Still join every callback it registered before settling this session.
653
+ effectsOpen = false;
654
+ await Promise.allSettled([...pendingEffects]);
655
+ if (launch.kind === "failed") throw launch.error;
656
+ const observation = launch.observation;
657
+ const matched = this.matchObservation(observation, reservation, frame, slot.role === "worker");
658
+ 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");
661
+ } catch {
662
+ 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");
665
+ throw new GuidanceProbeError("held");
666
+ }
667
+ }
668
+ private matchObservation(value: ProbeFakeObservation, reservation: ProbeReservation,
669
+ frame: { inputFrame: string; nonGuidanceInputSha256: string }, worker: boolean): boolean {
670
+ return !!value && same(value.reservation, reservation) && ["closed_fixture", "failed_known", "unknown"].includes(value.outcome)
671
+ && value.servedModel === GUIDANCE_PROBE_MODEL && value.inputFrameHash === probeHash(frame.inputFrame)
672
+ && (worker ? value.workerEffectiveInputHash === probeHash(frame.inputFrame) && value.nonGuidanceInputSha256 === frame.nonGuidanceInputSha256
673
+ : value.workerEffectiveInputHash === null && value.nonGuidanceInputSha256 === null)
674
+ && (value.candidateArtifactSha256 === null || probeSha256(value.candidateArtifactSha256));
675
+ }
676
+ private effects(reservation: ProbeReservation, signal: AbortSignal, lifetime: EffectLifetime): ProbeFakeEffects {
677
+ const current = (): void => {
678
+ if (!lifetime.open() || signal.aborted || this.store.checkInvocation(reservation, this.options.revalidate).state !== "active" || signal.aborted) return fail("held");
679
+ };
680
+ return { current, runEffect: <T>(request: ProbeFakeEffectRequest, effect: (signal: AbortSignal) => Promise<ProbeFakeEffectValue<T>>): Promise<ProbeFakeEffectResult<T>> => {
681
+ const operation = (async (): Promise<ProbeFakeEffectResult<T>> => {
682
+ if (!lifetime.open() || signal.aborted) return fail("held");
683
+ if (!request || !["model_calls", "tool_calls", "resources"].includes(request.unit)) return fail("invalid");
684
+ const extra = resourceCharges(request.charges);
685
+ if (request.unit === "resources" && (request.reservedTokens !== undefined || !extra || !Object.values(extra).some(value => value > 0))) return fail("invalid");
686
+ const requested: ProbeEffectAdmission = { reservation, sequence: request.sequence,
687
+ unit: request.unit === "resources" ? "input_bytes" : request.unit, amount: request.unit === "resources" ? 0 : 1,
688
+ descriptorSha256: request.descriptorSha256, ...(request.reservedTokens === undefined ? {} : { reservedTokens: request.reservedTokens }),
689
+ ...(extra === undefined ? {} : { charges: extra }), now: this.options.now() };
690
+ const granted = this.store.admitEffect(requested, this.options.revalidate);
691
+ if (granted.kind === "existing") return granted;
692
+ const admission = granted.admission, release = lifetime.track();
693
+ try {
694
+ current();
695
+ const result = await effect(signal);
696
+ const observed = result.usage, visibleHash = probeHash(canonical({ request, usage: observed }));
697
+ if (request.unit === "resources" && observed !== 0) this.store.latchHold(reservation, "usage");
698
+ if (result.observationSha256 !== visibleHash) this.store.latchHold(reservation, "observation");
699
+ this.store.recordUsage({ admission, observed, observationSha256: probeHash(canonical({ admission, observed })) });
700
+ this.store.settleEffect({ admission, outcome: "settled" });
701
+ return { kind: "executed", value: result.value };
702
+ } catch {
703
+ const observed = null;
704
+ this.store.recordUsage({ admission, observed, observationSha256: probeHash(canonical({ admission, observed })) });
705
+ this.store.settleEffect({ admission, outcome: "unknown" });
706
+ throw new GuidanceProbeError("held");
707
+ } finally { release(); }
708
+ })();
709
+ void operation.catch(() => {});
710
+ return operation;
711
+ } };
712
+ }
713
+ }