@riddledc/riddle-proof 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +6 -6
  2. package/dist/chunk-3MHFLQKG.js +853 -0
  3. package/dist/{chunk-LVP22WE4.js → chunk-5GZZZ6JA.js} +5 -1
  4. package/dist/engine-harness.cjs +2505 -22
  5. package/dist/engine-harness.js +1 -1
  6. package/dist/index.cjs +2512 -29
  7. package/dist/index.js +2 -2
  8. package/dist/openclaw.cjs +1 -1
  9. package/dist/openclaw.js +1 -1
  10. package/dist/proof-run-core.cjs +909 -0
  11. package/dist/proof-run-core.d.cts +280 -0
  12. package/dist/proof-run-core.d.ts +280 -0
  13. package/dist/proof-run-core.js +48 -0
  14. package/dist/proof-run-engine.cjs +2499 -0
  15. package/dist/proof-run-engine.d.cts +677 -0
  16. package/dist/proof-run-engine.d.ts +677 -0
  17. package/dist/proof-run-engine.js +1649 -0
  18. package/lib/workspace-core.mjs +391 -0
  19. package/package.json +15 -3
  20. package/runtime/lib/author.py +343 -0
  21. package/runtime/lib/implement.py +63 -0
  22. package/runtime/lib/preflight.py +246 -0
  23. package/runtime/lib/recon.py +1048 -0
  24. package/runtime/lib/riddle_core_call.mjs +151 -0
  25. package/runtime/lib/setup.py +387 -0
  26. package/runtime/lib/ship.py +834 -0
  27. package/runtime/lib/util.py +673 -0
  28. package/runtime/lib/verify.py +1223 -0
  29. package/runtime/pipelines/riddle-proof-author.lobster +28 -0
  30. package/runtime/pipelines/riddle-proof-implement.lobster +26 -0
  31. package/runtime/pipelines/riddle-proof-recon.lobster +79 -0
  32. package/runtime/pipelines/riddle-proof-setup.lobster +141 -0
  33. package/runtime/pipelines/riddle-proof-ship.lobster +36 -0
  34. package/runtime/pipelines/riddle-proof-verify.lobster +74 -0
  35. package/runtime/tests/recon_verify_smoke.py +1198 -0
