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