@riddledc/riddle-proof 0.5.38 → 0.5.40

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.
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/checkpoint.ts
31
+ var checkpoint_exports = {};
32
+ __export(checkpoint_exports, {
33
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: () => RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
34
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
35
+ authorPacketPayloadFromCheckpointResponse: () => authorPacketPayloadFromCheckpointResponse,
36
+ buildAuthorCheckpointPacket: () => buildAuthorCheckpointPacket,
37
+ checkpointSummaryFromState: () => checkpointSummaryFromState,
38
+ isDuplicateCheckpointResponse: () => isDuplicateCheckpointResponse,
39
+ normalizeCheckpointResponse: () => normalizeCheckpointResponse,
40
+ proofContractFromAuthorCheckpointResponse: () => proofContractFromAuthorCheckpointResponse,
41
+ statePathsForRunState: () => statePathsForRunState
42
+ });
43
+ module.exports = __toCommonJS(checkpoint_exports);
44
+ var import_node_crypto = __toESM(require("crypto"), 1);
45
+
46
+ // src/result.ts
47
+ function compactRecord(input) {
48
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0 && value !== null && value !== ""));
49
+ }
50
+ function nonEmptyString(value) {
51
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
52
+ }
53
+ function recordValue(value) {
54
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
55
+ }
56
+
57
+ // src/checkpoint.ts
58
+ var RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION = "riddle-proof.checkpoint.v1";
59
+ var RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION = "riddle-proof.checkpoint_response.v1";
60
+ function timestamp() {
61
+ return (/* @__PURE__ */ new Date()).toISOString();
62
+ }
63
+ function jsonCloneRecord(value) {
64
+ const record = recordValue(value);
65
+ if (!record) return void 0;
66
+ try {
67
+ return JSON.parse(JSON.stringify(record));
68
+ } catch {
69
+ return { ...record };
70
+ }
71
+ }
72
+ function jsonCloneValue(value) {
73
+ if (value === void 0 || value === null) return void 0;
74
+ try {
75
+ return JSON.parse(JSON.stringify(value));
76
+ } catch {
77
+ return value;
78
+ }
79
+ }
80
+ function compactText(value, limit = 1600) {
81
+ const text = nonEmptyString(value);
82
+ if (!text) return void 0;
83
+ return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
84
+ }
85
+ function statePathsForRunState(state, engineStatePath) {
86
+ return compactRecord({
87
+ wrapper_state_path: state.state_path || state.request.harness_state_path || null,
88
+ engine_state_path: engineStatePath || state.request.engine_state_path || null,
89
+ resume_state_path: engineStatePath || state.request.engine_state_path || null
90
+ });
91
+ }
92
+ function responseSchemaForAuthorPacket() {
93
+ return {
94
+ type: "object",
95
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "payload", "created_at"],
96
+ additionalProperties: false,
97
+ properties: {
98
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
99
+ run_id: { type: "string" },
100
+ checkpoint: { type: "string" },
101
+ resume_token: { type: "string" },
102
+ decision: {
103
+ type: "string",
104
+ enum: ["author_packet", "needs_recon", "blocked", "human_review"]
105
+ },
106
+ summary: { type: "string" },
107
+ payload: {
108
+ type: "object",
109
+ description: "For decision=author_packet, provide the proof packet itself or {author_packet:{...}} with proof_plan and capture_script."
110
+ },
111
+ reasons: { type: "array", items: { type: "string" } },
112
+ continue_with_stage: { type: "string", enum: ["author", "recon"] },
113
+ source: {
114
+ type: "object",
115
+ properties: {
116
+ kind: { type: "string" },
117
+ session_id: { type: "string" },
118
+ user_id: { type: "string" }
119
+ }
120
+ },
121
+ created_at: { type: "string" }
122
+ }
123
+ };
124
+ }
125
+ function resumeTokenFor(input) {
126
+ const hash = import_node_crypto.default.createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 24);
127
+ return `rpchk_${hash}`;
128
+ }
129
+ function artifactsFromState(state) {
130
+ const artifacts = [];
131
+ for (const role of ["before", "prod", "after"]) {
132
+ const url = nonEmptyString(state?.[`${role}_cdn`]);
133
+ if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
134
+ }
135
+ const authorRequest = recordValue(state?.author_request);
136
+ const latestAttempt = recordValue(authorRequest?.latest_attempt);
137
+ const observations = recordValue(latestAttempt?.observations);
138
+ for (const [label, observation] of Object.entries(observations || {})) {
139
+ const record = recordValue(observation);
140
+ const url = nonEmptyString(record?.url);
141
+ if (url && !artifacts.some((artifact) => artifact.url === url)) {
142
+ artifacts.push({
143
+ role: label === "before" || label === "prod" ? label : "json",
144
+ url,
145
+ name: `${label}-observation`,
146
+ summary: compactText(record?.reason, 240)
147
+ });
148
+ }
149
+ }
150
+ return artifacts.slice(0, 16);
151
+ }
152
+ function buildAuthorCheckpointPacket(input) {
153
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "author_supervisor_judgment";
154
+ const stage = "author";
155
+ const runId = input.runState.run_id || "unknown";
156
+ const fullState = input.fullRiddleState || {};
157
+ const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
158
+ const authorRequest = recordValue(fullState.author_request) || recordValue(fullState.proof_plan_request) || recordValue(decisionDetails?.authorRequest) || {};
159
+ const fallbackDefaults = recordValue(authorRequest.fallback_defaults) || {};
160
+ const reconResults = recordValue(fullState.recon_results);
161
+ const checkpointContract = recordValue(input.engineResult.checkpointContract);
162
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.author_summary) || "Author checkpoint needs a supervising proof packet.";
163
+ return {
164
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
165
+ run_id: runId,
166
+ state_path: input.runState.state_path,
167
+ stage,
168
+ checkpoint,
169
+ kind: "author_proof",
170
+ summary,
171
+ question: "Author the proof packet for this Riddle Proof run. Return a CheckpointResponse with decision=author_packet and payload containing proof_plan and capture_script.",
172
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
173
+ context: input.request.context,
174
+ artifacts: artifactsFromState(fullState),
175
+ state_excerpt: compactRecord({
176
+ repo: input.request.repo || fullState.repo,
177
+ branch: input.request.branch || fullState.branch,
178
+ verification_mode: input.request.verification_mode || fullState.verification_mode,
179
+ reference: input.request.reference || fullState.reference,
180
+ server_path: fullState.server_path,
181
+ wait_for_selector: fullState.wait_for_selector,
182
+ author_summary: fullState.author_summary,
183
+ author_request: jsonCloneRecord(authorRequest),
184
+ recon_baseline_understanding: jsonCloneRecord(fullState.recon_baseline_understanding),
185
+ fallback_defaults: jsonCloneRecord(fallbackDefaults)
186
+ }),
187
+ evidence_excerpt: compactRecord({
188
+ recon_results: jsonCloneRecord(reconResults),
189
+ checkpoint_contract: jsonCloneRecord(checkpointContract)
190
+ }),
191
+ allowed_decisions: ["author_packet", "needs_recon", "blocked", "human_review"],
192
+ response_schema: responseSchemaForAuthorPacket(),
193
+ routing_hint: {
194
+ suggested_role: "proof_author",
195
+ visibility: input.visibility || "quiet",
196
+ urgency: "normal",
197
+ can_auto_answer: input.visibility !== "manual"
198
+ },
199
+ resume_token: resumeTokenFor({
200
+ runId,
201
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
202
+ checkpoint,
203
+ stage
204
+ }),
205
+ created_at: input.created_at || timestamp()
206
+ };
207
+ }
208
+ function normalizeCheckpointResponse(value) {
209
+ const record = recordValue(value);
210
+ if (!record) return null;
211
+ const version = nonEmptyString(record.version);
212
+ const runId = nonEmptyString(record.run_id);
213
+ const checkpoint = nonEmptyString(record.checkpoint);
214
+ const decision = nonEmptyString(record.decision);
215
+ const summary = nonEmptyString(record.summary);
216
+ if (version !== RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION || !runId || !checkpoint || !decision || !summary) {
217
+ return null;
218
+ }
219
+ return compactRecord({
220
+ version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
221
+ run_id: runId,
222
+ checkpoint,
223
+ resume_token: nonEmptyString(record.resume_token),
224
+ decision,
225
+ summary,
226
+ payload: jsonCloneRecord(record.payload),
227
+ reasons: Array.isArray(record.reasons) ? record.reasons.filter((item) => typeof item === "string") : void 0,
228
+ continue_with_stage: nonEmptyString(record.continue_with_stage),
229
+ source: jsonCloneRecord(record.source),
230
+ created_at: nonEmptyString(record.created_at) || timestamp()
231
+ });
232
+ }
233
+ function checkpointSummaryFromState(state, engineStatePath) {
234
+ const history = state.checkpoint_history || [];
235
+ const packets = history.filter((entry) => entry.packet);
236
+ const responses = history.filter((entry) => entry.response);
237
+ const latestPacketEntry = [...history].reverse().find((entry) => entry.packet);
238
+ const latestResponseEntry = [...history].reverse().find((entry) => entry.response);
239
+ const latestPacket = state.checkpoint_packet || latestPacketEntry?.packet;
240
+ const latestResponse = latestResponseEntry?.response;
241
+ const latestResumeToken = latestPacket?.resume_token || null;
242
+ const latestResponseToken = latestResponse?.resume_token || null;
243
+ const tokenMatches = latestResumeToken && latestResponseToken ? latestResumeToken === latestResponseToken : latestResumeToken || latestResponseToken ? false : null;
244
+ return compactRecord({
245
+ pending: Boolean(state.checkpoint_packet),
246
+ packet_count: packets.length,
247
+ response_count: responses.length,
248
+ latest_checkpoint: state.checkpoint_packet?.checkpoint || latestResponse?.checkpoint || state.last_checkpoint || null,
249
+ latest_stage: state.checkpoint_packet?.stage || latestResponse?.continue_with_stage || state.current_stage || null,
250
+ latest_kind: state.checkpoint_packet?.kind || latestPacket?.kind || null,
251
+ latest_decision: latestResponse?.decision || null,
252
+ latest_packet_summary: latestPacket?.summary || null,
253
+ latest_response_summary: latestResponse?.summary || null,
254
+ latest_resume_token: latestResumeToken,
255
+ latest_response_token: latestResponseToken,
256
+ token_matches: tokenMatches,
257
+ last_packet_at: latestPacketEntry?.ts || null,
258
+ last_response_at: latestResponseEntry?.ts || null,
259
+ state_paths: statePathsForRunState(state, engineStatePath)
260
+ });
261
+ }
262
+ function isDuplicateCheckpointResponse(state, response) {
263
+ const latestResponse = [...state.checkpoint_history || []].reverse().find((entry) => entry.response)?.response;
264
+ if (!latestResponse) return false;
265
+ return latestResponse.run_id === response.run_id && latestResponse.checkpoint === response.checkpoint && latestResponse.resume_token === response.resume_token && latestResponse.decision === response.decision;
266
+ }
267
+ function authorPacketPayloadFromCheckpointResponse(response) {
268
+ if (response.decision !== "author_packet") return null;
269
+ const payload = recordValue(response.payload);
270
+ if (!payload) return null;
271
+ const nested = recordValue(payload.author_packet);
272
+ const candidate = nested || payload;
273
+ if (!nonEmptyString(candidate.proof_plan) || !nonEmptyString(candidate.capture_script)) return null;
274
+ return candidate;
275
+ }
276
+ function proofContractFromAuthorCheckpointResponse(response, packet, payload) {
277
+ const refinedInputs = recordValue(payload.refined_inputs) || {};
278
+ return compactRecord({
279
+ version: "riddle-proof.proof-contract.v1",
280
+ checkpoint: packet.checkpoint,
281
+ source_response: compactRecord({
282
+ run_id: response.run_id,
283
+ checkpoint: response.checkpoint,
284
+ resume_token: response.resume_token,
285
+ decision: response.decision,
286
+ summary: response.summary,
287
+ created_at: response.created_at
288
+ }),
289
+ proof_plan: nonEmptyString(payload.proof_plan),
290
+ capture_script: nonEmptyString(payload.capture_script),
291
+ artifact_contract: jsonCloneRecord(payload.artifact_contract),
292
+ assertions: jsonCloneValue(payload.assertions),
293
+ baseline_understanding: jsonCloneRecord(payload.baseline_understanding) || jsonCloneRecord(payload.recon_baseline_understanding) || jsonCloneRecord(packet.state_excerpt?.recon_baseline_understanding),
294
+ route_assumptions: compactRecord({
295
+ server_path: nonEmptyString(refinedInputs.server_path) || nonEmptyString(payload.server_path) || nonEmptyString(packet.state_excerpt?.server_path),
296
+ wait_for_selector: nonEmptyString(refinedInputs.wait_for_selector) || nonEmptyString(payload.wait_for_selector) || nonEmptyString(packet.state_excerpt?.wait_for_selector),
297
+ reference: nonEmptyString(refinedInputs.reference) || nonEmptyString(payload.reference),
298
+ expected_path: nonEmptyString(payload.expected_path) || nonEmptyString(refinedInputs.expected_path)
299
+ }),
300
+ stop_condition: nonEmptyString(payload.stop_condition),
301
+ rationale: jsonCloneValue(payload.rationale),
302
+ verdict_dimensions: jsonCloneRecord(payload.verdict_dimensions),
303
+ payload: jsonCloneRecord(payload),
304
+ created_at: timestamp()
305
+ });
306
+ }
307
+ // Annotate the CommonJS export names for ESM import in node:
308
+ 0 && (module.exports = {
309
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
310
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
311
+ authorPacketPayloadFromCheckpointResponse,
312
+ buildAuthorCheckpointPacket,
313
+ checkpointSummaryFromState,
314
+ isDuplicateCheckpointResponse,
315
+ normalizeCheckpointResponse,
316
+ proofContractFromAuthorCheckpointResponse,
317
+ statePathsForRunState
318
+ });
@@ -0,0 +1,26 @@
1
+ import { RiddleProofCheckpointResponse, RiddleProofRunParams, RiddleProofRunState, RiddleProofCheckpointPacket, RiddleProofCheckpointSummary, RiddleProofProofContract, RiddleProofStatePaths } from './types.cjs';
2
+
3
+ declare const RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: "riddle-proof.checkpoint.v1";
4
+ declare const RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: "riddle-proof.checkpoint_response.v1";
5
+ declare function statePathsForRunState(state: RiddleProofRunState, engineStatePath?: string | null): RiddleProofStatePaths;
6
+ declare function buildAuthorCheckpointPacket(input: {
7
+ request: RiddleProofRunParams;
8
+ runState: RiddleProofRunState;
9
+ engineResult: {
10
+ state_path?: string | null;
11
+ checkpoint?: string | null;
12
+ checkpointContract?: Record<string, unknown> | null;
13
+ decisionRequest?: Record<string, unknown> | null;
14
+ summary?: string;
15
+ };
16
+ fullRiddleState?: Record<string, unknown> | null;
17
+ visibility?: "liveblog" | "quiet" | "terminal_only" | "manual" | string;
18
+ created_at?: string;
19
+ }): RiddleProofCheckpointPacket;
20
+ declare function normalizeCheckpointResponse(value: unknown): RiddleProofCheckpointResponse | null;
21
+ declare function checkpointSummaryFromState(state: RiddleProofRunState, engineStatePath?: string | null): RiddleProofCheckpointSummary;
22
+ declare function isDuplicateCheckpointResponse(state: RiddleProofRunState, response: RiddleProofCheckpointResponse): boolean;
23
+ declare function authorPacketPayloadFromCheckpointResponse(response: RiddleProofCheckpointResponse): Record<string, unknown> | null;
24
+ declare function proofContractFromAuthorCheckpointResponse(response: RiddleProofCheckpointResponse, packet: RiddleProofCheckpointPacket, payload: Record<string, unknown>): RiddleProofProofContract;
25
+
26
+ export { RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION, RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION, authorPacketPayloadFromCheckpointResponse, buildAuthorCheckpointPacket, checkpointSummaryFromState, isDuplicateCheckpointResponse, normalizeCheckpointResponse, proofContractFromAuthorCheckpointResponse, statePathsForRunState };
@@ -0,0 +1,26 @@
1
+ import { RiddleProofCheckpointResponse, RiddleProofRunParams, RiddleProofRunState, RiddleProofCheckpointPacket, RiddleProofCheckpointSummary, RiddleProofProofContract, RiddleProofStatePaths } from './types.js';
2
+
3
+ declare const RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: "riddle-proof.checkpoint.v1";
4
+ declare const RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: "riddle-proof.checkpoint_response.v1";
5
+ declare function statePathsForRunState(state: RiddleProofRunState, engineStatePath?: string | null): RiddleProofStatePaths;
6
+ declare function buildAuthorCheckpointPacket(input: {
7
+ request: RiddleProofRunParams;
8
+ runState: RiddleProofRunState;
9
+ engineResult: {
10
+ state_path?: string | null;
11
+ checkpoint?: string | null;
12
+ checkpointContract?: Record<string, unknown> | null;
13
+ decisionRequest?: Record<string, unknown> | null;
14
+ summary?: string;
15
+ };
16
+ fullRiddleState?: Record<string, unknown> | null;
17
+ visibility?: "liveblog" | "quiet" | "terminal_only" | "manual" | string;
18
+ created_at?: string;
19
+ }): RiddleProofCheckpointPacket;
20
+ declare function normalizeCheckpointResponse(value: unknown): RiddleProofCheckpointResponse | null;
21
+ declare function checkpointSummaryFromState(state: RiddleProofRunState, engineStatePath?: string | null): RiddleProofCheckpointSummary;
22
+ declare function isDuplicateCheckpointResponse(state: RiddleProofRunState, response: RiddleProofCheckpointResponse): boolean;
23
+ declare function authorPacketPayloadFromCheckpointResponse(response: RiddleProofCheckpointResponse): Record<string, unknown> | null;
24
+ declare function proofContractFromAuthorCheckpointResponse(response: RiddleProofCheckpointResponse, packet: RiddleProofCheckpointPacket, payload: Record<string, unknown>): RiddleProofProofContract;
25
+
26
+ export { RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION, RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION, authorPacketPayloadFromCheckpointResponse, buildAuthorCheckpointPacket, checkpointSummaryFromState, isDuplicateCheckpointResponse, normalizeCheckpointResponse, proofContractFromAuthorCheckpointResponse, statePathsForRunState };
@@ -0,0 +1,23 @@
1
+ import {
2
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
3
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
4
+ authorPacketPayloadFromCheckpointResponse,
5
+ buildAuthorCheckpointPacket,
6
+ checkpointSummaryFromState,
7
+ isDuplicateCheckpointResponse,
8
+ normalizeCheckpointResponse,
9
+ proofContractFromAuthorCheckpointResponse,
10
+ statePathsForRunState
11
+ } from "./chunk-5LVCGDSD.js";
12
+ import "./chunk-W7VTDN4T.js";
13
+ export {
14
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
15
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
16
+ authorPacketPayloadFromCheckpointResponse,
17
+ buildAuthorCheckpointPacket,
18
+ checkpointSummaryFromState,
19
+ isDuplicateCheckpointResponse,
20
+ normalizeCheckpointResponse,
21
+ proofContractFromAuthorCheckpointResponse,
22
+ statePathsForRunState
23
+ };
@@ -0,0 +1,269 @@
1
+ import {
2
+ compactRecord,
3
+ nonEmptyString,
4
+ recordValue
5
+ } from "./chunk-W7VTDN4T.js";
6
+
7
+ // src/checkpoint.ts
8
+ import crypto from "crypto";
9
+ var RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION = "riddle-proof.checkpoint.v1";
10
+ var RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION = "riddle-proof.checkpoint_response.v1";
11
+ function timestamp() {
12
+ return (/* @__PURE__ */ new Date()).toISOString();
13
+ }
14
+ function jsonCloneRecord(value) {
15
+ const record = recordValue(value);
16
+ if (!record) return void 0;
17
+ try {
18
+ return JSON.parse(JSON.stringify(record));
19
+ } catch {
20
+ return { ...record };
21
+ }
22
+ }
23
+ function jsonCloneValue(value) {
24
+ if (value === void 0 || value === null) return void 0;
25
+ try {
26
+ return JSON.parse(JSON.stringify(value));
27
+ } catch {
28
+ return value;
29
+ }
30
+ }
31
+ function compactText(value, limit = 1600) {
32
+ const text = nonEmptyString(value);
33
+ if (!text) return void 0;
34
+ return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
35
+ }
36
+ function statePathsForRunState(state, engineStatePath) {
37
+ return compactRecord({
38
+ wrapper_state_path: state.state_path || state.request.harness_state_path || null,
39
+ engine_state_path: engineStatePath || state.request.engine_state_path || null,
40
+ resume_state_path: engineStatePath || state.request.engine_state_path || null
41
+ });
42
+ }
43
+ function responseSchemaForAuthorPacket() {
44
+ return {
45
+ type: "object",
46
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "payload", "created_at"],
47
+ additionalProperties: false,
48
+ properties: {
49
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
50
+ run_id: { type: "string" },
51
+ checkpoint: { type: "string" },
52
+ resume_token: { type: "string" },
53
+ decision: {
54
+ type: "string",
55
+ enum: ["author_packet", "needs_recon", "blocked", "human_review"]
56
+ },
57
+ summary: { type: "string" },
58
+ payload: {
59
+ type: "object",
60
+ description: "For decision=author_packet, provide the proof packet itself or {author_packet:{...}} with proof_plan and capture_script."
61
+ },
62
+ reasons: { type: "array", items: { type: "string" } },
63
+ continue_with_stage: { type: "string", enum: ["author", "recon"] },
64
+ source: {
65
+ type: "object",
66
+ properties: {
67
+ kind: { type: "string" },
68
+ session_id: { type: "string" },
69
+ user_id: { type: "string" }
70
+ }
71
+ },
72
+ created_at: { type: "string" }
73
+ }
74
+ };
75
+ }
76
+ function resumeTokenFor(input) {
77
+ const hash = crypto.createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 24);
78
+ return `rpchk_${hash}`;
79
+ }
80
+ function artifactsFromState(state) {
81
+ const artifacts = [];
82
+ for (const role of ["before", "prod", "after"]) {
83
+ const url = nonEmptyString(state?.[`${role}_cdn`]);
84
+ if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
85
+ }
86
+ const authorRequest = recordValue(state?.author_request);
87
+ const latestAttempt = recordValue(authorRequest?.latest_attempt);
88
+ const observations = recordValue(latestAttempt?.observations);
89
+ for (const [label, observation] of Object.entries(observations || {})) {
90
+ const record = recordValue(observation);
91
+ const url = nonEmptyString(record?.url);
92
+ if (url && !artifacts.some((artifact) => artifact.url === url)) {
93
+ artifacts.push({
94
+ role: label === "before" || label === "prod" ? label : "json",
95
+ url,
96
+ name: `${label}-observation`,
97
+ summary: compactText(record?.reason, 240)
98
+ });
99
+ }
100
+ }
101
+ return artifacts.slice(0, 16);
102
+ }
103
+ function buildAuthorCheckpointPacket(input) {
104
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "author_supervisor_judgment";
105
+ const stage = "author";
106
+ const runId = input.runState.run_id || "unknown";
107
+ const fullState = input.fullRiddleState || {};
108
+ const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
109
+ const authorRequest = recordValue(fullState.author_request) || recordValue(fullState.proof_plan_request) || recordValue(decisionDetails?.authorRequest) || {};
110
+ const fallbackDefaults = recordValue(authorRequest.fallback_defaults) || {};
111
+ const reconResults = recordValue(fullState.recon_results);
112
+ const checkpointContract = recordValue(input.engineResult.checkpointContract);
113
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.author_summary) || "Author checkpoint needs a supervising proof packet.";
114
+ return {
115
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
116
+ run_id: runId,
117
+ state_path: input.runState.state_path,
118
+ stage,
119
+ checkpoint,
120
+ kind: "author_proof",
121
+ summary,
122
+ question: "Author the proof packet for this Riddle Proof run. Return a CheckpointResponse with decision=author_packet and payload containing proof_plan and capture_script.",
123
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
124
+ context: input.request.context,
125
+ artifacts: artifactsFromState(fullState),
126
+ state_excerpt: compactRecord({
127
+ repo: input.request.repo || fullState.repo,
128
+ branch: input.request.branch || fullState.branch,
129
+ verification_mode: input.request.verification_mode || fullState.verification_mode,
130
+ reference: input.request.reference || fullState.reference,
131
+ server_path: fullState.server_path,
132
+ wait_for_selector: fullState.wait_for_selector,
133
+ author_summary: fullState.author_summary,
134
+ author_request: jsonCloneRecord(authorRequest),
135
+ recon_baseline_understanding: jsonCloneRecord(fullState.recon_baseline_understanding),
136
+ fallback_defaults: jsonCloneRecord(fallbackDefaults)
137
+ }),
138
+ evidence_excerpt: compactRecord({
139
+ recon_results: jsonCloneRecord(reconResults),
140
+ checkpoint_contract: jsonCloneRecord(checkpointContract)
141
+ }),
142
+ allowed_decisions: ["author_packet", "needs_recon", "blocked", "human_review"],
143
+ response_schema: responseSchemaForAuthorPacket(),
144
+ routing_hint: {
145
+ suggested_role: "proof_author",
146
+ visibility: input.visibility || "quiet",
147
+ urgency: "normal",
148
+ can_auto_answer: input.visibility !== "manual"
149
+ },
150
+ resume_token: resumeTokenFor({
151
+ runId,
152
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
153
+ checkpoint,
154
+ stage
155
+ }),
156
+ created_at: input.created_at || timestamp()
157
+ };
158
+ }
159
+ function normalizeCheckpointResponse(value) {
160
+ const record = recordValue(value);
161
+ if (!record) return null;
162
+ const version = nonEmptyString(record.version);
163
+ const runId = nonEmptyString(record.run_id);
164
+ const checkpoint = nonEmptyString(record.checkpoint);
165
+ const decision = nonEmptyString(record.decision);
166
+ const summary = nonEmptyString(record.summary);
167
+ if (version !== RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION || !runId || !checkpoint || !decision || !summary) {
168
+ return null;
169
+ }
170
+ return compactRecord({
171
+ version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
172
+ run_id: runId,
173
+ checkpoint,
174
+ resume_token: nonEmptyString(record.resume_token),
175
+ decision,
176
+ summary,
177
+ payload: jsonCloneRecord(record.payload),
178
+ reasons: Array.isArray(record.reasons) ? record.reasons.filter((item) => typeof item === "string") : void 0,
179
+ continue_with_stage: nonEmptyString(record.continue_with_stage),
180
+ source: jsonCloneRecord(record.source),
181
+ created_at: nonEmptyString(record.created_at) || timestamp()
182
+ });
183
+ }
184
+ function checkpointSummaryFromState(state, engineStatePath) {
185
+ const history = state.checkpoint_history || [];
186
+ const packets = history.filter((entry) => entry.packet);
187
+ const responses = history.filter((entry) => entry.response);
188
+ const latestPacketEntry = [...history].reverse().find((entry) => entry.packet);
189
+ const latestResponseEntry = [...history].reverse().find((entry) => entry.response);
190
+ const latestPacket = state.checkpoint_packet || latestPacketEntry?.packet;
191
+ const latestResponse = latestResponseEntry?.response;
192
+ const latestResumeToken = latestPacket?.resume_token || null;
193
+ const latestResponseToken = latestResponse?.resume_token || null;
194
+ const tokenMatches = latestResumeToken && latestResponseToken ? latestResumeToken === latestResponseToken : latestResumeToken || latestResponseToken ? false : null;
195
+ return compactRecord({
196
+ pending: Boolean(state.checkpoint_packet),
197
+ packet_count: packets.length,
198
+ response_count: responses.length,
199
+ latest_checkpoint: state.checkpoint_packet?.checkpoint || latestResponse?.checkpoint || state.last_checkpoint || null,
200
+ latest_stage: state.checkpoint_packet?.stage || latestResponse?.continue_with_stage || state.current_stage || null,
201
+ latest_kind: state.checkpoint_packet?.kind || latestPacket?.kind || null,
202
+ latest_decision: latestResponse?.decision || null,
203
+ latest_packet_summary: latestPacket?.summary || null,
204
+ latest_response_summary: latestResponse?.summary || null,
205
+ latest_resume_token: latestResumeToken,
206
+ latest_response_token: latestResponseToken,
207
+ token_matches: tokenMatches,
208
+ last_packet_at: latestPacketEntry?.ts || null,
209
+ last_response_at: latestResponseEntry?.ts || null,
210
+ state_paths: statePathsForRunState(state, engineStatePath)
211
+ });
212
+ }
213
+ function isDuplicateCheckpointResponse(state, response) {
214
+ const latestResponse = [...state.checkpoint_history || []].reverse().find((entry) => entry.response)?.response;
215
+ if (!latestResponse) return false;
216
+ return latestResponse.run_id === response.run_id && latestResponse.checkpoint === response.checkpoint && latestResponse.resume_token === response.resume_token && latestResponse.decision === response.decision;
217
+ }
218
+ function authorPacketPayloadFromCheckpointResponse(response) {
219
+ if (response.decision !== "author_packet") return null;
220
+ const payload = recordValue(response.payload);
221
+ if (!payload) return null;
222
+ const nested = recordValue(payload.author_packet);
223
+ const candidate = nested || payload;
224
+ if (!nonEmptyString(candidate.proof_plan) || !nonEmptyString(candidate.capture_script)) return null;
225
+ return candidate;
226
+ }
227
+ function proofContractFromAuthorCheckpointResponse(response, packet, payload) {
228
+ const refinedInputs = recordValue(payload.refined_inputs) || {};
229
+ return compactRecord({
230
+ version: "riddle-proof.proof-contract.v1",
231
+ checkpoint: packet.checkpoint,
232
+ source_response: compactRecord({
233
+ run_id: response.run_id,
234
+ checkpoint: response.checkpoint,
235
+ resume_token: response.resume_token,
236
+ decision: response.decision,
237
+ summary: response.summary,
238
+ created_at: response.created_at
239
+ }),
240
+ proof_plan: nonEmptyString(payload.proof_plan),
241
+ capture_script: nonEmptyString(payload.capture_script),
242
+ artifact_contract: jsonCloneRecord(payload.artifact_contract),
243
+ assertions: jsonCloneValue(payload.assertions),
244
+ baseline_understanding: jsonCloneRecord(payload.baseline_understanding) || jsonCloneRecord(payload.recon_baseline_understanding) || jsonCloneRecord(packet.state_excerpt?.recon_baseline_understanding),
245
+ route_assumptions: compactRecord({
246
+ server_path: nonEmptyString(refinedInputs.server_path) || nonEmptyString(payload.server_path) || nonEmptyString(packet.state_excerpt?.server_path),
247
+ wait_for_selector: nonEmptyString(refinedInputs.wait_for_selector) || nonEmptyString(payload.wait_for_selector) || nonEmptyString(packet.state_excerpt?.wait_for_selector),
248
+ reference: nonEmptyString(refinedInputs.reference) || nonEmptyString(payload.reference),
249
+ expected_path: nonEmptyString(payload.expected_path) || nonEmptyString(refinedInputs.expected_path)
250
+ }),
251
+ stop_condition: nonEmptyString(payload.stop_condition),
252
+ rationale: jsonCloneValue(payload.rationale),
253
+ verdict_dimensions: jsonCloneRecord(payload.verdict_dimensions),
254
+ payload: jsonCloneRecord(payload),
255
+ created_at: timestamp()
256
+ });
257
+ }
258
+
259
+ export {
260
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
261
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
262
+ statePathsForRunState,
263
+ buildAuthorCheckpointPacket,
264
+ normalizeCheckpointResponse,
265
+ checkpointSummaryFromState,
266
+ isDuplicateCheckpointResponse,
267
+ authorPacketPayloadFromCheckpointResponse,
268
+ proofContractFromAuthorCheckpointResponse
269
+ };