@@ -0,0 +1,2499 @@
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/proof-run-engine.ts
31
+ var proof_run_engine_exports = {};
32
+ __export(proof_run_engine_exports, {
33
+ createRiddleProofEngine: () => createRiddleProofEngine,
34
+ executeWorkflow: () => executeWorkflow
35
+ });
36
+ module.exports = __toCommonJS(proof_run_engine_exports);
37
+ var import_node_child_process = require("child_process");
38
+ var import_node_fs2 = require("fs");
39
+ var import_node_path2 = __toESM(require("path"), 1);
40
+
41
+ // src/proof-run-core.ts
42
+ var import_node_fs = require("fs");
43
+ var import_node_crypto = require("crypto");
44
+ var import_node_path = __toESM(require("path"), 1);
45
+ var import_node_url = require("url");
46
+ var import_meta = {};
47
+ var WORKFLOW_STAGE_ORDER = ["setup", "recon", "author", "implement", "verify", "ship"];
48
+ var CHECKPOINT_CONTRACT_VERSION = "riddle-proof-run.checkpoint.v1";
49
+ function currentDistDir() {
50
+ const meta = typeof import_meta === "object" ? import_meta : {};
51
+ if (typeof meta.url === "string" && meta.url) {
52
+ return import_node_path.default.dirname((0, import_node_url.fileURLToPath)(meta.url));
53
+ }
54
+ if (typeof __dirname === "string") return __dirname;
55
+ return process.cwd();
56
+ }
57
+ var BUNDLED_RIDDLE_PROOF_DIR = import_node_path.default.resolve(
58
+ currentDistDir(),
59
+ "..",
60
+ "runtime"
61
+ );
62
+ var RIDDLE_PROOF_DIR_CANDIDATES = [
63
+ BUNDLED_RIDDLE_PROOF_DIR
64
+ ];
65
+ function createWorkflowStatePath() {
66
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
67
+ return `/tmp/riddle-proof-state-${stamp}-${(0, import_node_crypto.randomUUID)().slice(0, 8)}.json`;
68
+ }
69
+ function argsPathForStatePath(statePath) {
70
+ const base = import_node_path.default.basename(statePath);
71
+ if (base.startsWith("riddle-proof-state")) {
72
+ return import_node_path.default.join(import_node_path.default.dirname(statePath), base.replace("riddle-proof-state", "riddle-proof-args"));
73
+ }
74
+ return import_node_path.default.join(import_node_path.default.dirname(statePath), `${base}.args.json`);
75
+ }
76
+ function isRiddleProofSkillDir(candidate) {
77
+ return (0, import_node_fs.existsSync)(workflowFile(candidate, "setup"));
78
+ }
79
+ function resolveRiddleProofDir(config = {}) {
80
+ if (config.riddleProofDir) return config.riddleProofDir;
81
+ const candidates = [
82
+ process.env.RIDDLE_PROOF_DIR,
83
+ ...RIDDLE_PROOF_DIR_CANDIDATES
84
+ ].filter((candidate) => Boolean(candidate));
85
+ return candidates.find(isRiddleProofSkillDir) || candidates.find((candidate) => (0, import_node_fs.existsSync)(candidate)) || RIDDLE_PROOF_DIR_CANDIDATES[0];
86
+ }
87
+ function resolveConfig(config = {}, params = {}) {
88
+ const configuredStatePath = config.statePath || "";
89
+ const shouldIsolateWorkflow = !params.state_path && !configuredStatePath && (params.action === "setup" || params.action === "run");
90
+ const statePath = params.state_path || (shouldIsolateWorkflow ? createWorkflowStatePath() : configuredStatePath || "/tmp/riddle-proof-state.json");
91
+ return {
92
+ riddleProofDir: resolveRiddleProofDir(config),
93
+ statePath,
94
+ argsPath: argsPathForStatePath(statePath),
95
+ defaultReviewer: config.defaultReviewer || "davisdiehl"
96
+ };
97
+ }
98
+ function ensureAction(action) {
99
+ if (["setup", "recon", "author", "implement", "verify", "ship", "status", "sync", "run"].includes(action)) {
100
+ return action;
101
+ }
102
+ throw new Error(`Unsupported action: ${action}`);
103
+ }
104
+ function workflowFile(riddleProofDir, action) {
105
+ return import_node_path.default.join(riddleProofDir, "pipelines", `riddle-proof-${action}.lobster`);
106
+ }
107
+ function buildSetupArgs(params, config) {
108
+ if (!params.repo) throw new Error("repo is required for setup/run");
109
+ if (!params.change_request) throw new Error("change_request is required for setup/run");
110
+ const commitMessage = (params.commit_message || params.change_request || "").trim();
111
+ const captureScript = (params.capture_script || "").trim();
112
+ const requestedReference = params.reference || (params.prod_url ? "both" : "before");
113
+ const reference = !params.prod_url && requestedReference !== "before" ? "before" : requestedReference;
114
+ if (!commitMessage) throw new Error("commit_message is required for setup/run");
115
+ return {
116
+ repo: params.repo,
117
+ branch: params.branch || "",
118
+ change_request: params.change_request,
119
+ commit_message: commitMessage,
120
+ prod_url: params.prod_url || "",
121
+ capture_script: captureScript,
122
+ success_criteria: params.success_criteria || "",
123
+ assertions_json: params.assertions_json || "",
124
+ verification_mode: params.verification_mode || "proof",
125
+ reference,
126
+ base_branch: params.base_branch || "main",
127
+ before_ref: params.before_ref || "",
128
+ allow_static_preview_fallback: params.allow_static_preview_fallback ? "true" : "",
129
+ context: params.context || "",
130
+ reviewer: params.reviewer || config.defaultReviewer,
131
+ mode: params.mode || "",
132
+ build_command: params.build_command || "npm run build",
133
+ build_output: params.build_output || "build",
134
+ server_image: params.server_image || "node:20-slim",
135
+ server_command: params.server_command || "npm start",
136
+ server_port: String(params.server_port || 3e3),
137
+ server_path: params.server_path || "",
138
+ server_path_source: params.server_path ? "user" : "",
139
+ use_auth: params.use_auth ? "true" : "",
140
+ auth_localStorage_json: params.auth_localStorage_json || "",
141
+ auth_cookies_json: params.auth_cookies_json || "",
142
+ auth_headers_json: params.auth_headers_json || "",
143
+ color_scheme: params.color_scheme || "",
144
+ wait_for_selector: params.wait_for_selector || "",
145
+ discord_channel: params.discord_channel || "",
146
+ discord_thread_id: params.discord_thread_id || "",
147
+ discord_message_id: params.discord_message_id || "",
148
+ discord_source_url: params.discord_source_url || "",
149
+ leave_draft: params.leave_draft ? "true" : ""
150
+ };
151
+ }
152
+ function readState(statePath) {
153
+ if (!(0, import_node_fs.existsSync)(statePath)) {
154
+ return null;
155
+ }
156
+ return JSON.parse((0, import_node_fs.readFileSync)(statePath, "utf-8"));
157
+ }
158
+ function writeState(statePath, state) {
159
+ (0, import_node_fs.writeFileSync)(statePath, JSON.stringify(state, null, 2));
160
+ }
161
+ function normalizeOptionalString(value) {
162
+ return typeof value === "string" ? value.trim() : void 0;
163
+ }
164
+ function knownEnvironmentIssuesFromNotes(notes) {
165
+ const text = notes.toLowerCase();
166
+ const issues = [];
167
+ if ((text.includes("erofs") || text.includes("read-only file system")) && text.includes("node_modules") && (text.includes(".vite-temp") || text.includes("vite.config"))) {
168
+ issues.push({
169
+ code: "vite_temp_config_erofs",
170
+ source: "implementation_notes",
171
+ severity: "environment",
172
+ summary: "Focused build verification hit the known Vite temp-config EROFS issue in shared node_modules."
173
+ });
174
+ }
175
+ return issues;
176
+ }
177
+ function guardProofEvidenceGlobalAssignments(script) {
178
+ return script.replace(
179
+ /^(\s*)(globalThis|window|self)\.__riddleProofEvidence\s*=\s*([^;\n]+);\s*$/gm,
180
+ (_match, indent, root, expression) => `${indent}try { if (typeof ${root} !== "undefined" && ${root}) ${root}.__riddleProofEvidence = ${expression.trim()}; } catch {}`
181
+ );
182
+ }
183
+ function normalizeCaptureScript(value) {
184
+ const script = normalizeOptionalString(value) || "";
185
+ return script ? guardProofEvidenceGlobalAssignments(script) : "";
186
+ }
187
+ function appendProofSummaryLine(state, line) {
188
+ const text = String(line || "").trim();
189
+ if (!text) return;
190
+ const existing = typeof state.proof_summary === "string" ? state.proof_summary.trim() : "";
191
+ if (existing.includes(text)) return;
192
+ state.proof_summary = existing ? `${existing}
193
+ ${text}` : text;
194
+ }
195
+ function hasAuthoredProofPlan(state = {}) {
196
+ return Boolean((state?.proof_plan || "").trim()) && Boolean((state?.capture_script || "").trim());
197
+ }
198
+ function syncAuthoringState(state = {}) {
199
+ const reconReady = ["ready_for_proof_plan", "completed"].includes(state?.recon_status || "");
200
+ const reconBlocked = ["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "");
201
+ const reconExhausted = state?.recon_status === "exhausted";
202
+ if (reconBlocked) {
203
+ state.author_status = "needs_recon_judgment";
204
+ } else if (reconExhausted) {
205
+ state.author_status = "recon_exhausted";
206
+ } else if (!reconReady) {
207
+ state.author_status = state.author_status || "pending_recon";
208
+ } else if (state.author_status === "ready" || state.proof_plan_status === "ready") {
209
+ state.author_status = "ready";
210
+ } else {
211
+ state.author_status = "needs_authoring";
212
+ }
213
+ if (reconBlocked) {
214
+ state.proof_plan_status = "needs_recon_judgment";
215
+ } else if (reconExhausted) {
216
+ state.proof_plan_status = "recon_exhausted";
217
+ } else if (state.author_status === "ready" || state.proof_plan_status === "ready") {
218
+ state.proof_plan_status = "ready";
219
+ } else if (reconReady) {
220
+ state.proof_plan_status = "needs_authoring";
221
+ } else {
222
+ state.proof_plan_status = state.proof_plan_status || "pending_recon";
223
+ }
224
+ state.author_request = state.author_request || {};
225
+ state.author_summary = state.author_summary || "";
226
+ return state;
227
+ }
228
+ function ensureStageLoopState(state = {}) {
229
+ if (!state || typeof state !== "object") return state;
230
+ syncAuthoringState(state);
231
+ state.explicit_stage_gate = true;
232
+ state.stage_attempts = state.stage_attempts || {};
233
+ for (const stage of WORKFLOW_STAGE_ORDER) {
234
+ const current = state.stage_attempts[stage] || {};
235
+ state.stage_attempts[stage] = {
236
+ count: Number(current.count || 0),
237
+ last_status: current.last_status || null,
238
+ last_checkpoint: current.last_checkpoint || null,
239
+ last_summary: current.last_summary || null,
240
+ last_attempted_at: current.last_attempted_at || null,
241
+ history: Array.isArray(current.history) ? current.history : []
242
+ };
243
+ }
244
+ state.stage_decision_request = state.stage_decision_request || {};
245
+ state.active_checkpoint = state.active_checkpoint || null;
246
+ state.active_checkpoint_stage = state.active_checkpoint_stage || null;
247
+ state.last_requested_advance_stage = state.last_requested_advance_stage || null;
248
+ return state;
249
+ }
250
+ function clearStageDecisionRequest(state = {}) {
251
+ ensureStageLoopState(state);
252
+ state.stage_decision_request = {};
253
+ state.active_checkpoint = null;
254
+ state.active_checkpoint_stage = null;
255
+ return state;
256
+ }
257
+ function recordStageAttempt(state, stage, entry = {}) {
258
+ ensureStageLoopState(state);
259
+ const bucket = state.stage_attempts[stage];
260
+ const attemptNumber = Number(bucket.count || 0) + 1;
261
+ const item = {
262
+ attempt: attemptNumber,
263
+ stage,
264
+ status: entry.status || "completed",
265
+ checkpoint: entry.checkpoint || null,
266
+ summary: entry.summary || null,
267
+ requested_advance_stage: entry.requestedAdvanceStage || null,
268
+ halted_for_approval: Boolean(entry.haltedForApproval),
269
+ auto_approved: Boolean(entry.autoApproved),
270
+ error: entry.error || null,
271
+ details: entry.details || {},
272
+ attempted_at: (/* @__PURE__ */ new Date()).toISOString()
273
+ };
274
+ bucket.count = attemptNumber;
275
+ bucket.last_status = item.status;
276
+ bucket.last_checkpoint = item.checkpoint;
277
+ bucket.last_summary = item.summary;
278
+ bucket.last_attempted_at = item.attempted_at;
279
+ bucket.history = [...bucket.history, item].slice(-25);
280
+ state.stage_attempts[stage] = bucket;
281
+ state.last_requested_advance_stage = entry.requestedAdvanceStage || state.last_requested_advance_stage || null;
282
+ return item;
283
+ }
284
+ function setStageDecisionRequest(state, request) {
285
+ ensureStageLoopState(state);
286
+ const continueWithStage = request.continueWithStage || request.recommendedAdvanceStage || null;
287
+ state.active_checkpoint = request.checkpoint;
288
+ state.active_checkpoint_stage = request.stage;
289
+ state.stage_decision_request = {
290
+ stage: request.stage,
291
+ checkpoint: request.checkpoint,
292
+ summary: request.summary,
293
+ next_actions: request.nextActions || [],
294
+ advance_options: request.advanceOptions || [],
295
+ recommended_advance_stage: request.recommendedAdvanceStage || null,
296
+ continue_from_checkpoint: Boolean(continueWithStage),
297
+ continue_with_stage: continueWithStage,
298
+ blocking: Boolean(request.blocking),
299
+ details: request.details || {},
300
+ checkpoint_contract: request.checkpointContract || null,
301
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
302
+ };
303
+ return state.stage_decision_request;
304
+ }
305
+ function checkpointContinueStage(state) {
306
+ ensureStageLoopState(state);
307
+ const stage = state?.stage_decision_request?.continue_with_stage || state?.stage_decision_request?.recommended_advance_stage || null;
308
+ return WORKFLOW_STAGE_ORDER.includes(stage) ? stage : null;
309
+ }
310
+ function invalidateVerifyEvidence(state = {}) {
311
+ if (!state || typeof state !== "object") {
312
+ return { invalidated: false };
313
+ }
314
+ const hadAfterCdn = typeof state.after_cdn === "string" && state.after_cdn.trim().length > 0;
315
+ const hadVerifyResults = Boolean(state.verify_results && Object.keys(state.verify_results).length > 0);
316
+ const hadMergeRecommendation = typeof state.merge_recommendation === "string" && state.merge_recommendation.trim().length > 0;
317
+ const hadProofSummary = typeof state.proof_summary === "string" && state.proof_summary.trim().length > 0;
318
+ const hadVerifyStatus = typeof state.verify_status === "string" && state.verify_status.trim().length > 0;
319
+ const hadVerifySummary = typeof state.verify_summary === "string" && state.verify_summary.trim().length > 0;
320
+ const hadVerifyDecisionRequest = Boolean(state.verify_decision_request && Object.keys(state.verify_decision_request).length > 0);
321
+ const hadEvidenceNotes = Array.isArray(state.evidence_notes) && state.evidence_notes.length > 0;
322
+ const hadProofAssessment = Boolean(state.proof_assessment && Object.keys(state.proof_assessment).length > 0);
323
+ const hadProofAssessmentRequest = Boolean(state.proof_assessment_request && Object.keys(state.proof_assessment_request).length > 0);
324
+ const invalidated = hadAfterCdn || hadVerifyResults || hadMergeRecommendation || hadProofSummary || hadVerifyStatus || hadVerifySummary || hadVerifyDecisionRequest || hadEvidenceNotes || hadProofAssessment || hadProofAssessmentRequest;
325
+ if (invalidated) {
326
+ state.after_cdn = "";
327
+ state.verify_results = {};
328
+ state.verify_status = "";
329
+ state.verify_summary = "";
330
+ state.verify_decision_request = {};
331
+ state.merge_recommendation = null;
332
+ state.proof_summary = "";
333
+ state.evidence_notes = [];
334
+ state.proof_assessment = {};
335
+ state.proof_assessment_source = null;
336
+ state.proof_assessment_request = {};
337
+ }
338
+ return {
339
+ invalidated,
340
+ hadAfterCdn,
341
+ hadVerifyResults,
342
+ hadMergeRecommendation,
343
+ hadProofSummary,
344
+ hadVerifyStatus,
345
+ hadVerifySummary,
346
+ hadVerifyDecisionRequest,
347
+ hadEvidenceNotes,
348
+ hadProofAssessment,
349
+ hadProofAssessmentRequest
350
+ };
351
+ }
352
+ function normalizedReference(state = {}) {
353
+ const reference = String(state?.requested_reference || state?.reference || "before").trim();
354
+ return reference || "before";
355
+ }
356
+ function normalizedProofAssessment(state = {}) {
357
+ const proofAssessment = state?.proof_assessment || {};
358
+ const source = String(proofAssessment?.source || state?.proof_assessment_source || "").trim().toLowerCase();
359
+ const decision = String(proofAssessment?.decision || "").trim();
360
+ return {
361
+ decision: decision || null,
362
+ source: source || null
363
+ };
364
+ }
365
+ function requiredBaselineLabelsForState(state = {}) {
366
+ const reference = normalizedReference(state);
367
+ const labels = [];
368
+ if (reference === "before" || reference === "both") labels.push("before");
369
+ if (reference === "prod" || reference === "both") labels.push("prod");
370
+ return labels;
371
+ }
372
+ function validateShipGate(state = {}) {
373
+ const reference = normalizedReference(state);
374
+ const prodUrl = String(state?.prod_url || "").trim();
375
+ const beforeCdn = String(state?.before_cdn || "").trim();
376
+ const prodCdn = String(state?.prod_cdn || "").trim();
377
+ const afterCdn = String(state?.after_cdn || "").trim();
378
+ const verifyStatus = String(state?.verify_status || "").trim();
379
+ const proofAssessment = normalizedProofAssessment(state);
380
+ const reasons = [];
381
+ if (!["before", "prod", "both"].includes(reference)) {
382
+ reasons.push(`reference must be before, prod, or both; got ${reference}`);
383
+ }
384
+ const requiredBaselines = requiredBaselineLabelsForState(state);
385
+ if (requiredBaselines.includes("before") && !beforeCdn) {
386
+ reasons.push("before_cdn is required before ship");
387
+ }
388
+ if (requiredBaselines.includes("prod")) {
389
+ if (!prodUrl) {
390
+ reasons.push(`prod_url is required when reference=${reference}`);
391
+ }
392
+ if (!prodCdn) {
393
+ reasons.push("prod_cdn is required before ship");
394
+ }
395
+ }
396
+ if (!afterCdn) {
397
+ reasons.push("after_cdn is required before ship");
398
+ }
399
+ if (verifyStatus !== "evidence_captured") {
400
+ reasons.push("verify_status must be evidence_captured before ship");
401
+ }
402
+ if (!["supervising_agent", "supervisor"].includes(proofAssessment.source || "")) {
403
+ reasons.push("proof_assessment.source must be supervising_agent before ship");
404
+ }
405
+ if (proofAssessment.decision !== "ready_to_ship") {
406
+ reasons.push("proof_assessment.decision must be ready_to_ship before ship");
407
+ }
408
+ return {
409
+ ok: reasons.length === 0,
410
+ reasons,
411
+ required_baselines: requiredBaselines,
412
+ evidence: {
413
+ reference,
414
+ prod_url: prodUrl || null,
415
+ before_cdn: beforeCdn || null,
416
+ prod_cdn: prodCdn || null,
417
+ after_cdn: afterCdn || null,
418
+ verify_status: verifyStatus || null,
419
+ proof_assessment_decision: proofAssessment.decision,
420
+ proof_assessment_source: proofAssessment.source
421
+ }
422
+ };
423
+ }
424
+ var CHECKPOINT_CONTRACT_SPECS = {
425
+ setup_review: {
426
+ purpose: "Inspect prepared workspace state before moving into recon."
427
+ },
428
+ recon_supervisor_judgment: {
429
+ purpose: "Supervising agent judges the latest recon attempt and either retries recon, promotes baselines for authoring, or escalates.",
430
+ accepted_inputs: [{
431
+ name: "recon_assessment_json",
432
+ type: "json",
433
+ required: true,
434
+ description: "JSON assessment with decision, summary, baseline_understanding, continue_with_stage, escalation_target, refined_inputs, and reasons."
435
+ }],
436
+ response_schema: {
437
+ decision: ["retry_recon", "ready_for_author", "recon_stuck"],
438
+ summary: "string",
439
+ baseline_understanding: {
440
+ reference: ["before", "prod", "both", "unknown"],
441
+ target_route: "string",
442
+ before_evidence_url: "string",
443
+ visible_before_state: "string",
444
+ relevant_elements: ["string"],
445
+ requested_change: "string",
446
+ proof_focus: "string",
447
+ stop_condition: "string",
448
+ quality_risks: ["string"]
449
+ },
450
+ continue_with_stage: ["recon", "author"],
451
+ escalation_target: ["agent", "human"],
452
+ refined_inputs: {
453
+ server_path: "string",
454
+ wait_for_selector: "string",
455
+ reference: ["before", "prod", "both"]
456
+ },
457
+ reasons: ["string"],
458
+ source: "supervising_agent"
459
+ },
460
+ required_state: ["recon_assessment_request", "recon_results.attempt_history"]
461
+ },
462
+ recon_review: {
463
+ purpose: "Recon baselines were promoted and the workflow is ready for proof authoring."
464
+ },
465
+ recon_human_escalation: {
466
+ purpose: "Recon is explicitly blocked for human direction after supervising-agent escalation."
467
+ },
468
+ author_supervisor_judgment: {
469
+ purpose: "Supervising agent authors the proof packet from recon observations.",
470
+ accepted_inputs: [{
471
+ name: "author_packet_json",
472
+ type: "json",
473
+ required: true,
474
+ description: "JSON proof packet with proof_plan, capture_script, optional refined_inputs, rationale, confidence, and summary."
475
+ }],
476
+ response_schema: {
477
+ proof_plan: "string",
478
+ capture_script: "string",
479
+ baseline_understanding_used: {
480
+ reference: ["before", "prod", "both", "unknown"],
481
+ target_route: "string",
482
+ before_evidence_url: "string",
483
+ visible_before_state: "string",
484
+ relevant_elements: ["string"],
485
+ requested_change: "string",
486
+ proof_focus: "string",
487
+ stop_condition: "string",
488
+ quality_risks: ["string"]
489
+ },
490
+ refined_inputs: {
491
+ server_path: "string",
492
+ wait_for_selector: "string",
493
+ reference: ["before", "prod", "both"]
494
+ },
495
+ rationale: ["string"],
496
+ confidence: "low | medium | high",
497
+ summary: "string"
498
+ },
499
+ required_state: ["author_request", "recon_results.baselines"]
500
+ },
501
+ author_review: {
502
+ purpose: "Proof packet is ready; choose whether to inspect, re-author, implement, or verify."
503
+ },
504
+ implement_changes_missing: {
505
+ purpose: "Implementation stage did not detect material code changes.",
506
+ accepted_inputs: [{
507
+ name: "make_code_changes",
508
+ type: "external_action",
509
+ required: true,
510
+ description: "Make the actual code changes in the after worktree, then resume the implement stage."
511
+ }]
512
+ },
513
+ implement_review: {
514
+ purpose: "Implementation changes were detected and stale verify evidence, if any, was invalidated."
515
+ },
516
+ implement_required: {
517
+ purpose: "Verify cannot run until implementation changes are recorded.",
518
+ accepted_inputs: [{
519
+ name: "make_code_changes",
520
+ type: "external_action",
521
+ required: true,
522
+ description: "Make the requested code change, then advance the run to implement."
523
+ }]
524
+ },
525
+ verify_capture_retry: {
526
+ purpose: "Verify capture was incomplete; the agent loop should revise capture authoring before shipping.",
527
+ accepted_inputs: [{
528
+ name: "author_packet_json",
529
+ type: "json",
530
+ description: "Optional revised proof packet if returning to author."
531
+ }],
532
+ required_state: ["verify_decision_request"]
533
+ },
534
+ verify_supervisor_judgment: {
535
+ purpose: "Supervising agent judges whether captured evidence proves the change is ready to ship.",
536
+ accepted_inputs: [{
537
+ name: "proof_assessment_json",
538
+ type: "json",
539
+ required: true,
540
+ description: "JSON assessment with decision, summary, recommended_stage, continue_with_stage, escalation_target, and reasons."
541
+ }],
542
+ response_schema: {
543
+ decision: ["ready_to_ship", "needs_richer_proof"],
544
+ summary: "string",
545
+ recommended_stage: ["ship", "author", "implement", "recon", "verify"],
546
+ continue_with_stage: ["ship", "author", "implement", "recon", "verify"],
547
+ escalation_target: ["agent", "human"],
548
+ reasons: ["string"],
549
+ source: "supervising_agent"
550
+ },
551
+ required_state: ["before_cdn or prod_cdn", "after_cdn", "proof_assessment_request"],
552
+ include_ship_gate: true
553
+ },
554
+ verify_human_escalation: {
555
+ purpose: "Proof loop is explicitly escalated to the human after supervising-agent judgment."
556
+ },
557
+ verify_agent_retry: {
558
+ purpose: "Supervising agent judged the proof insufficient and kept the workflow inside the internal loop.",
559
+ accepted_inputs: [{
560
+ name: "author_packet_json",
561
+ type: "json",
562
+ description: "Optional revised proof packet if the checkpoint resumes to author."
563
+ }]
564
+ },
565
+ verify_ship_ready: {
566
+ purpose: "Proof assessment is ready_to_ship and the next continuation should enter ship.",
567
+ include_ship_gate: true
568
+ },
569
+ verify_required: {
570
+ purpose: "Ship is blocked until verify captures usable after evidence.",
571
+ include_ship_gate: true
572
+ },
573
+ verify_supervisor_judgment_required: {
574
+ purpose: "Ship is blocked until the supervising agent judges the current evidence ready_to_ship.",
575
+ accepted_inputs: [{
576
+ name: "proof_assessment_json",
577
+ type: "json",
578
+ required: true,
579
+ description: "JSON assessment that must use decision=ready_to_ship before ship can continue."
580
+ }],
581
+ include_ship_gate: true
582
+ },
583
+ ship_gate_blocked: {
584
+ purpose: "Ship is blocked because required baseline, after evidence, or supervising-agent proof approval is missing.",
585
+ include_ship_gate: true
586
+ },
587
+ ship_review: {
588
+ purpose: "Ship completed; inspect the PR, proof comment, and CI status.",
589
+ include_ship_gate: true
590
+ }
591
+ };
592
+ function buildCheckpointContract(state, request) {
593
+ const spec = CHECKPOINT_CONTRACT_SPECS[request.checkpoint] || {
594
+ purpose: request.summary
595
+ };
596
+ const continueWithStage = request.continueWithStage || request.recommendedAdvanceStage || null;
597
+ const payload = {
598
+ version: CHECKPOINT_CONTRACT_VERSION,
599
+ checkpoint: request.checkpoint,
600
+ stage: request.stage,
601
+ purpose: spec.purpose,
602
+ summary: request.summary,
603
+ blocking: Boolean(request.blocking),
604
+ next_actions: request.nextActions || [],
605
+ advance_options: request.advanceOptions || [],
606
+ accepted_inputs: spec.accepted_inputs || [],
607
+ response_schema: spec.response_schema || null,
608
+ required_state: spec.required_state || [],
609
+ resume: {
610
+ action: "run",
611
+ state_path: request.statePath || null,
612
+ continue_from_checkpoint: Boolean(continueWithStage),
613
+ continue_with_stage: continueWithStage
614
+ }
615
+ };
616
+ if (spec.include_ship_gate) {
617
+ payload.ship_gate = validateShipGate(state);
618
+ }
619
+ return payload;
620
+ }
621
+ function mergeStateFromParams(statePath, params) {
622
+ const state = readState(statePath);
623
+ if (!state) return null;
624
+ ensureStageLoopState(state);
625
+ const stringFields = [
626
+ "change_request",
627
+ "commit_message",
628
+ "prod_url",
629
+ "capture_script",
630
+ "success_criteria",
631
+ "assertions_json",
632
+ "verification_mode",
633
+ "base_branch",
634
+ "before_ref",
635
+ "context",
636
+ "reviewer",
637
+ "build_command",
638
+ "build_output",
639
+ "server_image",
640
+ "server_command",
641
+ "server_path",
642
+ "wait_for_selector",
643
+ "discord_channel",
644
+ "discord_thread_id",
645
+ "discord_message_id",
646
+ "discord_source_url",
647
+ "auth_localStorage_json",
648
+ "auth_cookies_json",
649
+ "auth_headers_json",
650
+ "proof_plan",
651
+ "implementation_notes"
652
+ ];
653
+ for (const field of stringFields) {
654
+ if (params[field] !== void 0) {
655
+ state[field] = normalizeOptionalString(params[field]);
656
+ }
657
+ }
658
+ if (params.server_path !== void 0) {
659
+ state.server_path_source = "tool_param";
660
+ }
661
+ if (params.implementation_notes !== void 0) {
662
+ const issues = knownEnvironmentIssuesFromNotes(state.implementation_notes || "");
663
+ if (issues.length) state.implementation_environment_issues = issues;
664
+ }
665
+ if (params.reference !== void 0) state.reference = params.reference;
666
+ if (params.mode !== void 0) state.mode = params.mode;
667
+ if (params.allow_static_preview_fallback !== void 0) {
668
+ state.allow_static_preview_fallback = params.allow_static_preview_fallback;
669
+ }
670
+ if (params.server_port !== void 0) state.server_port = String(params.server_port);
671
+ if (params.color_scheme !== void 0) state.color_scheme = params.color_scheme || "";
672
+ if (params.use_auth !== void 0) state.use_auth = params.use_auth ? "true" : "";
673
+ if (params.leave_draft !== void 0) state.leave_draft = params.leave_draft ? "true" : "";
674
+ if (params.advance_stage !== void 0) state.last_requested_advance_stage = params.advance_stage;
675
+ if (params.recon_assessment_json !== void 0) {
676
+ const raw = normalizeOptionalString(params.recon_assessment_json) || "";
677
+ if (!raw) {
678
+ state.recon_assessment = {};
679
+ state.recon_assessment_source = null;
680
+ } else {
681
+ const parsed = JSON.parse(raw);
682
+ state.recon_assessment = {
683
+ ...parsed,
684
+ source: (parsed?.source || "supervising_agent").toString()
685
+ };
686
+ state.recon_assessment_source = state.recon_assessment.source;
687
+ if (parsed?.baseline_understanding && typeof parsed.baseline_understanding === "object") {
688
+ state.recon_baseline_understanding = parsed.baseline_understanding;
689
+ }
690
+ const refined = parsed?.refined_inputs || {};
691
+ if (typeof refined?.server_path === "string") {
692
+ state.server_path = normalizeOptionalString(refined.server_path) || "";
693
+ state.server_path_source = "supervising_agent";
694
+ }
695
+ if (typeof refined?.wait_for_selector === "string") state.wait_for_selector = normalizeOptionalString(refined.wait_for_selector) || "";
696
+ if (typeof refined?.reference === "string" && refined.reference.trim()) state.reference = refined.reference.trim();
697
+ }
698
+ }
699
+ if (params.author_packet_json !== void 0) {
700
+ const raw = normalizeOptionalString(params.author_packet_json) || "";
701
+ if (!raw) {
702
+ state.supervisor_author_packet = null;
703
+ } else {
704
+ const parsed = JSON.parse(raw);
705
+ if (typeof parsed?.capture_script === "string") {
706
+ parsed.capture_script = normalizeCaptureScript(parsed.capture_script);
707
+ }
708
+ state.supervisor_author_packet = parsed;
709
+ if (typeof parsed?.proof_plan === "string") state.proof_plan = normalizeOptionalString(parsed.proof_plan) || "";
710
+ if (typeof parsed?.capture_script === "string") state.capture_script = normalizeCaptureScript(parsed.capture_script);
711
+ if (parsed?.baseline_understanding_used && typeof parsed.baseline_understanding_used === "object") {
712
+ state.author_baseline_understanding_used = parsed.baseline_understanding_used;
713
+ }
714
+ const refined = parsed?.refined_inputs || {};
715
+ if (typeof refined?.server_path === "string") {
716
+ state.server_path = normalizeOptionalString(refined.server_path) || "";
717
+ state.server_path_source = "supervising_agent";
718
+ }
719
+ if (typeof refined?.wait_for_selector === "string") state.wait_for_selector = normalizeOptionalString(refined.wait_for_selector) || "";
720
+ if (typeof refined?.reference === "string" && refined.reference.trim()) state.reference = refined.reference.trim();
721
+ if (typeof parsed?.confidence === "string") state.supervisor_author_confidence = normalizeOptionalString(parsed.confidence) || null;
722
+ if (parsed?.rationale !== void 0) state.supervisor_author_rationale = parsed.rationale;
723
+ if (typeof parsed?.summary === "string") state.supervisor_author_summary = normalizeOptionalString(parsed.summary) || null;
724
+ invalidateVerifyEvidence(state);
725
+ }
726
+ }
727
+ if (params.proof_assessment_json !== void 0) {
728
+ const raw = normalizeOptionalString(params.proof_assessment_json) || "";
729
+ if (!raw) {
730
+ state.proof_assessment = {};
731
+ state.proof_assessment_source = null;
732
+ } else {
733
+ const parsed = JSON.parse(raw);
734
+ state.proof_assessment = {
735
+ ...parsed,
736
+ source: (parsed?.source || "supervising_agent").toString()
737
+ };
738
+ state.proof_assessment_source = state.proof_assessment.source;
739
+ if (typeof parsed?.decision === "string") {
740
+ state.proof_decision = parsed.decision;
741
+ }
742
+ if (typeof parsed?.summary === "string") {
743
+ state.proof_assessment_summary = normalizeOptionalString(parsed.summary) || null;
744
+ }
745
+ if (parsed?.decision === "ready_to_ship") {
746
+ state.merge_recommendation = "ready-to-ship";
747
+ } else if (typeof parsed?.decision === "string" && parsed.decision.trim()) {
748
+ state.merge_recommendation = "do-not-merge";
749
+ }
750
+ appendProofSummaryLine(state, `Supervising proof assessment: ${state.proof_assessment.decision || "unknown"}`);
751
+ if (state.proof_assessment_summary) {
752
+ appendProofSummaryLine(state, `Assessment summary: ${state.proof_assessment_summary}`);
753
+ }
754
+ const reasons = Array.isArray(parsed?.reasons) ? parsed.reasons.filter((item) => typeof item === "string" && item.trim()).slice(0, 4) : [];
755
+ if (reasons.length) {
756
+ appendProofSummaryLine(state, `Assessment reasons: ${reasons.join("; ")}`);
757
+ }
758
+ }
759
+ }
760
+ if (params.assertions_json !== void 0) {
761
+ const raw = normalizeOptionalString(params.assertions_json) || "";
762
+ if (!raw) {
763
+ state.parsed_assertions = null;
764
+ } else {
765
+ state.parsed_assertions = JSON.parse(raw);
766
+ }
767
+ }
768
+ if ((params.proof_plan !== void 0 || params.capture_script !== void 0) && hasAuthoredProofPlan(state)) {
769
+ state.author_summary = state.author_summary || "Proof authoring inputs were updated from tool params.";
770
+ }
771
+ syncAuthoringState(state);
772
+ writeState(statePath, state);
773
+ return state;
774
+ }
775
+ function summarizeState(state) {
776
+ if (!state) {
777
+ return {
778
+ stage: "missing",
779
+ summary: "No riddle-proof state file exists yet.",
780
+ state: null
781
+ };
782
+ }
783
+ ensureStageLoopState(state);
784
+ const attemptCounts = Object.fromEntries(
785
+ WORKFLOW_STAGE_ORDER.map((stage) => [stage, Number(state.stage_attempts?.[stage]?.count || 0)])
786
+ );
787
+ const selected = {
788
+ workspace_ready: Boolean(state.workspace_ready),
789
+ repo: state.repo || null,
790
+ branch: state.branch || null,
791
+ mode: state.mode || null,
792
+ reference: state.reference || null,
793
+ before_ref: state.before_ref || null,
794
+ allow_static_preview_fallback: Boolean(state.allow_static_preview_fallback),
795
+ commit_message: state.commit_message || null,
796
+ author_status: state.author_status || null,
797
+ author_summary: state.author_summary || null,
798
+ author_request: state.author_request || null,
799
+ proof_plan_status: state.proof_plan_status || null,
800
+ proof_plan: state.proof_plan || null,
801
+ proof_plan_request: state.proof_plan_request || null,
802
+ proof_profile_applied: Boolean(state.proof_profile),
803
+ proof_profile: state.proof_profile || null,
804
+ recon_status: state.recon_status || null,
805
+ recon_assessment: state.recon_assessment || null,
806
+ recon_assessment_request: state.recon_assessment_request || null,
807
+ recon_assessment_source: state.recon_assessment_source || null,
808
+ recon_decision_request: state.recon_decision_request || null,
809
+ recon_attempts_used: Array.isArray(state.recon_results?.attempt_history) ? state.recon_results.attempt_history.length : 0,
810
+ recon_attempts_max: state.recon_results?.max_attempts || null,
811
+ recon_hypothesis: state.recon_hypothesis || null,
812
+ implementation_status: state.implementation_status || null,
813
+ implementation_summary: state.implementation_summary || null,
814
+ implementation_environment_issues: state.implementation_environment_issues || [],
815
+ verify_status: state.verify_status || null,
816
+ verify_summary: state.verify_summary || null,
817
+ verify_decision_request: state.verify_decision_request || null,
818
+ proof_assessment: state.proof_assessment || null,
819
+ proof_assessment_request: state.proof_assessment_request || null,
820
+ proof_assessment_source: state.proof_assessment_source || null,
821
+ merge_recommendation: state.merge_recommendation || null,
822
+ before_cdn: state.before_cdn || null,
823
+ after_cdn: state.after_cdn || null,
824
+ prod_cdn: state.prod_cdn || null,
825
+ pr_url: state.pr_url || null,
826
+ pr_branch: state.target_branch || state.branch || null,
827
+ pr_state: state.pr_state || null,
828
+ ship_commit: state.ship_commit || null,
829
+ ship_remote_head: state.ship_remote_head || null,
830
+ merge_commit: state.merge_commit || null,
831
+ merged_at: state.merged_at || null,
832
+ ship_push: state.ship_push || null,
833
+ ship_report: state.ship_report || null,
834
+ cleanup_report: state.cleanup_report || null,
835
+ proof_comment_url: state.proof_comment_url || null,
836
+ proof_assessment_comment_url: state.proof_assessment_comment_url || null,
837
+ marked_ready: typeof state.marked_ready === "boolean" ? state.marked_ready : null,
838
+ left_draft: typeof state.left_draft === "boolean" ? state.left_draft : null,
839
+ ci_status: state.ci_status || null,
840
+ reviewer: state.reviewer || null,
841
+ active_checkpoint: state.active_checkpoint || null,
842
+ active_checkpoint_stage: state.active_checkpoint_stage || null,
843
+ continue_with_stage: checkpointContinueStage(state),
844
+ stage_decision_request: state.stage_decision_request || {},
845
+ stage_attempt_counts: attemptCounts,
846
+ explicit_stage_gate: Boolean(state.explicit_stage_gate),
847
+ last_requested_advance_stage: state.last_requested_advance_stage || null,
848
+ recon_results: state.recon_results || null,
849
+ verify_results: state.verify_results || null
850
+ };
851
+ const parts = [
852
+ state.workspace_ready ? "workspace ready" : "workspace not ready",
853
+ state.mode ? `mode=${state.mode}` : null,
854
+ state.reference ? `reference=${state.reference}` : null,
855
+ state.author_status ? `author=${state.author_status}` : null,
856
+ state.proof_plan_status ? `proof=${state.proof_plan_status}` : null,
857
+ state.recon_status ? `recon=${state.recon_status}` : null,
858
+ state.implementation_status ? `implement=${state.implementation_status}` : null,
859
+ state.verify_status ? `verify=${state.verify_status}` : null,
860
+ state.active_checkpoint ? `checkpoint=${state.active_checkpoint}` : null,
861
+ state.after_cdn ? "after evidence captured" : null,
862
+ state.pr_url ? "PR linked" : null
863
+ ].filter(Boolean);
864
+ return {
865
+ stage: state.stage || (state.after_cdn ? "verified" : state.workspace_ready ? "setup" : "unknown"),
866
+ summary: parts.length ? parts.join(", ") : "State file present.",
867
+ state: selected
868
+ };
869
+ }
870
+
871
+ // src/proof-run-engine.ts
872
+ function snapshotFor(statePath) {
873
+ return summarizeState(readState(statePath));
874
+ }
875
+ function authorReady(state) {
876
+ return state?.author_status === "ready" || state?.proof_plan_status === "ready";
877
+ }
878
+ function implementationReady(state) {
879
+ return ["changes_detected", "completed"].includes(state?.implementation_status || "");
880
+ }
881
+ function stageAfterAuthor(state) {
882
+ return implementationReady(state) ? "verify" : "implement";
883
+ }
884
+ function latestReconAttempt(state) {
885
+ const history = Array.isArray(state?.recon_results?.attempt_history) ? state.recon_results.attempt_history : [];
886
+ return history.length ? history[history.length - 1] : null;
887
+ }
888
+ function latestReconCapturedBaselines(state) {
889
+ const latest = latestReconAttempt(state);
890
+ if (latest?.captured_baselines && typeof latest.captured_baselines === "object") return latest.captured_baselines;
891
+ if (latest?.baselines && typeof latest.baselines === "object") return latest.baselines;
892
+ return state?.recon_results?.baselines || {};
893
+ }
894
+ function requiredReconBaselineLabels(state) {
895
+ const labels = [];
896
+ const reference = state?.requested_reference || state?.reference || "before";
897
+ if (reference === "before" || reference === "both") labels.push("before");
898
+ if ((reference === "prod" || reference === "both") && String(state?.prod_url || "").trim()) labels.push("prod");
899
+ return labels;
900
+ }
901
+ function latestReconHasRequiredBaselines(state) {
902
+ const baselines = latestReconCapturedBaselines(state);
903
+ return requiredReconBaselineLabels(state).every((label) => Boolean((baselines?.[label]?.url || "").trim()));
904
+ }
905
+ function hasReconBaselineUnderstanding(state) {
906
+ const understanding = state?.recon_assessment?.baseline_understanding || state?.recon_baseline_understanding || {};
907
+ return Boolean(
908
+ String(understanding?.visible_before_state || "").trim() && String(understanding?.requested_change || "").trim() && String(understanding?.proof_focus || "").trim() && String(understanding?.stop_condition || "").trim()
909
+ );
910
+ }
911
+ function promoteLatestReconBaselines(state) {
912
+ const baselines = latestReconCapturedBaselines(state);
913
+ state.recon_results = state.recon_results || {};
914
+ state.recon_results.baselines = baselines;
915
+ state.recon_results.selected_attempt = latestReconAttempt(state) || {};
916
+ state.before_cdn = (baselines?.before?.url || "").trim();
917
+ state.prod_cdn = (baselines?.prod?.url || "").trim();
918
+ return baselines;
919
+ }
920
+ function hasSupervisorReconAssessment(state) {
921
+ const reconAssessment2 = state?.recon_assessment || {};
922
+ const source = String(reconAssessment2?.source || state?.recon_assessment_source || "").trim().toLowerCase();
923
+ if (!reconAssessment2?.decision) return false;
924
+ return source === "supervising_agent" || source === "supervisor";
925
+ }
926
+ function reconAssessment(state) {
927
+ const assessment = state?.recon_assessment || {};
928
+ const decision = assessment?.decision || null;
929
+ const continueWithStage = assessment?.continue_with_stage || assessment?.recommended_stage || (decision === "ready_for_author" ? "author" : "recon");
930
+ return {
931
+ decision,
932
+ summary: assessment?.summary || state?.recon_assessment_request?.summary || state?.recon_summary || null,
933
+ recommendedStage: assessment?.recommended_stage || continueWithStage || null,
934
+ continueWithStage: continueWithStage || null,
935
+ escalationTarget: assessment?.escalation_target || "agent",
936
+ reasons: Array.isArray(assessment?.reasons) ? assessment.reasons : [],
937
+ raw: assessment,
938
+ source: String(assessment?.source || state?.recon_assessment_source || "").trim() || null
939
+ };
940
+ }
941
+ function updateState(statePath, mutate) {
942
+ const state = readState(statePath) || {};
943
+ mutate(state);
944
+ writeState(statePath, state);
945
+ return state;
946
+ }
947
+ function hasSupervisorProofAssessment(state) {
948
+ const proofAssessment = state?.proof_assessment || {};
949
+ const source = String(proofAssessment?.source || state?.proof_assessment_source || "").trim().toLowerCase();
950
+ if (!proofAssessment?.decision) return false;
951
+ return source === "supervising_agent" || source === "supervisor";
952
+ }
953
+ function verifyAssessment(state) {
954
+ const proofAssessment = state?.proof_assessment || {};
955
+ const verifyDecision = state?.verify_decision_request || {};
956
+ if (hasSupervisorProofAssessment(state)) {
957
+ return {
958
+ decision: proofAssessment?.decision || null,
959
+ summary: proofAssessment?.summary || verifyDecision?.summary || null,
960
+ recommendedStage: proofAssessment?.continue_with_stage || proofAssessment?.recommended_stage || verifyDecision?.continue_with_stage || verifyDecision?.recommended_stage || null,
961
+ continueWithStage: proofAssessment?.continue_with_stage || verifyDecision?.continue_with_stage || proofAssessment?.recommended_stage || verifyDecision?.recommended_stage || null,
962
+ escalationTarget: proofAssessment?.escalation_target || "agent",
963
+ reasons: Array.isArray(proofAssessment?.reasons) ? proofAssessment.reasons : [],
964
+ raw: proofAssessment,
965
+ source: "supervising_agent"
966
+ };
967
+ }
968
+ if (state?.verify_status === "capture_incomplete") {
969
+ return {
970
+ decision: verifyDecision?.capture_quality?.decision || "revise_capture",
971
+ summary: verifyDecision?.summary || "Verify needs another internal capture iteration before the evidence can be judged.",
972
+ recommendedStage: verifyDecision?.continue_with_stage || verifyDecision?.recommended_stage || "author",
973
+ continueWithStage: verifyDecision?.continue_with_stage || verifyDecision?.recommended_stage || "author",
974
+ escalationTarget: "agent",
975
+ reasons: Array.isArray(verifyDecision?.capture_quality?.reasons) ? verifyDecision.capture_quality.reasons : [],
976
+ raw: verifyDecision?.capture_quality || verifyDecision,
977
+ source: "workflow_capture"
978
+ };
979
+ }
980
+ return {
981
+ decision: null,
982
+ summary: verifyDecision?.summary || "Verify captured evidence and is waiting for supervising-agent proof assessment.",
983
+ recommendedStage: null,
984
+ continueWithStage: null,
985
+ escalationTarget: "agent",
986
+ reasons: [],
987
+ raw: proofAssessment,
988
+ source: "awaiting_supervisor"
989
+ };
990
+ }
991
+ function nonConvergenceSignals(state, assessment = verifyAssessment(state)) {
992
+ const verifyAttempts = Number(state?.stage_attempts?.verify?.count || 0);
993
+ const authorAttempts = Number(state?.stage_attempts?.author?.count || 0);
994
+ const reconAttempts = Number(state?.stage_attempts?.recon?.count || 0);
995
+ const continueStage = assessment.continueWithStage || assessment.recommendedStage || null;
996
+ return {
997
+ verifyAttempts,
998
+ authorAttempts,
999
+ reconAttempts,
1000
+ continueStage,
1001
+ warning: verifyAttempts >= 4 || continueStage === "author" && verifyAttempts >= 2 && authorAttempts >= 2 || continueStage === "recon" && verifyAttempts >= 2 && reconAttempts >= 2 || continueStage === "implement" && verifyAttempts >= 2
1002
+ };
1003
+ }
1004
+ function shouldEscalateVerifyToHuman(_state, assessment = verifyAssessment(_state)) {
1005
+ return assessment.escalationTarget === "human";
1006
+ }
1007
+ function recommendedAdvanceStage(state) {
1008
+ if (!state?.workspace_ready) return "setup";
1009
+ if (!state?.recon_results || ["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "")) return "recon";
1010
+ if (!authorReady(state)) return "author";
1011
+ if (!implementationReady(state)) return "implement";
1012
+ if (state?.verify_status === "capture_incomplete") return verifyAssessment(state).continueWithStage || verifyAssessment(state).recommendedStage || "author";
1013
+ if (state?.verify_status === "evidence_captured") return verifyAssessment(state).continueWithStage || verifyAssessment(state).recommendedStage;
1014
+ if (!(state?.after_cdn || "").trim()) return "verify";
1015
+ return null;
1016
+ }
1017
+ function normalizeStageRequest(state, requestedAdvanceStage) {
1018
+ if (requestedAdvanceStage) return requestedAdvanceStage;
1019
+ if (!state?.workspace_ready) return null;
1020
+ if (!state?.recon_results || ["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "")) return "recon";
1021
+ return null;
1022
+ }
1023
+ function stringValue(value) {
1024
+ return typeof value === "string" && value.trim() ? value.trim() : "";
1025
+ }
1026
+ function commandResult(command, args, cwd, timeout = 6e4) {
1027
+ try {
1028
+ return {
1029
+ ok: true,
1030
+ stdout: (0, import_node_child_process.execFileSync)(command, args, { cwd, encoding: "utf-8", timeout, stdio: ["ignore", "pipe", "pipe"] }),
1031
+ stderr: ""
1032
+ };
1033
+ } catch (error) {
1034
+ return {
1035
+ ok: false,
1036
+ stdout: String(error?.stdout || ""),
1037
+ stderr: String(error?.stderr || error?.message || "")
1038
+ };
1039
+ }
1040
+ }
1041
+ function repoDirForSync(state) {
1042
+ const candidates = [
1043
+ state?.repo_dir,
1044
+ state?.after_worktree,
1045
+ state?.before_worktree
1046
+ ].map(stringValue).filter(Boolean);
1047
+ return candidates.find((candidate) => (0, import_node_fs2.existsSync)(import_node_path2.default.join(candidate, ".git"))) || "";
1048
+ }
1049
+ function parseWorktreeList(output) {
1050
+ const entries = [];
1051
+ let current = {};
1052
+ for (const line of output.split(/\r?\n/)) {
1053
+ if (!line.trim()) {
1054
+ if (current.worktree) entries.push(current);
1055
+ current = {};
1056
+ continue;
1057
+ }
1058
+ const [key, ...rest] = line.split(" ");
1059
+ const value = rest.join(" ").trim();
1060
+ if (key === "worktree" || key === "HEAD" || key === "branch" || key === "detached") current[key] = value;
1061
+ }
1062
+ if (current.worktree) entries.push(current);
1063
+ return entries;
1064
+ }
1065
+ function gitStdout(cwd, args, timeout = 6e4) {
1066
+ const result = commandResult("git", args, cwd, timeout);
1067
+ return result.ok ? result.stdout.trim() : "";
1068
+ }
1069
+ function shortBranch(ref) {
1070
+ return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
1071
+ }
1072
+ function safeInteger(value) {
1073
+ const parsed = Number.parseInt(value, 10);
1074
+ return Number.isFinite(parsed) ? parsed : null;
1075
+ }
1076
+ function baseCheckoutReport(repoDir, baseBranch, updateRequested, updateAllowed) {
1077
+ const remoteRef = `origin/${baseBranch}`;
1078
+ const report = {
1079
+ requested: updateRequested,
1080
+ repo_dir: repoDir,
1081
+ base_branch: baseBranch,
1082
+ remote_ref: remoteRef,
1083
+ updated: false
1084
+ };
1085
+ const listed = commandResult("git", ["worktree", "list", "--porcelain"], repoDir, 6e4);
1086
+ if (!listed.ok) {
1087
+ report.update_skipped = "worktree_list_failed";
1088
+ report.error = listed.stderr.slice(0, 300);
1089
+ return report;
1090
+ }
1091
+ const worktrees = parseWorktreeList(listed.stdout);
1092
+ const baseRef = `refs/heads/${baseBranch}`;
1093
+ const selected = worktrees.find((entry) => entry.branch === baseRef) || worktrees.find((entry) => import_node_path2.default.resolve(entry.worktree || "") === import_node_path2.default.resolve(repoDir) && shortBranch(entry.branch || "") === baseBranch);
1094
+ if (!selected?.worktree) {
1095
+ report.worktrees_seen = worktrees.map((entry) => ({
1096
+ path: entry.worktree || null,
1097
+ branch: entry.branch ? shortBranch(entry.branch) : null,
1098
+ detached: Boolean(entry.detached)
1099
+ }));
1100
+ report.update_skipped = "base_worktree_not_found";
1101
+ return report;
1102
+ }
1103
+ const baseDir = selected.worktree;
1104
+ const branch = shortBranch(selected.branch || "");
1105
+ const status = commandResult("git", ["status", "--porcelain"], baseDir, 6e4);
1106
+ const clean = status.ok && !status.stdout.trim();
1107
+ const localHead = gitStdout(baseDir, ["rev-parse", "HEAD"]);
1108
+ const remoteHead = gitStdout(baseDir, ["rev-parse", "--verify", remoteRef]);
1109
+ const counts = remoteHead ? gitStdout(baseDir, ["rev-list", "--left-right", "--count", `HEAD...${remoteRef}`]) : "";
1110
+ const [aheadRaw, behindRaw] = counts.split(/\s+/);
1111
+ Object.assign(report, {
1112
+ base_worktree: baseDir,
1113
+ branch: branch || null,
1114
+ clean,
1115
+ local_head: localHead || null,
1116
+ remote_head: remoteHead || null,
1117
+ ahead: safeInteger(aheadRaw || ""),
1118
+ behind: safeInteger(behindRaw || "")
1119
+ });
1120
+ if (!updateRequested) {
1121
+ report.update_skipped = "update_not_requested";
1122
+ return report;
1123
+ }
1124
+ if (!updateAllowed) {
1125
+ report.update_skipped = "fetch_failed";
1126
+ return report;
1127
+ }
1128
+ if (branch !== baseBranch) {
1129
+ report.update_skipped = "base_worktree_not_on_base_branch";
1130
+ return report;
1131
+ }
1132
+ if (!status.ok) {
1133
+ report.update_skipped = "status_failed";
1134
+ report.status_error = status.stderr.slice(0, 300);
1135
+ return report;
1136
+ }
1137
+ if (!clean) {
1138
+ report.update_skipped = "base_worktree_dirty";
1139
+ return report;
1140
+ }
1141
+ if (!remoteHead) {
1142
+ report.update_skipped = "remote_ref_missing";
1143
+ return report;
1144
+ }
1145
+ if (localHead && localHead === remoteHead) {
1146
+ report.update_skipped = "already_current";
1147
+ return report;
1148
+ }
1149
+ const merge = commandResult("git", ["merge", "--ff-only", remoteRef], baseDir, 12e4);
1150
+ if (!merge.ok) {
1151
+ report.update_skipped = "fast_forward_failed";
1152
+ report.update_error = merge.stderr.slice(0, 500);
1153
+ return report;
1154
+ }
1155
+ const updatedHead = gitStdout(baseDir, ["rev-parse", "HEAD"]);
1156
+ const updatedCounts = gitStdout(baseDir, ["rev-list", "--left-right", "--count", `HEAD...${remoteRef}`]);
1157
+ const [updatedAheadRaw, updatedBehindRaw] = updatedCounts.split(/\s+/);
1158
+ report.updated = true;
1159
+ report.local_head = updatedHead || report.local_head;
1160
+ report.ahead = safeInteger(updatedAheadRaw || "");
1161
+ report.behind = safeInteger(updatedBehindRaw || "");
1162
+ report.update_summary = merge.stdout.trim().slice(0, 500);
1163
+ return report;
1164
+ }
1165
+ function normalizeGhPrStatus(value) {
1166
+ const status = stringValue(value).toLowerCase();
1167
+ if (status === "merged") return "merged";
1168
+ if (status === "open") return "open";
1169
+ if (status === "closed") return "closed";
1170
+ return status || "unknown";
1171
+ }
1172
+ function prRefFromState(state) {
1173
+ return stringValue(state?.pr_number) || stringValue(state?.pr_url);
1174
+ }
1175
+ function prNumberFromUrl(url) {
1176
+ const match = url.match(/\/pull\/(\d+)(?:$|[?#])/);
1177
+ return match?.[1] || "";
1178
+ }
1179
+ function normalizePrState(raw, state, checkedAt = (/* @__PURE__ */ new Date()).toISOString()) {
1180
+ const mergeCommit = typeof raw?.mergeCommit === "object" && raw.mergeCommit ? stringValue(raw.mergeCommit.oid) : stringValue(raw?.mergeCommit);
1181
+ const url = stringValue(raw?.url) || stringValue(state?.pr_url);
1182
+ return {
1183
+ status: normalizeGhPrStatus(raw?.state),
1184
+ pr_url: url || null,
1185
+ pr_number: String(raw?.number || state?.pr_number || prNumberFromUrl(url) || ""),
1186
+ repo: stringValue(state?.repo) || null,
1187
+ head_branch: stringValue(raw?.headRefName) || stringValue(state?.target_branch) || stringValue(state?.branch) || null,
1188
+ base_branch: stringValue(raw?.baseRefName) || stringValue(state?.base_branch) || "main",
1189
+ merge_commit: mergeCommit || null,
1190
+ merged_at: stringValue(raw?.mergedAt) || null,
1191
+ closed_at: stringValue(raw?.closedAt) || null,
1192
+ checked_at: checkedAt,
1193
+ source: "gh"
1194
+ };
1195
+ }
1196
+ function cleanupMergedProofRun(state, repoDir, params, prState) {
1197
+ const cleanup = {
1198
+ requested: params.cleanup_merged_pr !== false,
1199
+ fetch_base: params.fetch_base !== false,
1200
+ update_base_checkout: params.update_base_checkout !== false,
1201
+ repo_dir: repoDir,
1202
+ worktrees_removed: [],
1203
+ worktree_remove_errors: [],
1204
+ branches_deleted: [],
1205
+ branch_delete_errors: [],
1206
+ pruned: false
1207
+ };
1208
+ const baseBranch = stringValue(prState.base_branch) || stringValue(state?.base_branch) || "main";
1209
+ let fetchedBase = params.fetch_base === false;
1210
+ if (params.fetch_base !== false && baseBranch) {
1211
+ const fetch = commandResult("git", ["fetch", "origin", baseBranch], repoDir, 12e4);
1212
+ cleanup.fetch = fetch.ok ? { ok: true, base_branch: baseBranch } : { ok: false, base_branch: baseBranch, error: fetch.stderr.slice(0, 300) };
1213
+ if (fetch.ok) {
1214
+ fetchedBase = true;
1215
+ state.base_synced_at = (/* @__PURE__ */ new Date()).toISOString();
1216
+ state.base_branch = baseBranch;
1217
+ }
1218
+ }
1219
+ cleanup.base_checkout = baseCheckoutReport(repoDir, baseBranch, params.update_base_checkout !== false, fetchedBase);
1220
+ if (params.cleanup_merged_pr === false) {
1221
+ cleanup.skipped = "cleanup_disabled";
1222
+ return cleanup;
1223
+ }
1224
+ const removed = [];
1225
+ const removeErrors = [];
1226
+ for (const candidate of [state?.before_worktree, state?.after_worktree].map(stringValue).filter(Boolean)) {
1227
+ if (!(0, import_node_fs2.existsSync)(candidate) || import_node_path2.default.resolve(candidate) === import_node_path2.default.resolve(repoDir)) continue;
1228
+ const remove = commandResult("git", ["worktree", "remove", "--force", candidate], repoDir, 12e4);
1229
+ if (remove.ok) {
1230
+ removed.push(candidate);
1231
+ } else {
1232
+ removeErrors.push({ path: candidate, error: remove.stderr.slice(0, 300) });
1233
+ }
1234
+ }
1235
+ cleanup.worktrees_removed = removed;
1236
+ cleanup.worktree_remove_errors = removeErrors;
1237
+ const afterBranch = stringValue(state?.after_worktree_branch);
1238
+ if (afterBranch.startsWith("riddle-proof/")) {
1239
+ const deleted = commandResult("git", ["branch", "-D", afterBranch], repoDir, 6e4);
1240
+ if (deleted.ok) {
1241
+ cleanup.branches_deleted = [afterBranch];
1242
+ } else {
1243
+ cleanup.branch_delete_errors = [{ branch: afterBranch, error: deleted.stderr.slice(0, 300) }];
1244
+ }
1245
+ }
1246
+ const prune = commandResult("git", ["worktree", "prune"], repoDir, 6e4);
1247
+ cleanup.pruned = prune.ok;
1248
+ if (!prune.ok) cleanup.prune_error = prune.stderr.slice(0, 300);
1249
+ return cleanup;
1250
+ }
1251
+ function syncPrLifecycle(statePath, params) {
1252
+ const state = readState(statePath);
1253
+ if (!state) {
1254
+ return {
1255
+ ok: false,
1256
+ action: "sync",
1257
+ state_path: statePath,
1258
+ checkpoint: "pr_sync_not_found",
1259
+ summary: "No readable Riddle Proof state exists at state_path.",
1260
+ state: null,
1261
+ nextAction: "Check the wrapper state_path or run riddle_proof_status first."
1262
+ };
1263
+ }
1264
+ const repoDir = repoDirForSync(state);
1265
+ const prRef = prRefFromState(state);
1266
+ if (!repoDir || !prRef) {
1267
+ const missingPr = !prRef;
1268
+ const orphanSummary = "Riddle Proof state exists, but this run is not recoverable through PR sync because no PR URL or PR number was linked before it stopped.";
1269
+ const orphanNextAction = "Treat this as an orphaned proof run: update the base checkout directly if needed, then clean stale proof worktrees or riddle-proof/* branches outside normal PR sync.";
1270
+ const prState2 = {
1271
+ status: missingPr ? "orphaned" : "unavailable",
1272
+ pr_url: state.pr_url || null,
1273
+ pr_number: String(state.pr_number || prNumberFromUrl(stringValue(state.pr_url)) || ""),
1274
+ repo: state.repo || null,
1275
+ head_branch: state.target_branch || state.branch || null,
1276
+ base_branch: state.base_branch || "main",
1277
+ checked_at: (/* @__PURE__ */ new Date()).toISOString(),
1278
+ source: repoDir ? "state" : "local_state",
1279
+ sync_recoverable: !missingPr,
1280
+ sync_blocker: missingPr ? "missing_pr_linkage" : "missing_local_repo",
1281
+ next_action: missingPr ? orphanNextAction : "State has a PR but no readable local git repo/worktree; restore repo access and rerun sync."
1282
+ };
1283
+ state.pr_state = prState2;
1284
+ if (missingPr) state.pr_sync_summary = orphanSummary;
1285
+ writeState(statePath, state);
1286
+ return {
1287
+ ok: false,
1288
+ action: "sync",
1289
+ state_path: statePath,
1290
+ checkpoint: missingPr ? "pr_sync_no_pr" : "pr_sync_unavailable",
1291
+ summary: missingPr ? orphanSummary : prState2.next_action,
1292
+ state: summarizeState(state).state,
1293
+ pr_state: prState2,
1294
+ nextAction: prState2.next_action
1295
+ };
1296
+ }
1297
+ const viewed = commandResult("gh", ["pr", "view", prRef, "--json", "state,mergedAt,closedAt,mergeCommit,headRefName,baseRefName,url,number"], repoDir, 6e4);
1298
+ if (!viewed.ok) {
1299
+ const prState2 = {
1300
+ status: "unavailable",
1301
+ pr_url: state.pr_url || null,
1302
+ pr_number: String(state.pr_number || prNumberFromUrl(stringValue(state.pr_url)) || ""),
1303
+ repo: state.repo || null,
1304
+ head_branch: state.target_branch || state.branch || null,
1305
+ base_branch: state.base_branch || "main",
1306
+ checked_at: (/* @__PURE__ */ new Date()).toISOString(),
1307
+ source: "gh",
1308
+ next_action: "GitHub PR state is unavailable; fix gh auth/repo access and rerun riddle_proof_sync."
1309
+ };
1310
+ state.pr_state = prState2;
1311
+ state.cleanup_report = { requested: params.cleanup_merged_pr !== false, skipped: "pr_state_unavailable", error: viewed.stderr.slice(0, 300) };
1312
+ writeState(statePath, state);
1313
+ return {
1314
+ ok: false,
1315
+ action: "sync",
1316
+ state_path: statePath,
1317
+ checkpoint: "pr_sync_unavailable",
1318
+ summary: prState2.next_action,
1319
+ state: summarizeState(state).state,
1320
+ pr_state: prState2,
1321
+ cleanup: state.cleanup_report,
1322
+ nextAction: prState2.next_action
1323
+ };
1324
+ }
1325
+ let rawPr;
1326
+ try {
1327
+ rawPr = JSON.parse(viewed.stdout);
1328
+ } catch {
1329
+ rawPr = {};
1330
+ }
1331
+ const prState = normalizePrState(rawPr, state);
1332
+ let cleanup = null;
1333
+ let checkpoint = "pr_sync_open";
1334
+ let ok = true;
1335
+ let summary = "PR is still open; no merge cleanup was performed.";
1336
+ let nextAction = "Wait for the PR to merge, then rerun riddle_proof_sync.";
1337
+ if (prState.status === "merged") {
1338
+ cleanup = cleanupMergedProofRun(state, repoDir, params, prState);
1339
+ prState.cleanup = cleanup;
1340
+ prState.next_action = "The PR is merged; sync recorded proof cleanup and the local base checkout refresh status.";
1341
+ state.finalized = true;
1342
+ state.merge_commit = prState.merge_commit || state.merge_commit || "";
1343
+ state.merged_at = prState.merged_at || state.merged_at || "";
1344
+ state.cleanup_report = cleanup;
1345
+ checkpoint = "pr_sync_merged";
1346
+ summary = "PR is merged and Riddle Proof state has been reconciled.";
1347
+ nextAction = "Start the next proof run from the recorded base checkout; inspect cleanup.base_checkout only if it reports a skipped or failed fast-forward.";
1348
+ } else if (prState.status === "closed") {
1349
+ prState.next_action = "The PR is closed without a merge; inspect the PR before reusing or deleting the branch.";
1350
+ checkpoint = "pr_sync_closed";
1351
+ summary = "PR is closed without a merge; no merge cleanup was performed.";
1352
+ nextAction = prState.next_action;
1353
+ } else if (prState.status !== "open") {
1354
+ ok = false;
1355
+ prState.next_action = "PR state was not recognized; inspect gh pr view output and rerun sync.";
1356
+ checkpoint = "pr_sync_unavailable";
1357
+ summary = prState.next_action;
1358
+ nextAction = prState.next_action;
1359
+ }
1360
+ state.pr_state = prState;
1361
+ state.pr_url = prState.pr_url || state.pr_url;
1362
+ state.pr_number = prState.pr_number || state.pr_number;
1363
+ state.target_branch = prState.head_branch || state.target_branch || state.branch;
1364
+ state.branch = prState.head_branch || state.branch;
1365
+ state.base_branch = prState.base_branch || state.base_branch;
1366
+ writeState(statePath, state);
1367
+ const snapshot = summarizeState(state);
1368
+ return {
1369
+ ok,
1370
+ action: "sync",
1371
+ state_path: statePath,
1372
+ checkpoint,
1373
+ summary,
1374
+ state: snapshot.state,
1375
+ pr_state: prState,
1376
+ cleanup,
1377
+ nextAction
1378
+ };
1379
+ }
1380
+ async function executeWorkflow(params, pluginConfig, resolvedConfig) {
1381
+ const config = resolvedConfig || resolveConfig(pluginConfig, params);
1382
+ const action = ensureAction(params.action);
1383
+ if (!(0, import_node_fs2.existsSync)(config.riddleProofDir)) {
1384
+ throw new Error(`riddle-proof runtime directory not found: ${config.riddleProofDir}`);
1385
+ }
1386
+ if (action === "status") {
1387
+ return {
1388
+ state_path: config.statePath,
1389
+ ...summarizeState(readState(config.statePath))
1390
+ };
1391
+ }
1392
+ if (action === "sync") {
1393
+ return syncPrLifecycle(config.statePath, params);
1394
+ }
1395
+ const stateKey = import_node_path2.default.basename(config.statePath).replace(/[^A-Za-z0-9_.-]/g, "-");
1396
+ const lobsterStateDir = import_node_path2.default.join(import_node_path2.default.dirname(config.statePath), "riddle-proof-lobster-state", stateKey);
1397
+ (0, import_node_fs2.mkdirSync)(lobsterStateDir, { recursive: true });
1398
+ const env = {
1399
+ ...process.env,
1400
+ RIDDLE_PROOF_DIR: config.riddleProofDir,
1401
+ RIDDLE_PROOF_STATE_FILE: config.statePath,
1402
+ RIDDLE_PROOF_ARGS_FILE: config.argsPath,
1403
+ LOBSTER_STATE_DIR: lobsterStateDir
1404
+ };
1405
+ const lobsterCommand = process.env.RIDDLE_PROOF_LOBSTER_COMMAND || "lobster";
1406
+ const lobsterPrefix = process.env.RIDDLE_PROOF_LOBSTER_SCRIPT ? [process.env.RIDDLE_PROOF_LOBSTER_SCRIPT] : [];
1407
+ const runOne = (step) => {
1408
+ const args = step === "setup" ? buildSetupArgs(params, config) : {};
1409
+ let output;
1410
+ try {
1411
+ output = JSON.parse(
1412
+ (0, import_node_child_process.execFileSync)(lobsterCommand, [...lobsterPrefix, "run", "--file", workflowFile(config.riddleProofDir, step), "--args-json", JSON.stringify(args)], {
1413
+ encoding: "utf-8",
1414
+ env
1415
+ })
1416
+ );
1417
+ } catch (error) {
1418
+ return {
1419
+ ok: false,
1420
+ step,
1421
+ error: error?.message || String(error),
1422
+ stdout: String(error?.stdout || ""),
1423
+ stderr: String(error?.stderr || "")
1424
+ };
1425
+ }
1426
+ if (output?.status === "needs_approval") {
1427
+ if (!params.auto_approve) {
1428
+ return {
1429
+ ok: false,
1430
+ haltedForApproval: true,
1431
+ step,
1432
+ approval: output.requiresApproval || null,
1433
+ raw: output
1434
+ };
1435
+ }
1436
+ const token = output?.requiresApproval?.resumeToken;
1437
+ if (!token) throw new Error(`${step} requested approval without a resume token.`);
1438
+ const resumed = JSON.parse(
1439
+ (0, import_node_child_process.execFileSync)(lobsterCommand, [...lobsterPrefix, "resume", "--token", token, "--approve", "yes"], {
1440
+ encoding: "utf-8",
1441
+ env
1442
+ })
1443
+ );
1444
+ return {
1445
+ ok: resumed?.ok !== false,
1446
+ step,
1447
+ autoApproved: true,
1448
+ raw: resumed
1449
+ };
1450
+ }
1451
+ return {
1452
+ ok: output?.ok !== false,
1453
+ step,
1454
+ raw: output
1455
+ };
1456
+ };
1457
+ let effectiveAdvanceStage = params.advance_stage || null;
1458
+ const recordAttempt = (stage, status, summary, extra = {}) => {
1459
+ updateState(config.statePath, (state) => {
1460
+ recordStageAttempt(state, stage, {
1461
+ status,
1462
+ summary,
1463
+ checkpoint: extra.checkpoint || null,
1464
+ requestedAdvanceStage: effectiveAdvanceStage || null,
1465
+ haltedForApproval: extra.haltedForApproval,
1466
+ autoApproved: extra.autoApproved,
1467
+ error: extra.error || null,
1468
+ details: extra.details || {}
1469
+ });
1470
+ });
1471
+ };
1472
+ const checkpoint = (stage, name, summary, extra = {}) => {
1473
+ const decision = updateState(config.statePath, (state) => {
1474
+ const checkpointContract = buildCheckpointContract(state, {
1475
+ statePath: config.statePath,
1476
+ stage,
1477
+ checkpoint: name,
1478
+ summary,
1479
+ nextActions: extra.nextActions,
1480
+ advanceOptions: extra.advanceOptions,
1481
+ recommendedAdvanceStage: extra.recommendedAdvanceStage,
1482
+ continueWithStage: extra.continueWithStage,
1483
+ blocking: extra.blocking
1484
+ });
1485
+ setStageDecisionRequest(state, {
1486
+ stage,
1487
+ checkpoint: name,
1488
+ summary,
1489
+ nextActions: extra.nextActions,
1490
+ advanceOptions: extra.advanceOptions,
1491
+ recommendedAdvanceStage: extra.recommendedAdvanceStage,
1492
+ continueWithStage: extra.continueWithStage,
1493
+ blocking: extra.blocking,
1494
+ details: extra.details,
1495
+ checkpointContract
1496
+ });
1497
+ }).stage_decision_request;
1498
+ const snapshot2 = snapshotFor(config.statePath);
1499
+ return {
1500
+ ok: extra.ok ?? true,
1501
+ action,
1502
+ state_path: config.statePath,
1503
+ stage: snapshot2.stage,
1504
+ checkpoint: name,
1505
+ summary,
1506
+ state: snapshot2.state,
1507
+ decisionRequest: decision,
1508
+ checkpointContract: decision?.checkpoint_contract || null,
1509
+ ...extra
1510
+ };
1511
+ };
1512
+ const primaryShipGateNextAction = (shipGate) => {
1513
+ const reasons = shipGate.reasons || [];
1514
+ if (reasons.some((reason) => reason.includes("proof_assessment"))) {
1515
+ return "resume with riddle_proof_review using decision=ready_to_ship only after the screenshots and semantic evidence visibly prove the request; otherwise choose needs_implementation or needs_richer_proof";
1516
+ }
1517
+ if (reasons.some((reason) => reason.includes("after_cdn") || reason.includes("verify_status"))) {
1518
+ return "rerun verify with stronger proof framing so after evidence is captured before shipping";
1519
+ }
1520
+ if (reasons.some((reason) => reason.includes("before_cdn") || reason.includes("prod_cdn") || reason.includes("prod_url"))) {
1521
+ return "return to recon and capture the missing required baseline before shipping";
1522
+ }
1523
+ return "inspect the ship gate details, repair the missing invariant, then resume the run";
1524
+ };
1525
+ const shipGateBlocked = (state, executed, details = {}) => {
1526
+ const shipGate = validateShipGate(state);
1527
+ const nextAction = primaryShipGateNextAction(shipGate);
1528
+ return checkpoint(
1529
+ "verify",
1530
+ "ship_gate_blocked",
1531
+ `Ship is blocked until the proof bundle satisfies the hard ship gate. Next action: ${nextAction}.`,
1532
+ {
1533
+ ok: false,
1534
+ nextActions: ["inspect_ship_gate", "advance_run_to_verify", "supply_proof_assessment_json", "return_to_recon_if_baseline_is_missing"],
1535
+ advanceOptions: ["verify", "author", "implement", "recon"],
1536
+ recommendedAdvanceStage: "verify",
1537
+ continueWithStage: "verify",
1538
+ blocking: true,
1539
+ details: { ...details, shipGate, next_action: nextAction, executed },
1540
+ nextAction,
1541
+ shipGate,
1542
+ verifyStatus: state?.verify_status || null,
1543
+ mergeRecommendation: state?.merge_recommendation || null,
1544
+ afterCdn: state?.after_cdn || null,
1545
+ proofAssessment: state?.proof_assessment || null,
1546
+ proofAssessmentRequest: state?.proof_assessment_request || null,
1547
+ executed
1548
+ }
1549
+ );
1550
+ };
1551
+ const failedRun = (stage, summary, res, extra = {}) => {
1552
+ recordAttempt(stage, res?.haltedForApproval ? "approval_required" : "failed", summary, {
1553
+ checkpoint: extra.checkpoint || null,
1554
+ haltedForApproval: res?.haltedForApproval || false,
1555
+ autoApproved: res?.autoApproved || false,
1556
+ error: res?.error || null,
1557
+ details: extra.details
1558
+ });
1559
+ const snapshot2 = snapshotFor(config.statePath);
1560
+ return {
1561
+ ok: false,
1562
+ action,
1563
+ state_path: config.statePath,
1564
+ stage: snapshot2.stage,
1565
+ summary,
1566
+ state: snapshot2.state,
1567
+ approval: res?.approval || null,
1568
+ error: res?.error || null,
1569
+ checkpoint: extra.checkpoint || null,
1570
+ ...extra
1571
+ };
1572
+ };
1573
+ if (action !== "setup") {
1574
+ mergeStateFromParams(config.statePath, params);
1575
+ }
1576
+ if (action === "run") {
1577
+ const executed = [];
1578
+ let state = readState(config.statePath);
1579
+ if (!state || !state.workspace_ready || params.advance_stage === "setup") {
1580
+ const setupRes = runOne("setup");
1581
+ executed.push({ step: "setup", ok: setupRes.ok, haltedForApproval: setupRes.haltedForApproval || false, autoApproved: setupRes.autoApproved || false });
1582
+ if (!setupRes.ok || setupRes.haltedForApproval) {
1583
+ return failedRun("setup", setupRes.haltedForApproval ? "setup halted for approval" : "setup failed", setupRes, {
1584
+ checkpoint: "setup_blocked"
1585
+ });
1586
+ }
1587
+ recordAttempt("setup", "completed", "Setup completed and state/worktrees are ready.", {
1588
+ checkpoint: params.advance_stage === "setup" ? "setup_review" : null,
1589
+ autoApproved: setupRes.autoApproved || false
1590
+ });
1591
+ state = readState(config.statePath);
1592
+ if (params.advance_stage === "setup") {
1593
+ return checkpoint(
1594
+ "setup",
1595
+ "setup_review",
1596
+ "Setup completed. Inspect the prepared workspace and explicitly advance to recon when ready.",
1597
+ {
1598
+ nextActions: ["inspect_setup_state", "advance_run_to_recon"],
1599
+ advanceOptions: ["recon", "setup"],
1600
+ recommendedAdvanceStage: "recon",
1601
+ details: { executed },
1602
+ executed
1603
+ }
1604
+ );
1605
+ }
1606
+ }
1607
+ state = readState(config.statePath);
1608
+ const continuedStage = params.continue_from_checkpoint ? checkpointContinueStage(state) : null;
1609
+ if (params.continue_from_checkpoint && !continuedStage) {
1610
+ const recommended = recommendedAdvanceStage(state);
1611
+ return checkpoint(
1612
+ state?.active_checkpoint_stage || recommended || "recon",
1613
+ "continue_unavailable",
1614
+ "This run call asked to continue from a checkpoint, but the current state has no resumable checkpoint. Inspect status or set advance_stage explicitly.",
1615
+ {
1616
+ ok: false,
1617
+ nextActions: ["inspect_state", "set_advance_stage", "resume_run"],
1618
+ advanceOptions: ["recon", "author", "implement", "verify", "ship"],
1619
+ recommendedAdvanceStage: null,
1620
+ blocking: true,
1621
+ details: {
1622
+ executed,
1623
+ activeCheckpoint: state?.active_checkpoint || null,
1624
+ suggestedAdvanceStage: recommended || null
1625
+ },
1626
+ suggestedAdvanceStage: recommended || null,
1627
+ executed
1628
+ }
1629
+ );
1630
+ }
1631
+ effectiveAdvanceStage = params.advance_stage || continuedStage || null;
1632
+ if (effectiveAdvanceStage) {
1633
+ updateState(config.statePath, (state2) => {
1634
+ clearStageDecisionRequest(state2);
1635
+ state2.last_requested_advance_stage = effectiveAdvanceStage;
1636
+ });
1637
+ state = readState(config.statePath);
1638
+ }
1639
+ let requestedStage = normalizeStageRequest(state, effectiveAdvanceStage);
1640
+ const reconCheckpointActive = ["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "") || state?.active_checkpoint === "recon_supervisor_judgment";
1641
+ if (requestedStage === "recon" && reconCheckpointActive) {
1642
+ const latestAttempt = latestReconAttempt(state);
1643
+ const latestCapturedBaselines = latestReconCapturedBaselines(state);
1644
+ const latestAssessment = reconAssessment(state);
1645
+ const reconAssessmentRequest = state?.recon_assessment_request || state?.recon_decision_request || null;
1646
+ const reconDetails = {
1647
+ executed,
1648
+ latestAttempt,
1649
+ latestCapturedBaselines,
1650
+ reconAssessmentRequest,
1651
+ reconAssessment: latestAssessment.raw
1652
+ };
1653
+ if (!hasSupervisorReconAssessment(state)) {
1654
+ return checkpoint(
1655
+ "recon",
1656
+ "recon_supervisor_judgment",
1657
+ "Recon gathered route hints, candidate paths, baseline captures, and observations. The supervising agent should now judge whether the latest baseline is trustworthy, whether recon should retry/reframe, and whether recon is done.",
1658
+ {
1659
+ nextActions: ["inspect_recon_packet", "supply_recon_assessment_json", "continue_internal_loop_with_checkpoint"],
1660
+ advanceOptions: ["recon", "author"],
1661
+ recommendedAdvanceStage: "recon",
1662
+ continueWithStage: "recon",
1663
+ blocking: false,
1664
+ details: reconDetails,
1665
+ reconAssessmentRequest,
1666
+ reconDecisionRequest: state?.recon_decision_request || null,
1667
+ executed
1668
+ }
1669
+ );
1670
+ }
1671
+ if (latestAssessment.decision === "recon_stuck" && latestAssessment.escalationTarget === "human") {
1672
+ const summary = latestAssessment.summary || "The supervising agent concluded recon is genuinely stuck and should escalate to the human.";
1673
+ recordAttempt("recon", "escalated", summary, {
1674
+ checkpoint: "recon_human_escalation",
1675
+ details: reconDetails
1676
+ });
1677
+ return checkpoint(
1678
+ "recon",
1679
+ "recon_human_escalation",
1680
+ summary,
1681
+ {
1682
+ ok: false,
1683
+ nextActions: ["inspect_recon_history", "summarize_failed_baselines", "ask_human_for_direction"],
1684
+ advanceOptions: ["recon", "author"],
1685
+ recommendedAdvanceStage: null,
1686
+ continueWithStage: null,
1687
+ blocking: true,
1688
+ details: reconDetails,
1689
+ reconAssessment: latestAssessment.raw,
1690
+ reconAssessmentRequest,
1691
+ executed
1692
+ }
1693
+ );
1694
+ }
1695
+ if ((latestAssessment.decision === "ready_for_author" || latestAssessment.continueWithStage === "author") && latestReconHasRequiredBaselines(state) && hasReconBaselineUnderstanding(state)) {
1696
+ updateState(config.statePath, (currentState) => {
1697
+ promoteLatestReconBaselines(currentState);
1698
+ currentState.recon_status = "ready_for_proof_plan";
1699
+ currentState.recon_results = currentState.recon_results || {};
1700
+ currentState.recon_results.status = "ready_for_proof_plan";
1701
+ currentState.recon_assessment_request = {};
1702
+ currentState.recon_decision_request = {};
1703
+ if ((currentState.proof_plan || "").trim() && (currentState.capture_script || "").trim()) {
1704
+ currentState.author_status = "ready";
1705
+ currentState.proof_plan_status = "ready";
1706
+ } else if (!authorReady(currentState)) {
1707
+ currentState.author_status = "needs_authoring";
1708
+ currentState.proof_plan_status = "needs_authoring";
1709
+ }
1710
+ });
1711
+ state = readState(config.statePath);
1712
+ const approvedSummary = latestAssessment.summary || "The supervising agent approved the latest recon baseline and selected the route for proof authoring.";
1713
+ if (params.advance_stage === "recon") {
1714
+ recordAttempt("recon", "completed", approvedSummary, {
1715
+ checkpoint: "recon_review",
1716
+ details: {
1717
+ ...reconDetails,
1718
+ promotedBaselines: latestReconCapturedBaselines(state)
1719
+ }
1720
+ });
1721
+ return checkpoint(
1722
+ "recon",
1723
+ "recon_review",
1724
+ approvedSummary,
1725
+ {
1726
+ nextActions: ["inspect_recon_baseline", "continue_internal_loop_with_checkpoint", "advance_run_to_author"],
1727
+ advanceOptions: ["author", "recon", "implement"],
1728
+ recommendedAdvanceStage: "author",
1729
+ continueWithStage: "author",
1730
+ blocking: false,
1731
+ details: {
1732
+ ...reconDetails,
1733
+ promotedBaselines: latestReconCapturedBaselines(state)
1734
+ },
1735
+ reconAssessment: latestAssessment.raw,
1736
+ executed
1737
+ }
1738
+ );
1739
+ }
1740
+ recordAttempt("recon", "completed", approvedSummary, {
1741
+ checkpoint: "recon_auto_continue",
1742
+ details: {
1743
+ ...reconDetails,
1744
+ promotedBaselines: latestReconCapturedBaselines(state)
1745
+ }
1746
+ });
1747
+ effectiveAdvanceStage = "author";
1748
+ updateState(config.statePath, (currentState) => {
1749
+ currentState.last_requested_advance_stage = "author";
1750
+ });
1751
+ state = readState(config.statePath);
1752
+ requestedStage = normalizeStageRequest(state, effectiveAdvanceStage);
1753
+ } else if (latestAssessment.decision === "ready_for_author") {
1754
+ const missingUnderstanding = latestReconHasRequiredBaselines(state) && !hasReconBaselineUnderstanding(state);
1755
+ return checkpoint(
1756
+ "recon",
1757
+ "recon_supervisor_judgment",
1758
+ missingUnderstanding ? "The supervising agent tried to approve recon, but did not provide a concrete baseline_understanding. The before evidence must be understood before proof authoring or code edits begin." : "The supervising agent tried to approve recon, but the latest attempt is still missing one or more required baseline screenshots. Retry recon with a better plan or declare the loop genuinely stuck.",
1759
+ {
1760
+ ok: false,
1761
+ nextActions: ["inspect_recon_packet", "refine_recon_plan", "continue_internal_loop_with_checkpoint"],
1762
+ advanceOptions: ["recon", "author"],
1763
+ recommendedAdvanceStage: "recon",
1764
+ continueWithStage: "recon",
1765
+ blocking: false,
1766
+ details: reconDetails,
1767
+ reconAssessment: latestAssessment.raw,
1768
+ reconAssessmentRequest,
1769
+ executed
1770
+ }
1771
+ );
1772
+ } else {
1773
+ updateState(config.statePath, (currentState) => {
1774
+ currentState.recon_status = "";
1775
+ currentState.recon_assessment = {};
1776
+ currentState.recon_assessment_source = null;
1777
+ currentState.recon_assessment_request = {};
1778
+ currentState.recon_decision_request = {};
1779
+ currentState.before_cdn = "";
1780
+ currentState.prod_cdn = "";
1781
+ currentState.recon_results = currentState.recon_results || {};
1782
+ currentState.recon_results.baselines = {};
1783
+ currentState.recon_results.selected_attempt = {};
1784
+ currentState.recon_results.status = "retry_requested";
1785
+ });
1786
+ state = readState(config.statePath);
1787
+ }
1788
+ }
1789
+ if (!state?.recon_results || state?.stage === "setup" || state?.stage === "preflight" || ["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "") || requestedStage === "recon") {
1790
+ const reconRes = runOne("recon");
1791
+ executed.push({ step: "recon", ok: reconRes.ok, haltedForApproval: reconRes.haltedForApproval || false, autoApproved: reconRes.autoApproved || false });
1792
+ if (!reconRes.ok || reconRes.haltedForApproval) {
1793
+ return failedRun("recon", reconRes.haltedForApproval ? "recon halted for approval" : "recon failed", reconRes, {
1794
+ checkpoint: "recon_failed",
1795
+ details: { executed },
1796
+ executed
1797
+ });
1798
+ }
1799
+ state = readState(config.statePath);
1800
+ if (["needs_agent_decision", "needs_supervisor_judgment"].includes(state?.recon_status || "")) {
1801
+ const reconAssessmentRequest = state?.recon_assessment_request || state?.recon_decision_request || null;
1802
+ const summary = "Recon gathered route hints, candidate paths, baseline captures, and observations. The supervising agent should now judge whether the latest baseline is trustworthy, whether recon should retry/reframe, and whether recon is done.";
1803
+ const reconDetails = {
1804
+ executed,
1805
+ latestAttempt: latestReconAttempt(state),
1806
+ latestCapturedBaselines: latestReconCapturedBaselines(state),
1807
+ reconAssessmentRequest
1808
+ };
1809
+ recordAttempt("recon", "checkpoint", summary, {
1810
+ autoApproved: reconRes.autoApproved || false,
1811
+ checkpoint: "recon_supervisor_judgment",
1812
+ details: reconDetails
1813
+ });
1814
+ return checkpoint(
1815
+ "recon",
1816
+ "recon_supervisor_judgment",
1817
+ summary,
1818
+ {
1819
+ nextActions: ["inspect_recon_packet", "supply_recon_assessment_json", "continue_internal_loop_with_checkpoint"],
1820
+ advanceOptions: ["recon", "author"],
1821
+ recommendedAdvanceStage: "recon",
1822
+ continueWithStage: "recon",
1823
+ blocking: false,
1824
+ details: reconDetails,
1825
+ reconAssessmentRequest,
1826
+ reconDecisionRequest: state?.recon_decision_request || null,
1827
+ executed
1828
+ }
1829
+ );
1830
+ }
1831
+ recordAttempt("recon", "completed", "Recon completed and promoted an approved baseline context.", {
1832
+ autoApproved: reconRes.autoApproved || false,
1833
+ details: { executed }
1834
+ });
1835
+ }
1836
+ state = readState(config.statePath);
1837
+ if (!authorReady(state) || effectiveAdvanceStage === "author") {
1838
+ const authorRes = runOne("author");
1839
+ executed.push({ step: "author", ok: authorRes.ok, haltedForApproval: authorRes.haltedForApproval || false, autoApproved: authorRes.autoApproved || false });
1840
+ if (!authorRes.ok || authorRes.haltedForApproval) {
1841
+ return failedRun("author", authorRes.haltedForApproval ? "author halted for approval" : "author failed", authorRes, {
1842
+ checkpoint: "author_failed",
1843
+ details: { executed },
1844
+ executed
1845
+ });
1846
+ }
1847
+ state = readState(config.statePath);
1848
+ if (!authorReady(state)) {
1849
+ recordAttempt("author", "checkpoint", "Author prepared a supervisor judgment request instead of delegating proof authoring to an internal model.", {
1850
+ autoApproved: authorRes.autoApproved || false,
1851
+ checkpoint: "author_supervisor_judgment",
1852
+ details: {
1853
+ executed,
1854
+ authorSummary: state?.author_summary || null,
1855
+ authorRequest: state?.author_request || null,
1856
+ serverPath: state?.server_path || null,
1857
+ waitForSelector: state?.wait_for_selector || null
1858
+ }
1859
+ });
1860
+ return checkpoint(
1861
+ "author",
1862
+ "author_supervisor_judgment",
1863
+ "Author distilled recon into a proof-authoring request. The supervising agent should supply the proof packet, then resume the workflow.",
1864
+ {
1865
+ nextActions: ["inspect_author_request", "supply_author_packet_json_or_proof_plan", "continue_internal_loop_with_checkpoint"],
1866
+ advanceOptions: ["author", "recon", "implement", "verify"],
1867
+ recommendedAdvanceStage: "author",
1868
+ continueWithStage: "author",
1869
+ details: {
1870
+ executed,
1871
+ authorSummary: state?.author_summary || null,
1872
+ authorRequest: state?.author_request || null,
1873
+ proofPlanDraft: state?.author_request?.fallback_defaults?.proof_plan || null,
1874
+ captureScriptDraft: state?.author_request?.fallback_defaults?.capture_script || null,
1875
+ serverPathDraft: state?.author_request?.fallback_defaults?.server_path || null,
1876
+ waitForSelectorDraft: state?.author_request?.fallback_defaults?.wait_for_selector || null
1877
+ },
1878
+ authorSummary: state?.author_summary || null,
1879
+ authorRequest: state?.author_request || null,
1880
+ proofPlanDraft: state?.author_request?.fallback_defaults?.proof_plan || null,
1881
+ captureScriptDraft: state?.author_request?.fallback_defaults?.capture_script || null,
1882
+ serverPathDraft: state?.author_request?.fallback_defaults?.server_path || null,
1883
+ waitForSelectorDraft: state?.author_request?.fallback_defaults?.wait_for_selector || null,
1884
+ executed
1885
+ }
1886
+ );
1887
+ }
1888
+ const authorNextStage = stageAfterAuthor(state);
1889
+ const explicitAuthorDebug = params.advance_stage === "author";
1890
+ recordAttempt("author", "completed", "Author applied the supervising agent's proof packet to recon observations.", {
1891
+ autoApproved: authorRes.autoApproved || false,
1892
+ checkpoint: explicitAuthorDebug ? "author_review" : "author_auto_continue",
1893
+ details: {
1894
+ executed,
1895
+ authorSummary: state?.author_summary || null,
1896
+ authorModel: state?.author_model || null,
1897
+ authorRuntimeModelHint: state?.author_runtime_model_hint || null,
1898
+ serverPath: state?.server_path || null,
1899
+ waitForSelector: state?.wait_for_selector || null
1900
+ }
1901
+ });
1902
+ if (explicitAuthorDebug) {
1903
+ return checkpoint(
1904
+ "author",
1905
+ "author_review",
1906
+ authorNextStage === "verify" ? "Author applied the supervising agent's proof packet. Because implementation is already recorded, you can continue straight into verify." : "Author applied the supervising agent's proof packet. Inspect it if needed, then continue into implement.",
1907
+ {
1908
+ nextActions: authorNextStage === "verify" ? ["inspect_proof_packet", "advance_run_to_verify", "rerun_author"] : ["inspect_proof_packet", "advance_run_to_implement", "rerun_author"],
1909
+ advanceOptions: authorNextStage === "verify" ? ["author", "verify", "recon"] : ["author", "implement", "recon"],
1910
+ recommendedAdvanceStage: authorNextStage,
1911
+ continueWithStage: authorNextStage,
1912
+ details: {
1913
+ executed,
1914
+ authorSummary: state?.author_summary || null,
1915
+ authorModel: state?.author_model || null,
1916
+ authorRuntimeModelHint: state?.author_runtime_model_hint || null,
1917
+ proofPlan: state?.proof_plan || null,
1918
+ serverPath: state?.server_path || null,
1919
+ waitForSelector: state?.wait_for_selector || null
1920
+ },
1921
+ authorSummary: state?.author_summary || null,
1922
+ authorModel: state?.author_model || null,
1923
+ authorRuntimeModelHint: state?.author_runtime_model_hint || null,
1924
+ proofPlan: state?.proof_plan || null,
1925
+ serverPath: state?.server_path || null,
1926
+ waitForSelector: state?.wait_for_selector || null,
1927
+ executed
1928
+ }
1929
+ );
1930
+ }
1931
+ effectiveAdvanceStage = authorNextStage;
1932
+ updateState(config.statePath, (currentState) => {
1933
+ currentState.last_requested_advance_stage = authorNextStage;
1934
+ });
1935
+ state = readState(config.statePath);
1936
+ }
1937
+ if (!effectiveAdvanceStage) {
1938
+ const recommended = recommendedAdvanceStage(state);
1939
+ return checkpoint(
1940
+ recommended || "implement",
1941
+ "awaiting_stage_advance",
1942
+ "Proof authoring is ready. The wrapper will not guess the next stage from here, explicitly choose whether to revisit recon/author, validate implementation, capture verify evidence, or ship.",
1943
+ {
1944
+ nextActions: ["inspect_state", "set_advance_stage", "resume_run"],
1945
+ advanceOptions: ["recon", "author", "implement", "verify", "ship"],
1946
+ recommendedAdvanceStage: recommended,
1947
+ details: { executed },
1948
+ executed
1949
+ }
1950
+ );
1951
+ }
1952
+ if (effectiveAdvanceStage === "implement") {
1953
+ const implementRes = runOne("implement");
1954
+ executed.push({ step: "implement", ok: implementRes.ok, haltedForApproval: implementRes.haltedForApproval || false, autoApproved: implementRes.autoApproved || false });
1955
+ if (implementRes.haltedForApproval) {
1956
+ return failedRun("implement", "implement halted for approval", implementRes, {
1957
+ checkpoint: "implement_blocked",
1958
+ details: { executed },
1959
+ executed
1960
+ });
1961
+ }
1962
+ if (!implementRes.ok) {
1963
+ const implementError = `${implementRes.error || ""}
1964
+ ${implementRes.stdout || ""}
1965
+ ${implementRes.stderr || ""}`;
1966
+ if (implementError.includes("No implementation detected")) {
1967
+ recordAttempt("implement", "checkpoint", "Implementation checkpoint found no material code changes yet.", {
1968
+ checkpoint: "implement_changes_missing",
1969
+ error: implementRes.error || null,
1970
+ details: { executed }
1971
+ });
1972
+ return checkpoint(
1973
+ "implement",
1974
+ "implement_changes_missing",
1975
+ "Proof plan is ready, but code changes are not recorded yet. Make the implementation changes on the after worktree, then resume run.",
1976
+ {
1977
+ nextActions: ["make_code_changes", "rerun_implement"],
1978
+ advanceOptions: ["implement", "author", "recon"],
1979
+ recommendedAdvanceStage: "implement",
1980
+ blocking: true,
1981
+ details: { executed },
1982
+ executed
1983
+ }
1984
+ );
1985
+ }
1986
+ return failedRun("implement", "implement failed", implementRes, {
1987
+ checkpoint: "implement_failed",
1988
+ details: { executed },
1989
+ executed
1990
+ });
1991
+ }
1992
+ let invalidatedVerifyEvidence2 = false;
1993
+ updateState(config.statePath, (state2) => {
1994
+ invalidatedVerifyEvidence2 = invalidateVerifyEvidence(state2).invalidated;
1995
+ });
1996
+ recordAttempt("implement", "completed", "Implementation checkpoint recorded code changes on the after worktree.", {
1997
+ autoApproved: implementRes.autoApproved || false,
1998
+ checkpoint: "implement_review",
1999
+ details: { executed, invalidatedVerifyEvidence: invalidatedVerifyEvidence2 }
2000
+ });
2001
+ return checkpoint(
2002
+ "implement",
2003
+ "implement_review",
2004
+ invalidatedVerifyEvidence2 ? "Implementation changes were detected and prior verify evidence was invalidated. Inspect the branch diff or notes, then explicitly choose whether to iterate implementation again or advance to verify." : "Implementation changes were detected. Inspect the branch diff or notes, then explicitly choose whether to iterate implementation again or advance to verify.",
2005
+ {
2006
+ nextActions: ["inspect_branch_diff", "rerun_implement", "advance_run_to_verify"],
2007
+ advanceOptions: ["implement", "author", "verify", "recon"],
2008
+ recommendedAdvanceStage: "verify",
2009
+ details: {
2010
+ executed,
2011
+ implementationSummary: readState(config.statePath)?.implementation_summary || null,
2012
+ invalidatedVerifyEvidence: invalidatedVerifyEvidence2
2013
+ },
2014
+ implementationSummary: readState(config.statePath)?.implementation_summary || null,
2015
+ invalidatedVerifyEvidence: invalidatedVerifyEvidence2,
2016
+ executed
2017
+ }
2018
+ );
2019
+ }
2020
+ if (effectiveAdvanceStage === "verify") {
2021
+ state = readState(config.statePath);
2022
+ if (!["changes_detected", "completed"].includes(state?.implementation_status || "")) {
2023
+ return checkpoint(
2024
+ "implement",
2025
+ "implement_required",
2026
+ "Verify is blocked until implementation has been recorded. Run the implement stage after making code changes, then resume verify.",
2027
+ {
2028
+ ok: false,
2029
+ nextActions: ["make_code_changes", "advance_run_to_implement"],
2030
+ advanceOptions: ["implement", "author", "recon"],
2031
+ recommendedAdvanceStage: "implement",
2032
+ continueWithStage: "implement",
2033
+ blocking: true,
2034
+ details: { executed },
2035
+ executed
2036
+ }
2037
+ );
2038
+ }
2039
+ const hasIncomingProofAssessment = typeof params.proof_assessment_json === "string" && params.proof_assessment_json.trim().length > 0;
2040
+ const canReuseVerifyEvidence = (params.advance_stage !== "verify" || hasIncomingProofAssessment) && state?.verify_status === "evidence_captured" && Boolean((state?.after_cdn || "").trim()) && (state?.active_checkpoint === "verify_supervisor_judgment" || hasSupervisorProofAssessment(state));
2041
+ let verifyRes = { ok: true, step: "verify", reusedEvidence: canReuseVerifyEvidence };
2042
+ if (!canReuseVerifyEvidence) {
2043
+ verifyRes = runOne("verify");
2044
+ executed.push({ step: "verify", ok: verifyRes.ok, haltedForApproval: verifyRes.haltedForApproval || false, autoApproved: verifyRes.autoApproved || false });
2045
+ if (!verifyRes.ok || verifyRes.haltedForApproval) {
2046
+ return failedRun("verify", verifyRes.haltedForApproval ? "verify halted for approval" : "verify failed", verifyRes, {
2047
+ checkpoint: "verify_failed",
2048
+ details: { executed },
2049
+ executed
2050
+ });
2051
+ }
2052
+ } else {
2053
+ executed.push({ step: "verify", ok: true, reusedEvidence: true, haltedForApproval: false, autoApproved: false });
2054
+ }
2055
+ state = readState(config.statePath);
2056
+ const verifyStatus = state?.verify_status || ((state?.after_cdn || "").trim() ? "evidence_captured" : "capture_incomplete");
2057
+ const verifyDecisionRequest = state?.verify_decision_request || null;
2058
+ const verifySummary = state?.verify_summary || state?.proof_summary || null;
2059
+ const proofAssessment = verifyAssessment(state);
2060
+ const convergenceSignals = nonConvergenceSignals(state, proofAssessment);
2061
+ const verifyRecommendedStage = proofAssessment.recommendedStage || null;
2062
+ const verifyContinueWithStage = shouldEscalateVerifyToHuman(state, proofAssessment) ? null : proofAssessment.continueWithStage || verifyRecommendedStage || null;
2063
+ const verifyDetails = {
2064
+ executed,
2065
+ verifyStatus,
2066
+ verifySummary,
2067
+ afterCdn: state?.after_cdn || null,
2068
+ mergeRecommendation: state?.merge_recommendation || null,
2069
+ verifyDecisionRequest,
2070
+ proofAssessment: proofAssessment.raw,
2071
+ proofAssessmentSource: proofAssessment.source || null,
2072
+ proofAssessmentRequest: state?.proof_assessment_request || null,
2073
+ verifyRecommendedStage,
2074
+ verifyContinueWithStage,
2075
+ convergenceSignals
2076
+ };
2077
+ if (verifyStatus !== "evidence_captured") {
2078
+ if ((verifyContinueWithStage || verifyRecommendedStage || "author") === "author") {
2079
+ updateState(config.statePath, (currentState) => {
2080
+ currentState.author_status = "needs_authoring";
2081
+ currentState.proof_plan_status = "needs_authoring";
2082
+ currentState.supervisor_author_packet = null;
2083
+ });
2084
+ state = readState(config.statePath);
2085
+ }
2086
+ const checkpointName = "verify_capture_retry";
2087
+ const summary = "Verify ran, but the proof packet still needs internal capture-plan work before it should ship.";
2088
+ recordAttempt("verify", "checkpoint", summary, {
2089
+ autoApproved: verifyRes.autoApproved || false,
2090
+ checkpoint: checkpointName,
2091
+ details: verifyDetails
2092
+ });
2093
+ return checkpoint(
2094
+ "verify",
2095
+ checkpointName,
2096
+ summary,
2097
+ {
2098
+ ok: true,
2099
+ nextActions: ["inspect_after_capture", "continue_internal_loop_with_checkpoint", "return_to_recon_if_baseline_is_wrong"],
2100
+ advanceOptions: ["author", "verify", "implement", "recon"],
2101
+ recommendedAdvanceStage: verifyRecommendedStage || "author",
2102
+ continueWithStage: verifyContinueWithStage || "author",
2103
+ blocking: false,
2104
+ details: verifyDetails,
2105
+ verifyStatus,
2106
+ verifySummary,
2107
+ afterCdn: state?.after_cdn || null,
2108
+ mergeRecommendation: state?.merge_recommendation || null,
2109
+ verifyDecisionRequest,
2110
+ proofAssessment: proofAssessment.raw,
2111
+ executed
2112
+ }
2113
+ );
2114
+ }
2115
+ if (!hasSupervisorProofAssessment(state)) {
2116
+ const summary = "Verify captured usable evidence. The supervising agent should now assess whether the proof supports ship or more internal iteration, then resume the workflow with proof_assessment_json.";
2117
+ recordAttempt("verify", "checkpoint", summary, {
2118
+ autoApproved: verifyRes.autoApproved || false,
2119
+ checkpoint: "verify_supervisor_judgment",
2120
+ details: verifyDetails
2121
+ });
2122
+ return checkpoint(
2123
+ "verify",
2124
+ "verify_supervisor_judgment",
2125
+ summary,
2126
+ {
2127
+ nextActions: ["inspect_evidence", "author_proof_assessment_json", "continue_internal_loop_with_checkpoint"],
2128
+ advanceOptions: ["verify", "author", "implement", "recon", "ship"],
2129
+ recommendedAdvanceStage: "verify",
2130
+ continueWithStage: "verify",
2131
+ blocking: false,
2132
+ details: verifyDetails,
2133
+ verifyStatus,
2134
+ verifySummary,
2135
+ afterCdn: state?.after_cdn || null,
2136
+ mergeRecommendation: state?.merge_recommendation || null,
2137
+ verifyDecisionRequest,
2138
+ proofAssessmentRequest: state?.proof_assessment_request || null,
2139
+ executed
2140
+ }
2141
+ );
2142
+ }
2143
+ const shouldEscalate = shouldEscalateVerifyToHuman(state, proofAssessment);
2144
+ if (shouldEscalate) {
2145
+ const summary = "The supervising agent concluded the workflow hit a real wall and explicitly escalated the proof loop to the human.";
2146
+ recordAttempt("verify", "escalated", summary, {
2147
+ autoApproved: verifyRes.autoApproved || false,
2148
+ checkpoint: "verify_human_escalation",
2149
+ details: verifyDetails
2150
+ });
2151
+ return checkpoint(
2152
+ "verify",
2153
+ "verify_human_escalation",
2154
+ summary,
2155
+ {
2156
+ ok: false,
2157
+ nextActions: ["inspect_retry_history", "summarize_internal_loop", "ask_human_for_direction"],
2158
+ advanceOptions: ["author", "implement", "ship", "verify", "recon"],
2159
+ recommendedAdvanceStage: null,
2160
+ continueWithStage: null,
2161
+ blocking: true,
2162
+ details: verifyDetails,
2163
+ verifyStatus,
2164
+ verifySummary,
2165
+ afterCdn: state?.after_cdn || null,
2166
+ mergeRecommendation: state?.merge_recommendation || null,
2167
+ verifyDecisionRequest,
2168
+ proofAssessment: proofAssessment.raw,
2169
+ executed
2170
+ }
2171
+ );
2172
+ }
2173
+ const shouldAutoShip = verifyContinueWithStage === "ship" && (params.ship_after_verify || params.continue_from_checkpoint || params.advance_stage !== "verify");
2174
+ if (shouldAutoShip) {
2175
+ const shipGate = validateShipGate(state);
2176
+ if (!shipGate.ok) {
2177
+ recordAttempt("verify", "checkpoint", "Verify cannot continue into ship because the hard ship gate is missing required evidence or approval.", {
2178
+ autoApproved: verifyRes.autoApproved || false,
2179
+ checkpoint: "ship_gate_blocked",
2180
+ details: { ...verifyDetails, shipGate }
2181
+ });
2182
+ return shipGateBlocked(state, executed, verifyDetails);
2183
+ }
2184
+ recordAttempt("verify", "checkpoint", "Verify captured a strong proof packet and is continuing directly into ship.", {
2185
+ autoApproved: verifyRes.autoApproved || false,
2186
+ checkpoint: "verify_then_ship",
2187
+ details: { ...verifyDetails, shipGate }
2188
+ });
2189
+ const shipRes = runOne("ship");
2190
+ executed.push({ step: "ship", ok: shipRes.ok, haltedForApproval: shipRes.haltedForApproval || false, autoApproved: shipRes.autoApproved || false });
2191
+ if (!shipRes.ok || shipRes.haltedForApproval) {
2192
+ const shipNextAction = shipRes?.error && String(shipRes.error).includes("temporary proof branch") ? "product bug: ship resolved a temporary proof branch; resolve the PR head branch before retrying ship" : "inspect the ship error, confirm the PR head branch and verified commit, then retry ship";
2193
+ return failedRun("ship", shipRes.haltedForApproval ? "ship halted for approval" : "ship failed", shipRes, {
2194
+ checkpoint: "ship_failed",
2195
+ details: { executed, next_action: shipNextAction },
2196
+ nextAction: shipNextAction,
2197
+ executed
2198
+ });
2199
+ }
2200
+ recordAttempt("ship", "completed", "Ship updated the PR and posted proof artifacts after the supervising agent judged the proof strong enough.", {
2201
+ autoApproved: shipRes.autoApproved || false,
2202
+ checkpoint: "ship_review",
2203
+ details: { executed }
2204
+ });
2205
+ const snapshot2 = snapshotFor(config.statePath);
2206
+ const summary = "The supervising agent judged the proof strong enough, so the workflow shipped automatically and left the PR as the main human review surface.";
2207
+ const finalState = readState(config.statePath);
2208
+ const shipReport = finalState?.ship_report || snapshot2.state?.ship_report || null;
2209
+ return {
2210
+ ok: true,
2211
+ action,
2212
+ state_path: config.statePath,
2213
+ stage: snapshot2.stage,
2214
+ checkpoint: "ship_review",
2215
+ summary,
2216
+ state: snapshot2.state,
2217
+ shipReport,
2218
+ checkpointContract: buildCheckpointContract(readState(config.statePath), {
2219
+ statePath: config.statePath,
2220
+ stage: "ship",
2221
+ checkpoint: "ship_review",
2222
+ summary,
2223
+ nextActions: ["inspect_pr", "rerun_ship_if_needed"],
2224
+ advanceOptions: ["ship", "verify", "author", "implement"],
2225
+ recommendedAdvanceStage: "ship"
2226
+ }),
2227
+ executed
2228
+ };
2229
+ }
2230
+ if (proofAssessment.decision === "ready_to_ship") {
2231
+ const shipGate = validateShipGate(state);
2232
+ if (!shipGate.ok) {
2233
+ recordAttempt("verify", "checkpoint", "Verify cannot mark ship ready because the hard ship gate is missing required evidence or approval.", {
2234
+ autoApproved: verifyRes.autoApproved || false,
2235
+ checkpoint: "ship_gate_blocked",
2236
+ details: { ...verifyDetails, shipGate }
2237
+ });
2238
+ return shipGateBlocked(state, executed, verifyDetails);
2239
+ }
2240
+ recordAttempt("verify", "checkpoint", "Verify captured a strong proof packet and is ready to continue into ship.", {
2241
+ autoApproved: verifyRes.autoApproved || false,
2242
+ checkpoint: "verify_ship_ready",
2243
+ details: { ...verifyDetails, shipGate }
2244
+ });
2245
+ return checkpoint(
2246
+ "verify",
2247
+ "verify_ship_ready",
2248
+ "The supervising agent judged the proof strong enough to continue into ship.",
2249
+ {
2250
+ nextActions: ["inspect_evidence", "continue_internal_loop_with_checkpoint", "advance_run_to_ship_if_you_need_manual_control"],
2251
+ advanceOptions: ["ship", "verify", "author", "implement", "recon"],
2252
+ recommendedAdvanceStage: "ship",
2253
+ continueWithStage: "ship",
2254
+ blocking: false,
2255
+ details: { ...verifyDetails, shipGate },
2256
+ shipGate,
2257
+ verifyStatus,
2258
+ verifySummary,
2259
+ afterCdn: state?.after_cdn || null,
2260
+ mergeRecommendation: state?.merge_recommendation || null,
2261
+ verifyDecisionRequest,
2262
+ proofAssessment: proofAssessment.raw,
2263
+ executed
2264
+ }
2265
+ );
2266
+ }
2267
+ if (verifyContinueWithStage === "author") {
2268
+ updateState(config.statePath, (currentState) => {
2269
+ currentState.author_status = "needs_authoring";
2270
+ currentState.proof_plan_status = "needs_authoring";
2271
+ currentState.supervisor_author_packet = null;
2272
+ });
2273
+ state = readState(config.statePath);
2274
+ }
2275
+ const unresolvedSummary = convergenceSignals.warning ? "The supervising agent kept the workflow in the internal loop, but retry history suggests it may not be converging yet. Keep iterating internally or explicitly escalate with escalation_target=human when you conclude it is genuinely stuck." : "The supervising agent judged that the workflow should keep iterating internally before it ships.";
2276
+ recordAttempt("verify", "checkpoint", unresolvedSummary, {
2277
+ autoApproved: verifyRes.autoApproved || false,
2278
+ checkpoint: "verify_agent_retry",
2279
+ details: verifyDetails
2280
+ });
2281
+ return checkpoint(
2282
+ "verify",
2283
+ "verify_agent_retry",
2284
+ unresolvedSummary,
2285
+ {
2286
+ ok: true,
2287
+ nextActions: convergenceSignals.warning ? ["inspect_retry_history", "decide_whether_to_keep_iterating_or_escalate", "continue_internal_loop_with_checkpoint"] : ["inspect_proof_assessment", "continue_internal_loop_with_checkpoint", "return_to_implement_if_fix_failed"],
2288
+ advanceOptions: ["author", "implement", "ship", "verify", "recon"],
2289
+ recommendedAdvanceStage: verifyRecommendedStage,
2290
+ continueWithStage: verifyContinueWithStage,
2291
+ blocking: false,
2292
+ details: verifyDetails,
2293
+ verifyStatus,
2294
+ verifySummary,
2295
+ afterCdn: state?.after_cdn || null,
2296
+ mergeRecommendation: state?.merge_recommendation || null,
2297
+ verifyDecisionRequest,
2298
+ proofAssessment: proofAssessment.raw,
2299
+ executed
2300
+ }
2301
+ );
2302
+ }
2303
+ if (effectiveAdvanceStage === "ship") {
2304
+ state = readState(config.statePath);
2305
+ const shipAssessment = verifyAssessment(state);
2306
+ const shipGate = validateShipGate(state);
2307
+ if (state?.verify_status !== "evidence_captured") {
2308
+ return checkpoint(
2309
+ "verify",
2310
+ "verify_required",
2311
+ "Ship is blocked until verify has captured a usable proof packet. Run verify, inspect the evidence, then explicitly advance to ship only if the proof supports success.",
2312
+ {
2313
+ ok: false,
2314
+ nextActions: ["advance_run_to_verify", "inspect_verify_state"],
2315
+ advanceOptions: ["verify", "author", "implement", "recon"],
2316
+ recommendedAdvanceStage: "verify",
2317
+ continueWithStage: "verify",
2318
+ blocking: true,
2319
+ details: {
2320
+ executed,
2321
+ shipGate,
2322
+ verifyStatus: state?.verify_status || null,
2323
+ mergeRecommendation: state?.merge_recommendation || null,
2324
+ afterCdn: state?.after_cdn || null
2325
+ },
2326
+ shipGate,
2327
+ verifyStatus: state?.verify_status || null,
2328
+ mergeRecommendation: state?.merge_recommendation || null,
2329
+ afterCdn: state?.after_cdn || null,
2330
+ executed
2331
+ }
2332
+ );
2333
+ }
2334
+ if (!hasSupervisorProofAssessment(state) || shipAssessment.decision !== "ready_to_ship") {
2335
+ return checkpoint(
2336
+ "verify",
2337
+ "verify_supervisor_judgment_required",
2338
+ "Ship is blocked until the supervising agent judges the current proof packet as ready_to_ship.",
2339
+ {
2340
+ ok: false,
2341
+ nextActions: ["inspect_evidence", "supply_proof_assessment_json", "continue_internal_loop_with_checkpoint"],
2342
+ advanceOptions: ["verify", "author", "implement", "recon", "ship"],
2343
+ recommendedAdvanceStage: "verify",
2344
+ continueWithStage: "verify",
2345
+ blocking: true,
2346
+ details: {
2347
+ executed,
2348
+ shipGate,
2349
+ verifyStatus: state?.verify_status || null,
2350
+ mergeRecommendation: state?.merge_recommendation || null,
2351
+ afterCdn: state?.after_cdn || null,
2352
+ proofAssessment: state?.proof_assessment || null,
2353
+ proofAssessmentRequest: state?.proof_assessment_request || null
2354
+ },
2355
+ shipGate,
2356
+ verifyStatus: state?.verify_status || null,
2357
+ mergeRecommendation: state?.merge_recommendation || null,
2358
+ afterCdn: state?.after_cdn || null,
2359
+ proofAssessment: state?.proof_assessment || null,
2360
+ proofAssessmentRequest: state?.proof_assessment_request || null,
2361
+ executed
2362
+ }
2363
+ );
2364
+ }
2365
+ if (!shipGate.ok) {
2366
+ return shipGateBlocked(state, executed, { shipAssessment: shipAssessment.raw });
2367
+ }
2368
+ const shipRes = runOne("ship");
2369
+ executed.push({ step: "ship", ok: shipRes.ok, haltedForApproval: shipRes.haltedForApproval || false, autoApproved: shipRes.autoApproved || false });
2370
+ if (!shipRes.ok || shipRes.haltedForApproval) {
2371
+ return failedRun("ship", shipRes.haltedForApproval ? "ship halted for approval" : "ship failed", shipRes, {
2372
+ checkpoint: "ship_failed",
2373
+ details: { executed },
2374
+ executed
2375
+ });
2376
+ }
2377
+ recordAttempt("ship", "completed", "Ship updated the PR and posted proof artifacts.", {
2378
+ autoApproved: shipRes.autoApproved || false,
2379
+ checkpoint: "ship_review",
2380
+ details: { executed }
2381
+ });
2382
+ return checkpoint(
2383
+ "ship",
2384
+ "ship_review",
2385
+ "Ship completed. Review the PR, proof comment, and cleanup results. Re-run ship if you need to refresh the PR after more changes.",
2386
+ {
2387
+ nextActions: ["inspect_pr", "rerun_ship_if_needed"],
2388
+ advanceOptions: ["ship", "verify", "author", "implement"],
2389
+ recommendedAdvanceStage: "ship",
2390
+ details: {
2391
+ executed,
2392
+ prUrl: readState(config.statePath)?.pr_url || null
2393
+ },
2394
+ prUrl: readState(config.statePath)?.pr_url || null,
2395
+ executed
2396
+ }
2397
+ );
2398
+ }
2399
+ }
2400
+ if (action === "ship") {
2401
+ const state = readState(config.statePath);
2402
+ const shipGate = validateShipGate(state);
2403
+ if (state?.verify_status !== "evidence_captured") {
2404
+ return checkpoint(
2405
+ "verify",
2406
+ "verify_required",
2407
+ "Ship is blocked until verify has captured a usable proof packet. Run verify, inspect the evidence, then ship only if the proof supports success.",
2408
+ {
2409
+ ok: false,
2410
+ nextActions: ["run_verify", "inspect_verify_state"],
2411
+ advanceOptions: ["verify", "author", "implement", "recon"],
2412
+ recommendedAdvanceStage: "verify",
2413
+ continueWithStage: "verify",
2414
+ blocking: true,
2415
+ details: { shipGate },
2416
+ shipGate,
2417
+ verifyStatus: state?.verify_status || null,
2418
+ mergeRecommendation: state?.merge_recommendation || null,
2419
+ afterCdn: state?.after_cdn || null
2420
+ }
2421
+ );
2422
+ }
2423
+ if (!hasSupervisorProofAssessment(state) || verifyAssessment(state).decision !== "ready_to_ship") {
2424
+ return checkpoint(
2425
+ "verify",
2426
+ "verify_supervisor_judgment_required",
2427
+ "Ship is blocked until the supervising agent judges the current proof packet as ready_to_ship.",
2428
+ {
2429
+ ok: false,
2430
+ nextActions: ["inspect_evidence", "supply_proof_assessment_json", "rerun_ship"],
2431
+ advanceOptions: ["verify", "author", "implement", "recon", "ship"],
2432
+ recommendedAdvanceStage: "verify",
2433
+ continueWithStage: "verify",
2434
+ blocking: true,
2435
+ details: { shipGate },
2436
+ shipGate,
2437
+ verifyStatus: state?.verify_status || null,
2438
+ mergeRecommendation: state?.merge_recommendation || null,
2439
+ afterCdn: state?.after_cdn || null,
2440
+ proofAssessment: state?.proof_assessment || null,
2441
+ proofAssessmentRequest: state?.proof_assessment_request || null
2442
+ }
2443
+ );
2444
+ }
2445
+ if (!shipGate.ok) {
2446
+ return shipGateBlocked(state, [], {});
2447
+ }
2448
+ }
2449
+ const single = runOne(action);
2450
+ if (!single.ok || single.haltedForApproval) {
2451
+ return failedRun(action, single.haltedForApproval ? `${action} halted for approval` : `${action} failed`, single, {
2452
+ checkpoint: `${action}_failed`
2453
+ });
2454
+ }
2455
+ let invalidatedVerifyEvidence = false;
2456
+ updateState(config.statePath, (state) => {
2457
+ if (action === "implement") {
2458
+ invalidatedVerifyEvidence = invalidateVerifyEvidence(state).invalidated;
2459
+ }
2460
+ clearStageDecisionRequest(state);
2461
+ });
2462
+ const singleSummary = action === "implement" && invalidatedVerifyEvidence ? "implement completed and invalidated prior verify evidence" : `${action} completed`;
2463
+ recordAttempt(action, "completed", singleSummary, {
2464
+ autoApproved: single.autoApproved || false,
2465
+ details: action === "implement" ? { invalidatedVerifyEvidence } : {}
2466
+ });
2467
+ const snapshot = snapshotFor(config.statePath);
2468
+ return {
2469
+ ok: true,
2470
+ action,
2471
+ state_path: config.statePath,
2472
+ stage: snapshot.stage,
2473
+ summary: singleSummary,
2474
+ state: snapshot.state,
2475
+ approval: null,
2476
+ autoApproved: single.autoApproved || false,
2477
+ error: null
2478
+ };
2479
+ }
2480
+ function createRiddleProofEngine(pluginConfig = {}) {
2481
+ return {
2482
+ execute(params) {
2483
+ const config = resolveConfig(pluginConfig, params);
2484
+ return executeWorkflow(params, pluginConfig, config);
2485
+ },
2486
+ status(statePath) {
2487
+ const config = resolveConfig(pluginConfig, { action: "status", state_path: statePath });
2488
+ return executeWorkflow({ action: "status", state_path: statePath }, pluginConfig, config);
2489
+ },
2490
+ resolveConfig(params = {}) {
2491
+ return resolveConfig(pluginConfig, params);
2492
+ }
2493
+ };
2494
+ }
2495
+ // Annotate the CommonJS export names for ESM import in node:
2496
+ 0 && (module.exports = {
2497
+ createRiddleProofEngine,
2498
+ executeWorkflow
2499
+ });