@staix/agent-hub 0.36.0 → 0.38.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.
- package/CHANGELOG.md +27 -0
- package/README.md +6 -2
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +13 -3
- package/docs/agent-notes/daemon.md +4 -4
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +2 -1
- package/docs/agent-notes/tasks.md +1 -1
- package/docs/agent-notes/tests.md +1 -2
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +43 -2
- package/docs/design/agent-hub-architecture.md +9 -1
- package/docs/design/guidance-probes.md +1167 -0
- package/docs/design/model-routes.md +437 -12
- package/docs/dogfood.md +12 -13
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +123 -151
- package/docs/profiles.md +1 -1
- package/docs/quickstart.md +15 -3
- package/docs/research.md +1 -1
- package/docs/sdlc.md +5 -3
- package/docs/security.md +25 -1
- package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
- package/docs/verification/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-0.38.0.md +41 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
- package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verified.json +25 -25
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +2403 -1444
- package/plugins/agent-hub/server.js +2480 -1509
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +2 -1
- package/src/adapters/compat.ts +1 -1
- package/src/adapters/local-probe.ts +233 -0
- package/src/adapters/local-worker.ts +232 -21
- package/src/cli/console-state.ts +25 -6
- package/src/cli/console-versions.ts +99 -0
- package/src/cli/console.ts +13 -1
- package/src/cli/help.ts +2 -1
- package/src/cli/init.ts +3 -1
- package/src/cli/install-paths.ts +7 -2
- package/src/cli/main.ts +78 -7
- package/src/cli/output.ts +8 -4
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- package/src/cli/upgrade-runtime.ts +1 -1
- package/src/hub/bus.ts +2 -2
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +6 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +195 -13
- package/src/hub/envelope.ts +6 -1
- package/src/hub/events.ts +3 -2
- package/src/hub/guidance-probe-store.ts +1044 -0
- package/src/hub/guidance-probes.ts +692 -0
- package/src/hub/inference.ts +18 -5
- package/src/hub/manager.ts +24 -1
- package/src/hub/operational-authority.ts +14 -1
- package/src/hub/peers.ts +5 -0
- package/src/hub/person-command.ts +25 -0
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +23 -16
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +7 -0
- package/src/hub/sdlc-release-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +59 -7
- package/src/hub/supervision.ts +3 -2
- package/src/hub/tasks.ts +363 -7
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +110 -0
- package/src/local/probe-workspace.ts +426 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +21 -17
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +114 -19
- package/src/models/route/escalation-control.ts +30 -0
- package/src/models/route/hub-prompts.ts +97 -0
- package/src/models/route/judge-choice.ts +155 -0
- package/src/models/route/judge-replies.ts +102 -0
- package/src/models/route/labels.ts +14 -70
- package/src/models/route/observation-signals.ts +250 -0
- package/src/models/route/plan-execute-choice.ts +27 -0
- package/src/models/route/relay-selector.ts +2 -2
- package/src/models/route/runtime.ts +115 -52
- package/src/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- package/src/ui/guidance-panel.ts +34 -2
- package/src/ui/guidance-view.ts +33 -0
- package/src/ui/plugin.ts +80 -23
- package/src/version.ts +4 -0
- package/templates/AGENTS.block.md +14 -14
- package/templates/adec/README.md +32 -0
- package/templates/adec/ahub.plan-execute.json +23 -0
- package/templates/adec/ahub.stage.json +23 -0
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
- package/LICENSES/Apache-2.0.txt +0 -204
- package/src/models/route/advisor.ts +0 -102
- package/src/models/route/escalation.ts +0 -82
- package/src/models/route/judge.ts +0 -23
- package/src/models/route/normalize.ts +0 -103
- package/src/models/route/plan-execute.ts +0 -52
- package/src/models/route/prompts.ts +0 -8
- package/src/models/route/signals.ts +0 -247
- package/src/models/route/state.ts +0 -54
- package/src/models/route/text.ts +0 -61
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
|
|
4
|
+
|
|
5
|
+
/** Published V1 format/admission bounds, not native execution guarantees. */
|
|
6
|
+
export const GUIDANCE_PROBE_LIMITS = Object.freeze({ recordBytes: 32768, snapshotBytes: 32768,
|
|
7
|
+
storageBytes: 1073741824, workerAttempts: 4, editorAttempts: 5, slots: 9, hashLength: 64 });
|
|
8
|
+
const registrationScaffoldBytes = Buffer.byteLength(JSON.stringify({ manifest: 0, snapshots: { task: "", baselineContext: "", dataPolicy: 0, systemPolicy: "", improverContext: "" } }));
|
|
9
|
+
/** Closed composition bounds, separate from each admitted manifest/snapshot ceiling. */
|
|
10
|
+
export const GUIDANCE_PROBE_REGISTRATION_BYTES = GUIDANCE_PROBE_LIMITS.recordBytes + GUIDANCE_PROBE_LIMITS.snapshotBytes
|
|
11
|
+
+ 4 * 2 * GUIDANCE_PROBE_LIMITS.snapshotBytes + registrationScaffoldBytes;
|
|
12
|
+
export const GUIDANCE_PROBE_SESSION_BYTES = 4 * GUIDANCE_PROBE_LIMITS.recordBytes;
|
|
13
|
+
export const GUIDANCE_PROBE_STOP_TIMEOUT_MS = 5000;
|
|
14
|
+
export const GUIDANCE_PROBE_FENCE_INTERVAL_MS = 250;
|
|
15
|
+
export const GUIDANCE_PROBE_MODEL = "qwen27b/qwen3.8-27b";
|
|
16
|
+
export type ProbeInteger = number;
|
|
17
|
+
export type ProbeSha256 = string;
|
|
18
|
+
export type ProbeId = string;
|
|
19
|
+
export type ProbeTree = { objectFormat: "sha1"; oid: string } | { objectFormat: "sha256"; oid: string };
|
|
20
|
+
export interface ProbeSnapshotRef { sha256: string; bytes: number }
|
|
21
|
+
export interface ProbeRoleIdentity { id: string; layer: "shipped" | "project"; baselineSha256: string }
|
|
22
|
+
export type ProbeArm = "baseline" | "candidate1" | "candidate2" | "successor";
|
|
23
|
+
export type ProbeStage = "baseline" | "proposal1" | "candidate1" | "proposal2" | "candidate2" | "compose" | "successor" | "select" | "reflect";
|
|
24
|
+
export interface ProbeSlot { id: string; stage: ProbeStage; role: "worker" | "proposal" | "compose" | "select" | "reflect"; arm: ProbeArm | "none"; retryOf?: string }
|
|
25
|
+
export interface GuidanceProbeManifestV1 {
|
|
26
|
+
v: 1; projectKey: string; experimentId: string;
|
|
27
|
+
task: { id: number; created: number; flowRevision: number };
|
|
28
|
+
role: ProbeRoleIdentity;
|
|
29
|
+
inputs: { task: ProbeSnapshotRef; baselineContext: ProbeSnapshotRef; dataPolicy: ProbeSnapshotRef; systemPolicy: ProbeSnapshotRef; codeTree: ProbeTree };
|
|
30
|
+
runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string };
|
|
31
|
+
model: { requested: typeof GUIDANCE_PROBE_MODEL; expectedServed: typeof GUIDANCE_PROBE_MODEL };
|
|
32
|
+
guidance: { baselineSha256: string };
|
|
33
|
+
improverContextHash?: string; improverContextBytes?: number;
|
|
34
|
+
slots: readonly ProbeSlot[];
|
|
35
|
+
limits: { modelCalls: number; toolCalls: number; elapsedMs: number; tokens?: number; inputBytes: number; scratchBytes: number; outputBytes: number };
|
|
36
|
+
taskOrderSeed?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface ProbeDataPolicyV1 {
|
|
39
|
+
v: 1;
|
|
40
|
+
allowedWrites: readonly { root: "scratch" | "output"; relative: string }[];
|
|
41
|
+
admittedData: readonly { id: string; sha256: string; bytes: number }[];
|
|
42
|
+
roles: {
|
|
43
|
+
worker: { dataIds: readonly string[]; guidanceOnlyExperience: true };
|
|
44
|
+
proposal: { dataIds: readonly string[]; improverContext: boolean };
|
|
45
|
+
compose: { dataIds: readonly string[]; improverContext: boolean };
|
|
46
|
+
select: { dataIds: readonly string[]; anonymizedDeliverables: true };
|
|
47
|
+
reflect: { dataIds: readonly string[]; closedRoundOnly: true };
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export interface ProbePrivateSnapshots { task: string; baselineContext: string; dataPolicy: ProbeDataPolicyV1; systemPolicy: string; improverContext?: string }
|
|
51
|
+
export interface ProbeRegistrationV1 { manifest: GuidanceProbeManifestV1; snapshots: ProbePrivateSnapshots }
|
|
52
|
+
export type ProbeState = "declared" | "active" | "closing" | "closed_fixture" | "failed_fixture" | "unknown_held";
|
|
53
|
+
export type ProbeSessionState = "planned" | "reserved" | "running" | "failed_known" | "closed_fixture" | "not_needed" | "unknown_held";
|
|
54
|
+
export type ProbeBudgetUnit = "model_calls" | "tool_calls" | "tokens" | "input_bytes" | "scratch_bytes" | "output_bytes";
|
|
55
|
+
export interface ProbeKey { projectKey: string; id: string }
|
|
56
|
+
export interface ProbeHostBinding {
|
|
57
|
+
projectKey: string; actor: string; task: { id: number; created: number; flowRevision: number }; role: ProbeRoleIdentity;
|
|
58
|
+
baselineGuidance: string; sessionGeneration: number | string; nativeSession: string | null; requestConnectionId: string;
|
|
59
|
+
}
|
|
60
|
+
export interface ProbeChildBinding {
|
|
61
|
+
variantId: string; candidateSha256: string; guidanceSha256: string; task: ProbeHostBinding["task"]; role: ProbeRoleIdentity; guidance: string;
|
|
62
|
+
authoring: "admitted_fixture" | "uncontrolled"; sourceSessionId: string | null;
|
|
63
|
+
}
|
|
64
|
+
export interface ProbeAdmissionRecheck { host: ProbeHostBinding; child?: ProbeChildBinding }
|
|
65
|
+
/** Hash/size of the exact frame built once by the trusted host before atomic admission. */
|
|
66
|
+
export interface ProbePreparedFrame { slotId: string; sha256: string; bytes: number }
|
|
67
|
+
export interface ProbePreparedWorkerFrame { inputFrame: string; nonGuidanceInputSha256: string }
|
|
68
|
+
export type ProbeWorkerFramePreparer = (state: ProbeStoredState, slot: ProbeSlot, guidance: string) => ProbePreparedWorkerFrame | Promise<ProbePreparedWorkerFrame>;
|
|
69
|
+
export interface ProbeResourceCharges { inputBytes?: number; scratchBytes?: number; outputBytes?: number }
|
|
70
|
+
export interface ProbeSessionAdmission {
|
|
71
|
+
key: ProbeKey; expectedRevision: number; host: ProbeHostBinding; child?: ProbeChildBinding; preparedFrame?: ProbePreparedFrame; now: number;
|
|
72
|
+
}
|
|
73
|
+
export interface ProbeReservation { key: ProbeKey; slotId: string; generation: number; revision: number }
|
|
74
|
+
export interface ProbeStartSelector {
|
|
75
|
+
requestedRevision: number; slotId: string; variantId: string | null; inputFrameSha256: string | null; inputFrameBytes: number;
|
|
76
|
+
actor: string; sessionGeneration: number | string; nativeSession: string | null; requestConnectionId: string;
|
|
77
|
+
}
|
|
78
|
+
export interface ProbeReceipt { id: string; revision: number; state: ProbeState; already: boolean }
|
|
79
|
+
export type ProbeReservationResult = { kind: "granted"; reservation: ProbeReservation } | { kind: "existing"; receipt: ProbeReceipt };
|
|
80
|
+
export interface ProbeEffectAdmission { reservation: ProbeReservation; sequence: number; unit: ProbeBudgetUnit; amount: number; reservedTokens?: number; charges?: ProbeResourceCharges; descriptorSha256: string; now: number }
|
|
81
|
+
export type ProbeEffectAdmissionResult = { kind: "granted"; admission: ProbeEffectAdmission } | { kind: "existing"; state: "pending" | "settled" | "unknown" };
|
|
82
|
+
export interface ProbeEffectSettlement { admission: ProbeEffectAdmission; outcome: "settled" | "unknown" }
|
|
83
|
+
export interface ProbeSessionSettlement { reservation: ProbeReservation; outcome: "closed_fixture" | "failed_known" | "unknown"; candidateArtifactSha256: string | null; now: number }
|
|
84
|
+
export interface ProbeSessionCoverage {
|
|
85
|
+
inputFrameSha256: string | null; inputFrameBytes: number; launchExposed: boolean; preLaunchFailure: boolean;
|
|
86
|
+
modelCalls: number; modelUsageKnown: number; toolCalls: number; toolUsageKnown: number;
|
|
87
|
+
usageUnknown: boolean; coverageVerified: boolean;
|
|
88
|
+
/** Tokens this session alone observed (T3). Optional: sessions written before it have none, which reads as 0 known tokens only when no model call ran unobserved. */
|
|
89
|
+
tokensObserved?: number;
|
|
90
|
+
}
|
|
91
|
+
export interface ProbeUsageObservation { admission: ProbeEffectAdmission; observed: number | null; observationSha256: string }
|
|
92
|
+
export interface ProbeCancellation { key: ProbeKey; expectedRevision: number; host: ProbeHostBinding }
|
|
93
|
+
export interface ProbeCounters {
|
|
94
|
+
workerAttempts: number; editorAttempts: number; modelCalls: number; toolCalls: number; tokensReserved: number; tokensObservedKnown: number;
|
|
95
|
+
inputBytes: number; scratchBytes: number; outputBytes: number; elapsedHighWaterMs: number; usageUnknown: boolean;
|
|
96
|
+
}
|
|
97
|
+
/** Why a session settled, recorded once when it settled so a receipt is derived from the session's own facts and never from experiment state that moves later. */
|
|
98
|
+
export type ProbeCloseCause = "none" | "cancel" | "elapsed" | "hold" | "crash";
|
|
99
|
+
export interface ProbeSession {
|
|
100
|
+
slotId: string; generation: number; revision: number; state: ProbeSessionState; candidateArtifactSha256: string | null;
|
|
101
|
+
closeCause?: ProbeCloseCause;
|
|
102
|
+
child?: ProbeChildBinding;
|
|
103
|
+
start?: ProbeStartSelector;
|
|
104
|
+
coverage: ProbeSessionCoverage;
|
|
105
|
+
}
|
|
106
|
+
export interface ProbeStoredState {
|
|
107
|
+
registration: ProbeRegistrationV1; binding: ProbeHostBinding; receipt: ProbeReceipt; counters: ProbeCounters;
|
|
108
|
+
firstReservedAt: number | null; admissionHold: "none" | "elapsed" | "observation" | "usage"; cancelRequested: boolean; notNeeded: number; sessions: readonly ProbeSession[];
|
|
109
|
+
}
|
|
110
|
+
export interface ProbeIntegrity { experiments: number; sessions: number; digest: string }
|
|
111
|
+
export interface ProbeFakeLaunch { reservation: ProbeReservation; slot: ProbeSlot; manifest: GuidanceProbeManifestV1; inputFrame: string; inputSha256: string; nonGuidanceInputSha256: string; purpose: "guidance_probe" }
|
|
112
|
+
export interface ProbeFakeObservation {
|
|
113
|
+
reservation: ProbeReservation; outcome: "closed_fixture" | "failed_known" | "unknown"; servedModel: string | null;
|
|
114
|
+
inputFrameHash: string | null;
|
|
115
|
+
workerEffectiveInputHash: string | null; nonGuidanceInputSha256: string | null; candidateArtifactSha256: string | null; usage: "known_fixture" | "unknown";
|
|
116
|
+
/** What the host measured of the finished session (T3). The adapter cannot supply `startedAt`: the host samples it when it exposes the launch. */
|
|
117
|
+
measured?: Omit<ProbeMeasuredSession, "startedAt">;
|
|
118
|
+
}
|
|
119
|
+
export interface ProbeFakeStop { reservation: ProbeReservation }
|
|
120
|
+
export interface ProbeFakeStopObservation { reservation: ProbeReservation; stopped: "known_fixture" | "unknown" }
|
|
121
|
+
export interface ProbeFakeEffectRequest { sequence: number; unit: "model_calls" | "tool_calls" | "resources"; descriptorSha256: string; reservedTokens?: number; charges?: ProbeResourceCharges }
|
|
122
|
+
export interface ProbeFakeEffectValue<T> { value: T; usage: number | null; observationSha256: string }
|
|
123
|
+
export type ProbeFakeEffectResult<T> = { kind: "executed"; value: T } | { kind: "existing"; state: "pending" | "settled" | "unknown" };
|
|
124
|
+
export interface ProbeFakeEffects {
|
|
125
|
+
/** Fresh captured actor/G1/ledger fence; no authority is reconstructed from metadata. */
|
|
126
|
+
current(): void;
|
|
127
|
+
runEffect<T>(request: ProbeFakeEffectRequest, effect: (signal: AbortSignal) => Promise<ProbeFakeEffectValue<T>>): Promise<ProbeFakeEffectResult<T>>;
|
|
128
|
+
}
|
|
129
|
+
/** Host test constructor only: never selected by manifest, configuration or a wire field. */
|
|
130
|
+
export interface GuidanceProbeFakePorts {
|
|
131
|
+
launch(input: ProbeFakeLaunch, effects: ProbeFakeEffects, signal: AbortSignal): Promise<ProbeFakeObservation>;
|
|
132
|
+
stop(input: ProbeFakeStop, signal: AbortSignal): Promise<ProbeFakeStopObservation>;
|
|
133
|
+
/**
|
|
134
|
+
* Remove output the port itself retained for a launch whose measurement the host did not seal with that record: an observation that did not match the
|
|
135
|
+
* reservation (a fallback model, for one), a failed seal, a settlement that lost its clock. Without it that directory has no row, so no prune could ever
|
|
136
|
+
* reach it. The port removes only what it created, by the identity it captured, and never throws into the host.
|
|
137
|
+
*/
|
|
138
|
+
discardRetained?(retained: ProbeRetainedRecord): void;
|
|
139
|
+
}
|
|
140
|
+
export interface ProbePublicReceipt extends ProbeReceipt { experimentId: string; taskId: number; evidence: "declaration" | "fixture" | "unknown" }
|
|
141
|
+
export interface ProbePublicStatus extends ProbePublicReceipt { counters: ProbeCounters; cancelRequested: boolean; notNeeded: number; comparable: boolean; authoring: "admitted_fixture" | "uncontrolled" | "unknown" }
|
|
142
|
+
export type GuidanceProbeCommand = { op: "register"; file: string; json: boolean }
|
|
143
|
+
| { op: "start"; id: string; revision: number; variantId?: string; json: boolean }
|
|
144
|
+
| { op: "show"; id: string; json: boolean } | { op: "receipts"; id: string; json: boolean } | { op: "cancel"; id: string; revision: number; json: boolean };
|
|
145
|
+
|
|
146
|
+
export class GuidanceProbeError extends Error {
|
|
147
|
+
constructor(readonly reason: "invalid" | "changed" | "budget" | "held" | "runner" | "storage") {
|
|
148
|
+
super({ invalid: "invalid probe fields or bounds; reload the closed V1 declaration before retrying",
|
|
149
|
+
changed: "probe binding or revision changed; read the current task, G1 and probe before retrying",
|
|
150
|
+
budget: "probe aggregate budget is exhausted or unknown; inspect the retained accounting before a separate experiment",
|
|
151
|
+
held: "probe outcome is uncertain or already active; inspect retained state without replaying work",
|
|
152
|
+
runner: "probe runner is unavailable in production T1; use fake-only fixtures, not a live launch",
|
|
153
|
+
storage: "probe storage is invalid or unavailable; inspect retained probe state before retrying" }[reason]);
|
|
154
|
+
this.name = "GuidanceProbeError";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const invalid = (): never => { throw new GuidanceProbeError("invalid"); };
|
|
158
|
+
export const probeHash = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex");
|
|
159
|
+
export const probeInteger = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
160
|
+
export const probeSha256 = (value: unknown): value is string => typeof value === "string" && value.length === GUIDANCE_PROBE_LIMITS.hashLength && /^[a-f0-9]+$/.test(value);
|
|
161
|
+
const identity = (value: unknown): value is string => executionText(value, EXECUTION_REFERENCE_LIMITS.id) && !/\p{Cf}/u.test(value);
|
|
162
|
+
export const probeSessionGeneration = (value: unknown): value is number | string => probeInteger(value) || identity(value);
|
|
163
|
+
const required = (condition: unknown): void => { if (!condition) invalid(); };
|
|
164
|
+
|
|
165
|
+
/** Bounded inert copy: no getter, iterator, proxy, toJSON, sparse array or cycle is evaluated. */
|
|
166
|
+
function inert(value: unknown, maximum: number): unknown {
|
|
167
|
+
let remaining = maximum;
|
|
168
|
+
const seen = new Set<object>();
|
|
169
|
+
const charge = (bytes: number) => { remaining -= bytes; if (remaining < 0) invalid(); };
|
|
170
|
+
const copy = (item: unknown): unknown => {
|
|
171
|
+
if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) { charge(Buffer.byteLength(JSON.stringify(item))); return item; }
|
|
172
|
+
if (typeof item === "string") { if (item.length > remaining) invalid(); charge(Buffer.byteLength(JSON.stringify(item))); return item; }
|
|
173
|
+
if (!item || typeof item !== "object" || types.isProxy(item) || seen.has(item)) return invalid();
|
|
174
|
+
const array = Array.isArray(item), proto = Object.getPrototypeOf(item);
|
|
175
|
+
if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) return invalid();
|
|
176
|
+
const keys = Reflect.ownKeys(item);
|
|
177
|
+
if (keys.length > remaining) return invalid();
|
|
178
|
+
seen.add(item); charge(2);
|
|
179
|
+
if (array) {
|
|
180
|
+
const length = Object.getOwnPropertyDescriptor(item, "length")?.value;
|
|
181
|
+
if (!probeInteger(length) || keys.length !== length + 1) return invalid();
|
|
182
|
+
const result: unknown[] = [];
|
|
183
|
+
for (let index = 0; index < length; index++) {
|
|
184
|
+
const field = Object.getOwnPropertyDescriptor(item, String(index));
|
|
185
|
+
if (!field || !("value" in field) || !field.enumerable) return invalid();
|
|
186
|
+
if (index) charge(1); result.push(copy(field.value));
|
|
187
|
+
}
|
|
188
|
+
seen.delete(item); return result;
|
|
189
|
+
}
|
|
190
|
+
const result: Record<string, unknown> = Object.create(null);
|
|
191
|
+
let index = 0;
|
|
192
|
+
for (const key of keys) {
|
|
193
|
+
if (typeof key !== "string") return invalid();
|
|
194
|
+
const field = Object.getOwnPropertyDescriptor(item, key);
|
|
195
|
+
if (!field || !("value" in field) || !field.enumerable) return invalid();
|
|
196
|
+
charge(Buffer.byteLength(JSON.stringify(key)) + 1 + (index++ ? 1 : 0)); result[key] = copy(field.value);
|
|
197
|
+
}
|
|
198
|
+
seen.delete(item); return result;
|
|
199
|
+
};
|
|
200
|
+
return copy(value);
|
|
201
|
+
}
|
|
202
|
+
function object(value: unknown, keys: readonly string[], optional: readonly string[] = []): Record<string, unknown> {
|
|
203
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
|
|
204
|
+
const fields = value as Record<string, unknown>;
|
|
205
|
+
if (Object.keys(fields).some(key => !keys.includes(key) && !optional.includes(key)) || keys.some(key => !Object.hasOwn(fields, key))) return invalid();
|
|
206
|
+
return fields;
|
|
207
|
+
}
|
|
208
|
+
function canonical(value: unknown): string {
|
|
209
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
210
|
+
if (value && typeof value === "object") return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`).join(",")}}`;
|
|
211
|
+
return JSON.stringify(value);
|
|
212
|
+
}
|
|
213
|
+
export const guidanceProbeCanonical = (value: unknown, maximum: number = GUIDANCE_PROBE_LIMITS.recordBytes): string => canonical(inert(value, maximum));
|
|
214
|
+
function ref(value: unknown): void { const fields = object(value, ["sha256", "bytes"]); required(probeSha256(fields.sha256) && probeInteger(fields.bytes) && fields.bytes <= GUIDANCE_PROBE_LIMITS.snapshotBytes); }
|
|
215
|
+
function role(value: unknown): void { const fields = object(value, ["id", "layer", "baselineSha256"]); required(identity(fields.id) && ["shipped", "project"].includes(fields.layer as string) && probeSha256(fields.baselineSha256)); }
|
|
216
|
+
const graph: readonly [ProbeStage, ProbeSlot["role"], ProbeSlot["arm"]][] = [
|
|
217
|
+
["baseline", "worker", "baseline"], ["proposal1", "proposal", "none"], ["candidate1", "worker", "candidate1"],
|
|
218
|
+
["proposal2", "proposal", "none"], ["candidate2", "worker", "candidate2"], ["compose", "compose", "none"],
|
|
219
|
+
["successor", "worker", "successor"], ["select", "select", "none"], ["reflect", "reflect", "none"] ];
|
|
220
|
+
function slots(value: unknown): void {
|
|
221
|
+
required(Array.isArray(value) && value.length > 0 && value.length <= GUIDANCE_PROBE_LIMITS.slots);
|
|
222
|
+
const list = value as ProbeSlot[], ids = new Set<string>(), counts = new Map<string, number>();
|
|
223
|
+
let last = -1;
|
|
224
|
+
for (const slot of list) {
|
|
225
|
+
const fields = object(slot, ["id", "stage", "role", "arm"], ["retryOf"]), position = graph.findIndex(item => item[0] === fields.stage);
|
|
226
|
+
required(identity(fields.id) && !ids.has(fields.id as string) && position >= 0);
|
|
227
|
+
required(graph[position]![1] === fields.role && graph[position]![2] === fields.arm);
|
|
228
|
+
if (Object.hasOwn(fields, "retryOf")) {
|
|
229
|
+
const prior = list[ids.size - 1];
|
|
230
|
+
required(identity(fields.retryOf) && prior && prior.id === fields.retryOf && prior.stage === fields.stage && position === last);
|
|
231
|
+
} else { required(position > last); last = position; }
|
|
232
|
+
ids.add(slot.id); counts.set(slot.role, (counts.get(slot.role) ?? 0) + 1);
|
|
233
|
+
}
|
|
234
|
+
required(list[0]!.stage === "baseline" && list.some(item => item.stage === "candidate1"));
|
|
235
|
+
required(!list.some(item => item.stage === "proposal2") || list.some(item => item.stage === "candidate2"));
|
|
236
|
+
required(!list.some(item => item.stage === "compose") || list.some(item => item.stage === "successor"));
|
|
237
|
+
required((counts.get("worker") ?? 0) <= GUIDANCE_PROBE_LIMITS.workerAttempts && (counts.get("proposal") ?? 0) <= 2
|
|
238
|
+
&& ["compose", "select", "reflect"].every(key => (counts.get(key) ?? 0) <= 1)
|
|
239
|
+
&& list.filter(item => item.role !== "worker").length <= GUIDANCE_PROBE_LIMITS.editorAttempts);
|
|
240
|
+
}
|
|
241
|
+
function manifest(value: unknown): GuidanceProbeManifestV1 {
|
|
242
|
+
const fields = object(value, ["v", "projectKey", "experimentId", "task", "role", "inputs", "runtime", "model", "guidance", "slots", "limits"], ["improverContextHash", "improverContextBytes", "taskOrderSeed"]);
|
|
243
|
+
required(fields.v === 1 && identity(fields.projectKey) && identity(fields.experimentId));
|
|
244
|
+
const task = object(fields.task, ["id", "created", "flowRevision"]); required(probeInteger(task.id) && task.id > 0 && probeInteger(task.created) && probeInteger(task.flowRevision)); role(fields.role);
|
|
245
|
+
const inputs = object(fields.inputs, ["task", "baselineContext", "dataPolicy", "systemPolicy", "codeTree"]);
|
|
246
|
+
for (const key of ["task", "baselineContext", "dataPolicy", "systemPolicy"]) ref(inputs[key]);
|
|
247
|
+
const tree = object(inputs.codeTree, ["objectFormat", "oid"]), oidLength = tree.objectFormat === "sha1" ? 40 : tree.objectFormat === "sha256" ? GUIDANCE_PROBE_LIMITS.hashLength : 0;
|
|
248
|
+
required(typeof tree.oid === "string" && oidLength > 0 && tree.oid.length === oidLength && /^[a-f0-9]+$/.test(tree.oid));
|
|
249
|
+
const runtime = object(fields.runtime, ["runtimeSha256", "toolsetSha256", "modelConfigSha256"]); required(Object.values(runtime).every(probeSha256));
|
|
250
|
+
const model = object(fields.model, ["requested", "expectedServed"]); required(model.requested === GUIDANCE_PROBE_MODEL && model.expectedServed === GUIDANCE_PROBE_MODEL);
|
|
251
|
+
required(probeSha256(object(fields.guidance, ["baselineSha256"]).baselineSha256));
|
|
252
|
+
const limits = object(fields.limits, ["modelCalls", "toolCalls", "elapsedMs", "inputBytes", "scratchBytes", "outputBytes"], ["tokens"]);
|
|
253
|
+
required(Object.values(limits).every(probeInteger));
|
|
254
|
+
let bytes = GUIDANCE_PROBE_LIMITS.storageBytes;
|
|
255
|
+
for (const key of ["inputBytes", "scratchBytes", "outputBytes"]) { required((limits[key] as number) <= bytes); bytes -= limits[key] as number; }
|
|
256
|
+
required(Object.hasOwn(fields, "improverContextHash") === Object.hasOwn(fields, "improverContextBytes"));
|
|
257
|
+
if (Object.hasOwn(fields, "improverContextHash")) { required(probeSha256(fields.improverContextHash)); required(probeInteger(fields.improverContextBytes) && fields.improverContextBytes <= GUIDANCE_PROBE_LIMITS.snapshotBytes); }
|
|
258
|
+
if (Object.hasOwn(fields, "taskOrderSeed")) required(probeInteger(fields.taskOrderSeed));
|
|
259
|
+
slots(fields.slots);
|
|
260
|
+
return fields as unknown as GuidanceProbeManifestV1;
|
|
261
|
+
}
|
|
262
|
+
export function parseGuidanceProbeManifest(value: unknown): GuidanceProbeManifestV1 | undefined {
|
|
263
|
+
try { return manifest(inert(value, GUIDANCE_PROBE_LIMITS.recordBytes)); } catch { return undefined; }
|
|
264
|
+
}
|
|
265
|
+
export function guidanceProbeManifestKey(value: GuidanceProbeManifestV1): string {
|
|
266
|
+
const parsed = parseGuidanceProbeManifest(value); if (!parsed) return invalid();
|
|
267
|
+
return probeHash(`agent-hub.guidance-probe.v1\n${guidanceProbeCanonical(parsed)}`);
|
|
268
|
+
}
|
|
269
|
+
function policy(value: unknown): ProbeDataPolicyV1 {
|
|
270
|
+
const fields = object(value, ["v", "allowedWrites", "admittedData", "roles"]); required(fields.v === 1 && Array.isArray(fields.allowedWrites) && Array.isArray(fields.admittedData));
|
|
271
|
+
const ids = new Set<string>(), writes = new Set<string>();
|
|
272
|
+
for (const write of fields.allowedWrites as unknown[]) {
|
|
273
|
+
const row = object(write, ["root", "relative"]); required(["scratch", "output"].includes(row.root as string) && identity(row.relative));
|
|
274
|
+
const name = row.relative as string; required(!name.includes("\\") && !name.startsWith("/") && !/^[a-z]:/i.test(name) && name.split("/").every(part => part && part !== "." && part !== ".."));
|
|
275
|
+
const key = `${row.root}/${name}`; required(!writes.has(key)); writes.add(key);
|
|
276
|
+
}
|
|
277
|
+
for (const data of fields.admittedData as unknown[]) { const row = object(data, ["id", "sha256", "bytes"]); required(identity(row.id) && !ids.has(row.id as string) && probeSha256(row.sha256) && probeInteger(row.bytes)); ids.add(row.id as string); }
|
|
278
|
+
const roles = object(fields.roles, ["worker", "proposal", "compose", "select", "reflect"]);
|
|
279
|
+
for (const [name, flag] of [["worker", "guidanceOnlyExperience"], ["proposal", "improverContext"], ["compose", "improverContext"], ["select", "anonymizedDeliverables"], ["reflect", "closedRoundOnly"]] as const) {
|
|
280
|
+
const row = object(roles[name], ["dataIds", flag]); required(Array.isArray(row.dataIds) && typeof row[flag] === "boolean" && (flag === "improverContext" || row[flag] === true));
|
|
281
|
+
const used = new Set<string>(); for (const id of row.dataIds as unknown[]) { required(identity(id) && ids.has(id as string) && !used.has(id as string)); used.add(id as string); }
|
|
282
|
+
}
|
|
283
|
+
return fields as unknown as ProbeDataPolicyV1;
|
|
284
|
+
}
|
|
285
|
+
export function parseGuidanceProbeRegistration(value: unknown): ProbeRegistrationV1 | undefined {
|
|
286
|
+
try {
|
|
287
|
+
// Inspect envelope/snapshot descriptors before any potentially large nested traversal.
|
|
288
|
+
if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
|
|
289
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return undefined;
|
|
290
|
+
const names = Reflect.ownKeys(value);
|
|
291
|
+
if (names.length !== 2 || !names.includes("manifest") || !names.includes("snapshots")) return undefined;
|
|
292
|
+
const envelope = Object.getOwnPropertyDescriptors(value);
|
|
293
|
+
if (Object.values(envelope).some(item => !("value" in item) || !item.enumerable)) return undefined;
|
|
294
|
+
const parsed = parseGuidanceProbeManifest(envelope.manifest?.value); if (!parsed) return undefined;
|
|
295
|
+
const raw = envelope.snapshots?.value;
|
|
296
|
+
if (!raw || typeof raw !== "object" || types.isProxy(raw) || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw))) return undefined;
|
|
297
|
+
const snapshots: Record<string, unknown> = Object.create(null), keys = Reflect.ownKeys(raw);
|
|
298
|
+
if (keys.length > 5) return undefined;
|
|
299
|
+
for (const key of keys) {
|
|
300
|
+
if (typeof key !== "string" || !["task", "baselineContext", "dataPolicy", "systemPolicy", "improverContext"].includes(key)) return undefined;
|
|
301
|
+
const descriptor = Object.getOwnPropertyDescriptor(raw, key); if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return undefined;
|
|
302
|
+
if (key === "dataPolicy") snapshots[key] = policy(inert(descriptor.value, GUIDANCE_PROBE_LIMITS.snapshotBytes));
|
|
303
|
+
else { const text = descriptor.value; required(typeof text === "string" && Buffer.byteLength(text) <= GUIDANCE_PROBE_LIMITS.snapshotBytes
|
|
304
|
+
&& !/[\p{Cc}\p{Cs}]/u.test(text.replace(/[\t\r\n]/g, ""))); snapshots[key] = text; }
|
|
305
|
+
}
|
|
306
|
+
object(snapshots, ["task", "baselineContext", "dataPolicy", "systemPolicy"], ["improverContext"]);
|
|
307
|
+
required(Object.hasOwn(snapshots, "improverContext") === Object.hasOwn(parsed, "improverContextHash"));
|
|
308
|
+
let total = 0;
|
|
309
|
+
for (const key of ["task", "baselineContext", "dataPolicy", "systemPolicy", "improverContext"] as const) {
|
|
310
|
+
if (!Object.hasOwn(snapshots, key)) continue;
|
|
311
|
+
const text = key === "dataPolicy" ? guidanceProbeCanonical(snapshots[key]) : snapshots[key] as string;
|
|
312
|
+
const expected = key === "improverContext" ? { sha256: parsed.improverContextHash, bytes: parsed.improverContextBytes } : parsed.inputs[key];
|
|
313
|
+
required(Buffer.byteLength(text) === expected.bytes && probeHash(text) === expected.sha256); total += Buffer.byteLength(text);
|
|
314
|
+
}
|
|
315
|
+
required(total <= parsed.limits.inputBytes);
|
|
316
|
+
const result = { manifest: parsed, snapshots: snapshots as unknown as ProbePrivateSnapshots };
|
|
317
|
+
if (Buffer.byteLength(JSON.stringify(result)) > GUIDANCE_PROBE_REGISTRATION_BYTES) return undefined;
|
|
318
|
+
return result;
|
|
319
|
+
} catch { return undefined; }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function parseGuidanceProbeCommand(args: readonly string[]): GuidanceProbeCommand | undefined {
|
|
323
|
+
const op = args[0]; if (!["register", "start", "show", "receipts", "cancel"].includes(op ?? "")) return undefined;
|
|
324
|
+
const fields = new Map<string, string>(), allowed = op === "register" ? ["--file"] : op === "show" || op === "receipts" ? ["--id"] : op === "start" ? ["--id", "--revision", "--variant"] : ["--id", "--revision"];
|
|
325
|
+
let json = false;
|
|
326
|
+
for (let index = 1; index < args.length; index++) {
|
|
327
|
+
const key = args[index]!; if (key === "--json" && !json) { json = true; continue; }
|
|
328
|
+
const value = args[++index]; if (!allowed.includes(key) || fields.has(key) || !value || value.startsWith("--")) return undefined; fields.set(key, value);
|
|
329
|
+
}
|
|
330
|
+
if (op === "register") return fields.has("--file") ? { op, file: fields.get("--file")!, json } : undefined;
|
|
331
|
+
const id = fields.get("--id"); if (!probeSha256(id)) return undefined;
|
|
332
|
+
if (op === "show" || op === "receipts") return { op, id, json };
|
|
333
|
+
const raw = fields.get("--revision"), revision = raw && /^(?:0|[1-9][0-9]*)$/.test(raw) ? Number(raw) : NaN;
|
|
334
|
+
if (!probeInteger(revision)) return undefined;
|
|
335
|
+
if (op === "cancel") return { op, id, revision, json };
|
|
336
|
+
const variantId = fields.get("--variant"); if (variantId !== undefined && !probeSha256(variantId)) return undefined;
|
|
337
|
+
return { op: "start", id, revision, ...(variantId === undefined ? {} : { variantId }), json };
|
|
338
|
+
}
|
|
339
|
+
export function parseGuidanceProbeSubcommand(args: readonly string[]): GuidanceProbeCommand | undefined {
|
|
340
|
+
if (args[0] !== "probe") return undefined;
|
|
341
|
+
return parseGuidanceProbeCommand(args.slice(1)) ?? invalid();
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const probeStates: readonly ProbeState[] = ["declared", "active", "closing", "closed_fixture", "failed_fixture", "unknown_held"];
|
|
345
|
+
const publicEvidence = (value: unknown): value is ProbePublicReceipt["evidence"] => ["declaration", "fixture", "unknown"].includes(value as string);
|
|
346
|
+
function publicReceipt(value: unknown, status: boolean): ProbePublicReceipt | ProbePublicStatus | undefined {
|
|
347
|
+
try {
|
|
348
|
+
const extra = status ? ["counters", "cancelRequested", "notNeeded", "comparable", "authoring"] : [];
|
|
349
|
+
const fields = object(value, ["id", "revision", "state", "already", "taskId", "experimentId", "evidence", ...extra]);
|
|
350
|
+
required(probeSha256(fields.id) && probeInteger(fields.revision) && probeStates.includes(fields.state as ProbeState)
|
|
351
|
+
&& typeof fields.already === "boolean" && probeInteger(fields.taskId) && fields.taskId > 0
|
|
352
|
+
&& typeof fields.experimentId === "string" && fields.experimentId.length <= 256 && publicEvidence(fields.evidence));
|
|
353
|
+
if (!status) return fields as unknown as ProbePublicReceipt;
|
|
354
|
+
const counters = object(fields.counters, ["workerAttempts", "editorAttempts", "modelCalls", "toolCalls", "tokensReserved", "tokensObservedKnown",
|
|
355
|
+
"inputBytes", "scratchBytes", "outputBytes", "elapsedHighWaterMs", "usageUnknown"]);
|
|
356
|
+
required(Object.entries(counters).every(([key, item]) => key === "usageUnknown" ? typeof item === "boolean" : probeInteger(item))
|
|
357
|
+
&& typeof fields.cancelRequested === "boolean" && probeInteger(fields.notNeeded) && typeof fields.comparable === "boolean"
|
|
358
|
+
&& ["admitted_fixture", "uncontrolled", "unknown"].includes(fields.authoring as string));
|
|
359
|
+
return fields as unknown as ProbePublicStatus;
|
|
360
|
+
} catch { return undefined; }
|
|
361
|
+
}
|
|
362
|
+
export const parseGuidanceProbePublicReceipt = (value: unknown): ProbePublicReceipt | undefined => publicReceipt(value, false) as ProbePublicReceipt | undefined;
|
|
363
|
+
export const parseGuidanceProbePublicStatus = (value: unknown): ProbePublicStatus | undefined => publicReceipt(value, true) as ProbePublicStatus | undefined;
|
|
364
|
+
|
|
365
|
+
/** Explicit worker-visible bytes; no host identity, arm label or improver side channel. */
|
|
366
|
+
export function guidanceProbeWorkerFrame(task: string, baselineContext: string, systemPolicy: string, guidance: string): string {
|
|
367
|
+
if ([task, baselineContext, systemPolicy].some(text => typeof text !== "string" || Buffer.byteLength(text) > GUIDANCE_PROBE_LIMITS.snapshotBytes)
|
|
368
|
+
|| typeof guidance !== "string") return invalid();
|
|
369
|
+
return JSON.stringify({ task, baselineContext, systemPolicy, guidance });
|
|
370
|
+
}
|
|
371
|
+
export const guidanceProbeNonGuidanceInputHash = (task: string, baselineContext: string, systemPolicy: string): string => probeHash(JSON.stringify({ task, baselineContext, systemPolicy }));
|
|
372
|
+
|
|
373
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
374
|
+
// T3 (#1226): host-observed receipts, the outcome denominator and comparability. Contract: docs/design/guidance-probes.md "T3 receipts, reconcile and cleanup contract".
|
|
375
|
+
// Everything here is pure: no storage, process or clock. The Store seals and hydrates; these functions only shape, check and classify.
|
|
376
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
/** Retained output is eligible for a prune this long after its receipt seals. A constant, not a setting; nothing deletes automatically. */
|
|
379
|
+
export const PROBE_RETENTION_DAYS = 14;
|
|
380
|
+
export const PROBE_RETENTION_MS = PROBE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
|
|
381
|
+
/**
|
|
382
|
+
* The bounds of one receipt, and the largest valid receipt they allow. `receiptBytes` is DERIVED from them, never chosen: a session that meets every success
|
|
383
|
+
* condition and writes 64 files with the longest allowed names must still seal as a success, so the byte bound can never sit below the largest valid manifest.
|
|
384
|
+
* A name is at most `nameBytes` UTF-8 bytes; in JSON each of those bytes can cost two (a quote or a backslash), plus the surrounding quotes. Control and format
|
|
385
|
+
* characters are refused outright (`probeOutputName`), so no byte costs more than two. `FIXED_RECEIPT_BYTES` covers every other field at its own maximum:
|
|
386
|
+
* three bounded ids and model names, eight digests, the counters, the limits array and the keys (measured at about 3 KB; the test builds the real maximum).
|
|
387
|
+
*/
|
|
388
|
+
const OUTPUT_NAME_BYTES = 256, OUTPUT_ENTRIES = 64;
|
|
389
|
+
const NAME_JSON_BYTES = 2 * OUTPUT_NAME_BYTES + 2;
|
|
390
|
+
const ENTRY_JSON_BYTES = NAME_JSON_BYTES + 160, EXCLUDED_JSON_BYTES = NAME_JSON_BYTES + 64, FIXED_RECEIPT_BYTES = 4096;
|
|
391
|
+
export const PROBE_OUTPUT_LIMITS = Object.freeze({ entries: OUTPUT_ENTRIES, fileBytes: 1024 * 1024, nameBytes: OUTPUT_NAME_BYTES,
|
|
392
|
+
receiptBytes: FIXED_RECEIPT_BYTES + OUTPUT_ENTRIES * (ENTRY_JSON_BYTES + 1) + OUTPUT_ENTRIES * (EXCLUDED_JSON_BYTES + 1) });
|
|
393
|
+
/** The one name check for an output path in a manifest, an exclusion or a retained record: bounded, relative, no control or format characters, no `..`. */
|
|
394
|
+
export const probeOutputName = (value: unknown): value is string => executionText(value, PROBE_OUTPUT_LIMITS.nameBytes) && !/\p{Cf}/u.test(value)
|
|
395
|
+
&& !value.startsWith("/") && !value.split("/").includes("..");
|
|
396
|
+
|
|
397
|
+
export type ProbeReceiptState = "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" | "unknown";
|
|
398
|
+
export type ProbeReceiptLimit = "usage_unknown" | "served_model_unobserved" | "served_model_mismatch" | "teardown_unverified" | "output_truncated" | "storage_over_cap" | "coverage_unverified";
|
|
399
|
+
export type ProbeExcludedReason = "not_regular" | "linked" | "outside_declared_writes" | "over_file_cap" | "over_total_cap" | "changed_while_read" | "over_entry_cap" | "over_depth" | "over_walk_cap" | "invalid_name";
|
|
400
|
+
export interface ProbeOutputEntry { relative: string; sha256: string; bytes: number }
|
|
401
|
+
export interface ProbeOutputExcluded { relative: string; reason: ProbeExcludedReason }
|
|
402
|
+
export interface ProbeOutputManifestV1 { v: 1; entries: readonly ProbeOutputEntry[]; excluded: readonly ProbeOutputExcluded[]; totalBytes: number }
|
|
403
|
+
export interface ProbeReceiptUsage { modelCalls: number; modelUsageKnown: number; toolCalls: number; toolUsageKnown: number; tokensObserved: number | null }
|
|
404
|
+
/** The host's immutable record of one finished session. Every field is host-computed; none is a provider claim. */
|
|
405
|
+
export interface ProbeReceiptV1 {
|
|
406
|
+
v: 1;
|
|
407
|
+
experimentId: string;
|
|
408
|
+
slotId: string;
|
|
409
|
+
generation: number;
|
|
410
|
+
revision: number;
|
|
411
|
+
requestedModel: string;
|
|
412
|
+
servedModel: string | null;
|
|
413
|
+
inputFrameSha256: string | null;
|
|
414
|
+
workerEffectiveInputSha256: string | null;
|
|
415
|
+
nonGuidanceInputSha256: string | null;
|
|
416
|
+
guidanceSha256: string | null;
|
|
417
|
+
/** The host's own fingerprints read at seal time. `null` when the host never observed them (a crash reconcile): never copied from the declaration. */
|
|
418
|
+
runtimeSha256: string | null;
|
|
419
|
+
toolsetSha256: string | null;
|
|
420
|
+
modelConfigSha256: string | null;
|
|
421
|
+
startedAt: number;
|
|
422
|
+
endedAt: number;
|
|
423
|
+
elapsedMs: number;
|
|
424
|
+
state: ProbeReceiptState;
|
|
425
|
+
usage: ProbeReceiptUsage;
|
|
426
|
+
limits: readonly ProbeReceiptLimit[];
|
|
427
|
+
output: ProbeOutputManifestV1;
|
|
428
|
+
/** Seal time plus PROBE_RETENTION_MS. A prune never removes retained output before this instant. */
|
|
429
|
+
expiresAt: number;
|
|
430
|
+
digest: string;
|
|
431
|
+
}
|
|
432
|
+
export type ProbeIncomparableReason = "served_model_mismatch" | "served_model_unobserved" | "input_drift" | "usage_unknown" | "incomplete_coverage"
|
|
433
|
+
| "teardown_unverified" | "authoring_uncontrolled" | "missing_receipt";
|
|
434
|
+
export interface ProbeComparability { comparable: boolean; reasons: readonly ProbeIncomparableReason[] }
|
|
435
|
+
/** Private status: the outcome denominator by receipt state, plus slots that never started. Never part of the public projection (T4 owns that). */
|
|
436
|
+
export interface ProbeOutcomeCounts { succeeded: number; failed: number; cancelled: number; timed_out: number; unavailable: number; unknown: number; planned: number; not_needed: number }
|
|
437
|
+
|
|
438
|
+
const RECEIPT_STATES: readonly ProbeReceiptState[] = ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "unknown"];
|
|
439
|
+
const RECEIPT_LIMITS: readonly ProbeReceiptLimit[] = ["usage_unknown", "served_model_unobserved", "served_model_mismatch", "teardown_unverified", "output_truncated", "storage_over_cap", "coverage_unverified"];
|
|
440
|
+
const EXCLUDED_REASONS: readonly ProbeExcludedReason[] = ["not_regular", "linked", "outside_declared_writes", "over_file_cap", "over_total_cap", "changed_while_read", "over_entry_cap", "over_depth", "over_walk_cap", "invalid_name"];
|
|
441
|
+
|
|
442
|
+
/** Digest over the canonical record without its own digest field. */
|
|
443
|
+
export function probeReceiptDigest(receipt: Omit<ProbeReceiptV1, "digest">): string {
|
|
444
|
+
return probeHash(guidanceProbeCanonical(receipt, PROBE_OUTPUT_LIMITS.receiptBytes));
|
|
445
|
+
}
|
|
446
|
+
const nullableSha = (value: unknown): boolean => value === null || probeSha256(value);
|
|
447
|
+
/** Closed, inert parse. Returns undefined for any shape, bound or digest violation; never repairs. */
|
|
448
|
+
export function parseProbeReceipt(value: unknown): ProbeReceiptV1 | undefined {
|
|
449
|
+
try {
|
|
450
|
+
const f = object(inert(value, PROBE_OUTPUT_LIMITS.receiptBytes), ["v", "experimentId", "slotId", "generation", "revision", "requestedModel", "servedModel", "inputFrameSha256",
|
|
451
|
+
"workerEffectiveInputSha256", "nonGuidanceInputSha256", "guidanceSha256", "runtimeSha256", "toolsetSha256", "modelConfigSha256", "startedAt", "endedAt", "elapsedMs", "state",
|
|
452
|
+
"usage", "limits", "output", "expiresAt", "digest"]);
|
|
453
|
+
required(f.v === 1 && identity(f.experimentId) && identity(f.slotId) && probeInteger(f.generation) && probeInteger(f.revision));
|
|
454
|
+
required(f.requestedModel === GUIDANCE_PROBE_MODEL && (f.servedModel === null || typeof f.servedModel === "string" && Buffer.byteLength(f.servedModel) <= 256));
|
|
455
|
+
required(nullableSha(f.inputFrameSha256) && nullableSha(f.workerEffectiveInputSha256) && nullableSha(f.nonGuidanceInputSha256) && nullableSha(f.guidanceSha256));
|
|
456
|
+
required(nullableSha(f.runtimeSha256) && nullableSha(f.toolsetSha256) && nullableSha(f.modelConfigSha256));
|
|
457
|
+
// elapsed time is wall time between the Store's trusted-clock samples, so it can never exceed the span between them.
|
|
458
|
+
required(probeInteger(f.startedAt) && probeInteger(f.endedAt) && probeInteger(f.elapsedMs) && f.endedAt >= f.startedAt && f.elapsedMs <= f.endedAt - f.startedAt
|
|
459
|
+
&& probeInteger(f.expiresAt) && f.expiresAt === f.endedAt + PROBE_RETENTION_MS);
|
|
460
|
+
required(RECEIPT_STATES.includes(f.state as ProbeReceiptState));
|
|
461
|
+
const usage = object(f.usage, ["modelCalls", "modelUsageKnown", "toolCalls", "toolUsageKnown", "tokensObserved"]);
|
|
462
|
+
required(probeInteger(usage.modelCalls) && probeInteger(usage.modelUsageKnown) && usage.modelUsageKnown <= usage.modelCalls
|
|
463
|
+
&& probeInteger(usage.toolCalls) && probeInteger(usage.toolUsageKnown) && usage.toolUsageKnown <= usage.toolCalls && (usage.tokensObserved === null || probeInteger(usage.tokensObserved)));
|
|
464
|
+
required(Array.isArray(f.limits) && f.limits.length <= RECEIPT_LIMITS.length && new Set(f.limits).size === f.limits.length && f.limits.every(item => RECEIPT_LIMITS.includes(item as ProbeReceiptLimit)));
|
|
465
|
+
const output = object(f.output, ["v", "entries", "excluded", "totalBytes"]);
|
|
466
|
+
required(output.v === 1 && Array.isArray(output.entries) && output.entries.length <= PROBE_OUTPUT_LIMITS.entries && Array.isArray(output.excluded) && output.excluded.length <= PROBE_OUTPUT_LIMITS.entries
|
|
467
|
+
&& probeInteger(output.totalBytes));
|
|
468
|
+
let total = 0; const names = new Set<string>();
|
|
469
|
+
for (const entry of output.entries as unknown[]) {
|
|
470
|
+
const e = object(entry, ["relative", "sha256", "bytes"]);
|
|
471
|
+
required(probeOutputName(e.relative) && probeSha256(e.sha256) && probeInteger(e.bytes) && e.bytes <= PROBE_OUTPUT_LIMITS.fileBytes && !names.has(e.relative));
|
|
472
|
+
names.add(e.relative as string); total += e.bytes as number;
|
|
473
|
+
}
|
|
474
|
+
required(total === output.totalBytes);
|
|
475
|
+
for (const entry of output.excluded as unknown[]) {
|
|
476
|
+
const e = object(entry, ["relative", "reason"]);
|
|
477
|
+
required(probeOutputName(e.relative) && EXCLUDED_REASONS.includes(e.reason as ProbeExcludedReason));
|
|
478
|
+
}
|
|
479
|
+
required(probeSha256(f.digest));
|
|
480
|
+
const { digest, ...rest } = f as unknown as ProbeReceiptV1;
|
|
481
|
+
required(probeReceiptDigest(rest) === digest);
|
|
482
|
+
// A success is never recorded alongside a limit or an exclusion that the contract says forbids it.
|
|
483
|
+
if (f.state === "succeeded") required((f.limits as unknown[]).length === 0 && (output.excluded as unknown[]).length === 0 && f.servedModel === GUIDANCE_PROBE_MODEL);
|
|
484
|
+
return f as unknown as ProbeReceiptV1;
|
|
485
|
+
} catch { return undefined; }
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Pure comparability over an experiment's receipts and the slots that should have produced them (AC4). One reason is enough to make the
|
|
490
|
+
* pair incomparable; reasons are listed, not ranked. Never an upgrade of the older inline expression: every case that expression called
|
|
491
|
+
* incomparable is incomparable here too.
|
|
492
|
+
*/
|
|
493
|
+
export function classifyProbeComparability(input: {
|
|
494
|
+
slots: readonly { slotId: string; role: ProbeSlot["role"]; arm: ProbeSlot["arm"]; reserved: boolean; coverageVerified: boolean; authoring?: "admitted_fixture" | "uncontrolled" }[];
|
|
495
|
+
receipts: readonly ProbeReceiptV1[];
|
|
496
|
+
/** The manifest's runtime fingerprints, which every receipt must match. */
|
|
497
|
+
runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string };
|
|
498
|
+
holds: boolean;
|
|
499
|
+
}): ProbeComparability {
|
|
500
|
+
const reasons = new Set<ProbeIncomparableReason>();
|
|
501
|
+
if (input.holds) reasons.add("usage_unknown");
|
|
502
|
+
const bySlot = new Map(input.receipts.map(item => [item.slotId, item]));
|
|
503
|
+
for (const slot of input.slots) {
|
|
504
|
+
if (!slot.reserved) continue;
|
|
505
|
+
if (slot.authoring === "uncontrolled") reasons.add("authoring_uncontrolled");
|
|
506
|
+
if (!slot.coverageVerified) reasons.add("incomplete_coverage");
|
|
507
|
+
const receipt = bySlot.get(slot.slotId);
|
|
508
|
+
if (!receipt) { reasons.add("missing_receipt"); continue; }
|
|
509
|
+
if (receipt.servedModel === null) reasons.add("served_model_unobserved");
|
|
510
|
+
else if (receipt.servedModel !== receipt.requestedModel) reasons.add("served_model_mismatch");
|
|
511
|
+
// A fingerprint the host never observed is drift it cannot rule out; one that differs from the declaration is drift.
|
|
512
|
+
if (receipt.runtimeSha256 !== input.runtime.runtimeSha256 || receipt.toolsetSha256 !== input.runtime.toolsetSha256 || receipt.modelConfigSha256 !== input.runtime.modelConfigSha256) reasons.add("input_drift");
|
|
513
|
+
if (receipt.limits.includes("usage_unknown") || receipt.usage.tokensObserved === null || receipt.usage.modelUsageKnown !== receipt.usage.modelCalls || receipt.usage.toolUsageKnown !== receipt.usage.toolCalls) reasons.add("usage_unknown");
|
|
514
|
+
if (receipt.limits.includes("teardown_unverified")) reasons.add("teardown_unverified");
|
|
515
|
+
if (receipt.state !== "succeeded") reasons.add("incomplete_coverage");
|
|
516
|
+
}
|
|
517
|
+
// Worker arms differ only in the admitted guidance slot: any other input byte differing is drift.
|
|
518
|
+
const workers = input.receipts.filter(item => input.slots.some(slot => slot.slotId === item.slotId && slot.role === "worker"));
|
|
519
|
+
const baseline = workers[0];
|
|
520
|
+
for (const worker of workers) if (baseline && (worker.nonGuidanceInputSha256 === null || worker.nonGuidanceInputSha256 !== baseline.nonGuidanceInputSha256)) reasons.add("input_drift");
|
|
521
|
+
return { comparable: reasons.size === 0, reasons: [...reasons].sort() };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** The outcome denominator: every reserved slot counts, whatever became of it. Slots never started are reported apart, never as success or failure. */
|
|
525
|
+
export function probeOutcomeCounts(slots: readonly { slotId: string; state: ProbeSessionState }[], receipts: readonly ProbeReceiptV1[]): ProbeOutcomeCounts {
|
|
526
|
+
const counts: ProbeOutcomeCounts = { succeeded: 0, failed: 0, cancelled: 0, timed_out: 0, unavailable: 0, unknown: 0, planned: 0, not_needed: 0 };
|
|
527
|
+
const bySlot = new Map(receipts.map(item => [item.slotId, item]));
|
|
528
|
+
for (const slot of slots) {
|
|
529
|
+
if (slot.state === "planned") { counts.planned++; continue; }
|
|
530
|
+
if (slot.state === "not_needed") { counts.not_needed++; continue; }
|
|
531
|
+
// A reserved slot with no sealed receipt is unknown: the host cannot vouch for it. It is never counted as failed.
|
|
532
|
+
counts[bySlot.get(slot.slotId)?.state ?? "unknown"]++;
|
|
533
|
+
}
|
|
534
|
+
return counts;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** What the host measured about one finished session, before the Store adds the fields only it can know. None of this comes from the provider. */
|
|
538
|
+
export interface ProbeMeasuredSession {
|
|
539
|
+
/** Store-trusted-clock sample taken when this session's launch was exposed, as reported back by the host that took it. Never the experiment's first reservation. */
|
|
540
|
+
startedAt: number;
|
|
541
|
+
servedModel: string | null;
|
|
542
|
+
workerEffectiveInputSha256: string | null;
|
|
543
|
+
nonGuidanceInputSha256: string | null;
|
|
544
|
+
/** True only when the peer, the confinement and every owned child reported known quiescence, and the output was collected after that point. */
|
|
545
|
+
teardownVerified: boolean;
|
|
546
|
+
/** The host's own runtime, toolset and model-config fingerprints at seal time, or null when it could not read them. Never the declaration's. */
|
|
547
|
+
runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string } | null;
|
|
548
|
+
cancelled: boolean;
|
|
549
|
+
timedOut: boolean;
|
|
550
|
+
/** The session could not start or reach the model for a host-known reason (for example confinement unavailable). */
|
|
551
|
+
unavailable: boolean;
|
|
552
|
+
/** Limits the host observed itself, such as `output_truncated`. The Store adds the ones it can derive. */
|
|
553
|
+
limits: readonly ProbeReceiptLimit[];
|
|
554
|
+
/** Bytes the session actually left in scratch, measured, not the declared reservation. */
|
|
555
|
+
scratchBytes: number;
|
|
556
|
+
output: ProbeOutputManifestV1;
|
|
557
|
+
/** The host-created retention directory for `output`, if any. Stored beside the receipt, never inside it. */
|
|
558
|
+
retained?: ProbeRetainedRecord;
|
|
559
|
+
}
|
|
560
|
+
/** Stored rows hold a canonical receipt, which is bounded well below this; the SQL length check guards against a hostile row. */
|
|
561
|
+
export const PROBE_RECEIPT_ROW_BYTES = PROBE_OUTPUT_LIMITS.receiptBytes;
|
|
562
|
+
/**
|
|
563
|
+
* The runtime half of the 1 GiB cap: output past the slot's declared bound is not retained, hashed or counted as the session's output. Entries are
|
|
564
|
+
* kept in order until the bound would be crossed; the rest are recorded as excluded, so the receipt can never claim more than was declared.
|
|
565
|
+
*/
|
|
566
|
+
export function capOutput(output: ProbeOutputManifestV1, maximum: number): ProbeOutputManifestV1 {
|
|
567
|
+
const entries: ProbeOutputEntry[] = [], excluded: ProbeOutputExcluded[] = [...output.excluded];
|
|
568
|
+
let total = 0;
|
|
569
|
+
for (const entry of output.entries) {
|
|
570
|
+
if (entries.length >= PROBE_OUTPUT_LIMITS.entries || total + entry.bytes > maximum) { excluded.push({ relative: entry.relative, reason: entries.length >= PROBE_OUTPUT_LIMITS.entries ? "over_entry_cap" : "over_total_cap" }); continue; }
|
|
571
|
+
entries.push(entry); total += entry.bytes;
|
|
572
|
+
}
|
|
573
|
+
return { v: 1, entries, excluded: excluded.slice(0, PROBE_OUTPUT_LIMITS.entries), totalBytes: total };
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* A retained output directory the host created, with the identity it recorded at creation. Kept beside the receipt in its own column and out of the
|
|
578
|
+
* digested receipt body: a receipt never carries a physical path. Prune acts on nothing that is not recorded here and still matches by identity.
|
|
579
|
+
*/
|
|
580
|
+
/**
|
|
581
|
+
* A host-created retention directory and the identity of each file in it. Inode numbers are recycled (Linux reuses one straight after an unlink), so a file's
|
|
582
|
+
* identity is its device, inode AND change time in nanoseconds: a replacement created later always has a later `ctimeNs`, even when it reuses the inode.
|
|
583
|
+
* ponytail: ctime granularity is the filesystem's (a few milliseconds on Linux), so a replacement created in the very same tick as the original with a recycled
|
|
584
|
+
* inode would match; retention-to-prune is days, so the window is the retention call itself. A per-file content hash re-check at prune is the upgrade path.
|
|
585
|
+
* ponytail: a directory has no stable change time (it moves with every entry), so its identity is device and inode only. Deleting a replaced empty directory
|
|
586
|
+
* under the host's own random-named retention root is the ceiling; a stable directory identity (a host-written marker file) is the upgrade path.
|
|
587
|
+
*/
|
|
588
|
+
export interface ProbeRetainedRecord { directory: string; dev: number; ino: number; files: readonly { relative: string; dev: number; ino: number; bytes: number; ctimeNs: string }[] }
|
|
589
|
+
/** The filesystem half of prune, injected so the Store (src/hub) never imports src/local. Both calls are identity-checked by their implementation. */
|
|
590
|
+
export interface ProbeRetentionFs {
|
|
591
|
+
preview(retained: ProbeRetainedRecord): { remove: { relative: string; bytes: number }[]; keep: { relative: string; reason: string }[] };
|
|
592
|
+
remove(retained: ProbeRetainedRecord): { removed: string[]; kept: { relative: string; reason: string }[] };
|
|
593
|
+
}
|
|
594
|
+
export function parseProbeRetained(value: unknown): ProbeRetainedRecord | undefined {
|
|
595
|
+
try {
|
|
596
|
+
const f = object(inert(value, PROBE_OUTPUT_LIMITS.receiptBytes), ["directory", "dev", "ino", "files"]);
|
|
597
|
+
required(typeof f.directory === "string" && f.directory.startsWith("/") && Buffer.byteLength(f.directory) <= 1024 && !/[\u0000-\u001f]/.test(f.directory));
|
|
598
|
+
required(probeInteger(f.dev) && probeInteger(f.ino) && Array.isArray(f.files) && f.files.length <= PROBE_OUTPUT_LIMITS.entries);
|
|
599
|
+
const seen = new Set<string>();
|
|
600
|
+
for (const item of f.files as unknown[]) {
|
|
601
|
+
const e = object(item, ["relative", "dev", "ino", "bytes", "ctimeNs"]);
|
|
602
|
+
required(probeOutputName(e.relative) && probeInteger(e.dev) && probeInteger(e.ino) && probeInteger(e.bytes) && e.bytes <= PROBE_OUTPUT_LIMITS.fileBytes && !seen.has(e.relative)
|
|
603
|
+
&& typeof e.ctimeNs === "string" && /^[0-9]{1,24}$/.test(e.ctimeNs));
|
|
604
|
+
seen.add(e.relative as string);
|
|
605
|
+
}
|
|
606
|
+
return f as unknown as ProbeRetainedRecord;
|
|
607
|
+
} catch { return undefined; }
|
|
608
|
+
}
|
|
609
|
+
export type ProbePruneKeepReason = "experiment_active" | "experiment_held" | "not_expired" | "already_pruned" | "no_retained_output" | "directory_replaced_or_missing" | "identity_changed" | "not_empty";
|
|
610
|
+
export interface ProbePrunePlan {
|
|
611
|
+
/** SHA-256 over the canonical plan: a prune takes this and refuses if the owned set changed since the person saw it. */
|
|
612
|
+
digest: string;
|
|
613
|
+
retainedBytes: number;
|
|
614
|
+
slots: readonly { slotId: string; expiresAt: number; remove: readonly { relative: string; bytes: number }[]; keep: readonly { relative: string; reason: ProbePruneKeepReason }[] }[];
|
|
615
|
+
}
|
|
616
|
+
export interface ProbePruneResult { pruned: readonly string[]; kept: readonly { slotId: string; relative: string; reason: ProbePruneKeepReason }[]; planDigest: string }
|
|
617
|
+
|
|
618
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
619
|
+
// T4 (#1226): the producer receipt reader and export. Contract: docs/design/guidance-probes.md "T4 producer status and receipt export".
|
|
620
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
621
|
+
|
|
622
|
+
/** Where a slot's retained output stands. It never names a path: a physical location is private to the host. */
|
|
623
|
+
export type ProbeRetentionState = "none" | "retained" | "pruned";
|
|
624
|
+
export interface ProbeExportSlot {
|
|
625
|
+
slotId: string; stage: ProbeStage; role: ProbeSlot["role"]; arm: ProbeSlot["arm"];
|
|
626
|
+
/** The session's own state, so a slot that never started (`planned`, `not_needed`) is visible beside the ones that did. */
|
|
627
|
+
state: ProbeSessionState;
|
|
628
|
+
/** The verbatim sealed receipt, digest-checked on every read. `null` when the slot has none, or when a name in it did not pass the privacy screen. */
|
|
629
|
+
receipt: ProbeReceiptV1 | null;
|
|
630
|
+
/** The receipt's own digest, kept when the receipt is withheld so the consumer can still cite it. `null` only when the slot has no receipt. */
|
|
631
|
+
receiptDigest: string | null;
|
|
632
|
+
withheld: boolean;
|
|
633
|
+
retention: ProbeRetentionState;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* What a producer or a receipt consumer reads about one experiment. Everything in it is host-observed or host-computed from sealed receipts; a fixture
|
|
637
|
+
* run is `evidence: "fixture"`, and nothing here claims a live trial, sampling control, provider behaviour or model quality. Unknown stays unknown: a
|
|
638
|
+
* usage gap is `usage_unknown`, an unobserved served model is `served_model_unobserved`, and a slot with no receipt is `unknown` in the denominator.
|
|
639
|
+
*/
|
|
640
|
+
export interface ProbeReceiptExport {
|
|
641
|
+
v: 1;
|
|
642
|
+
status: ProbePublicStatus;
|
|
643
|
+
/** The stricter of the older public expression and the sealed-receipt verdict, as in `show`. */
|
|
644
|
+
comparable: boolean;
|
|
645
|
+
/** Why the sealed receipts alone are not comparable. Empty when they are. */
|
|
646
|
+
reasons: readonly ProbeIncomparableReason[];
|
|
647
|
+
/** The full outcome denominator: every reserved slot counts, failed, cancelled, timed out and unavailable included. */
|
|
648
|
+
counts: ProbeOutcomeCounts;
|
|
649
|
+
slots: readonly ProbeExportSlot[];
|
|
650
|
+
}
|
|
651
|
+
/** The largest valid export: every slot with the largest valid receipt, plus the status and the counters. Derived, never chosen. */
|
|
652
|
+
export const PROBE_EXPORT_BYTES = GUIDANCE_PROBE_LIMITS.slots * (PROBE_OUTPUT_LIMITS.receiptBytes + 1024) + 4096;
|
|
653
|
+
const STAGES: readonly ProbeStage[] = ["baseline", "proposal1", "candidate1", "proposal2", "candidate2", "compose", "successor", "select", "reflect"];
|
|
654
|
+
const SLOT_ROLES: readonly ProbeSlot["role"][] = ["worker", "proposal", "compose", "select", "reflect"];
|
|
655
|
+
const SLOT_ARMS: readonly ProbeSlot["arm"][] = ["baseline", "candidate1", "candidate2", "successor", "none"];
|
|
656
|
+
const SESSION_STATES: readonly ProbeSessionState[] = ["planned", "reserved", "running", "failed_known", "closed_fixture", "not_needed", "unknown_held"];
|
|
657
|
+
const INCOMPARABLE_REASONS: readonly ProbeIncomparableReason[] = ["served_model_mismatch", "served_model_unobserved", "input_drift", "usage_unknown", "incomplete_coverage",
|
|
658
|
+
"teardown_unverified", "authoring_uncontrolled", "missing_receipt"];
|
|
659
|
+
const COUNT_KEYS: readonly (keyof ProbeOutcomeCounts)[] = ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "unknown", "planned", "not_needed"];
|
|
660
|
+
/** Closed, inert, bounded parse of a receipt export. Every embedded receipt is re-verified by `parseProbeReceipt`, so a tampered receipt never parses. */
|
|
661
|
+
export function parseGuidanceProbeReceiptExport(value: unknown): ProbeReceiptExport | undefined {
|
|
662
|
+
try {
|
|
663
|
+
const f = object(inert(value, PROBE_EXPORT_BYTES), ["v", "status", "comparable", "reasons", "counts", "slots"]);
|
|
664
|
+
required(f.v === 1);
|
|
665
|
+
const status = parseGuidanceProbePublicStatus(f.status); required(status);
|
|
666
|
+
required(typeof f.comparable === "boolean" && Array.isArray(f.reasons) && f.reasons.length <= INCOMPARABLE_REASONS.length && new Set(f.reasons).size === f.reasons.length
|
|
667
|
+
&& f.reasons.every(item => INCOMPARABLE_REASONS.includes(item as ProbeIncomparableReason)));
|
|
668
|
+
// The flag can only be stricter than the sealed verdict: a comparable export never lists a reason, and never outranks the public status.
|
|
669
|
+
required(!(f.comparable && ((f.reasons as unknown[]).length > 0 || !status!.comparable)));
|
|
670
|
+
const counts = object(f.counts, COUNT_KEYS);
|
|
671
|
+
required(COUNT_KEYS.every(key => probeInteger(counts[key])));
|
|
672
|
+
const slots = f.slots; required(Array.isArray(slots) && slots.length <= GUIDANCE_PROBE_LIMITS.slots);
|
|
673
|
+
const seen = new Set<string>(); let withReceipt = 0;
|
|
674
|
+
for (const item of slots as unknown[]) {
|
|
675
|
+
const s = object(item, ["slotId", "stage", "role", "arm", "state", "receipt", "receiptDigest", "withheld", "retention"]);
|
|
676
|
+
required(identity(s.slotId) && !seen.has(s.slotId as string) && STAGES.includes(s.stage as ProbeStage) && SLOT_ROLES.includes(s.role as ProbeSlot["role"])
|
|
677
|
+
&& SLOT_ARMS.includes(s.arm as ProbeSlot["arm"]) && SESSION_STATES.includes(s.state as ProbeSessionState) && typeof s.withheld === "boolean"
|
|
678
|
+
&& ["none", "retained", "pruned"].includes(s.retention as string));
|
|
679
|
+
seen.add(s.slotId as string);
|
|
680
|
+
if (s.receipt === null) {
|
|
681
|
+
// A withheld receipt still names its digest; a slot with no receipt has neither, and is never marked withheld.
|
|
682
|
+
required(s.withheld ? probeSha256(s.receiptDigest) : s.receiptDigest === null);
|
|
683
|
+
} else {
|
|
684
|
+
const receipt = parseProbeReceipt(s.receipt); required(receipt && !s.withheld && receipt.slotId === s.slotId && s.receiptDigest === receipt.digest);
|
|
685
|
+
withReceipt++;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const total = COUNT_KEYS.reduce((sum, key) => sum + (counts[key] as number), 0);
|
|
689
|
+
required(total === (slots as unknown[]).length && withReceipt <= total);
|
|
690
|
+
return f as unknown as ProbeReceiptExport;
|
|
691
|
+
} catch { return undefined; }
|
|
692
|
+
}
|