@riddledc/riddle-proof 0.5.45 → 0.5.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +17 -0
  2. package/dist/checkpoint.cjs +204 -1
  3. package/dist/checkpoint.d.cts +16 -1
  4. package/dist/checkpoint.d.ts +16 -1
  5. package/dist/checkpoint.js +4 -2
  6. package/dist/{chunk-W7VTDN4T.js → chunk-DUFDZJOF.js} +1 -0
  7. package/dist/{chunk-7S7O3NKF.js → chunk-JTNMEH57.js} +6 -1
  8. package/dist/{chunk-MRSYJMF4.js → chunk-L26NTZOU.js} +2 -2
  9. package/dist/chunk-NOBFZDZG.js +754 -0
  10. package/dist/chunk-PLSGW2GI.js +161 -0
  11. package/dist/{chunk-LXE5YUYY.js → chunk-R6SCWJCI.js} +204 -2
  12. package/dist/{chunk-CHRYLX6N.js → chunk-X3AQ2WUM.js} +128 -15
  13. package/dist/cli.cjs +6129 -0
  14. package/dist/cli.d.cts +1 -0
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +160 -0
  17. package/dist/codex-exec-agent.cjs +790 -0
  18. package/dist/codex-exec-agent.d.cts +91 -0
  19. package/dist/codex-exec-agent.d.ts +91 -0
  20. package/dist/codex-exec-agent.js +10 -0
  21. package/dist/engine-harness.cjs +740 -279
  22. package/dist/engine-harness.js +5 -4
  23. package/dist/index.cjs +1469 -247
  24. package/dist/index.d.cts +4 -2
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.js +33 -17
  27. package/dist/openclaw.js +4 -2
  28. package/dist/proof-run-engine.d.cts +3 -3
  29. package/dist/proof-run-engine.d.ts +3 -3
  30. package/dist/result.cjs +1 -0
  31. package/dist/result.js +1 -1
  32. package/dist/run-card.cjs +212 -0
  33. package/dist/run-card.d.cts +10 -0
  34. package/dist/run-card.d.ts +10 -0
  35. package/dist/run-card.js +10 -0
  36. package/dist/runner.cjs +2 -0
  37. package/dist/runner.js +5 -3
  38. package/dist/state.cjs +174 -5
  39. package/dist/state.d.cts +2 -1
  40. package/dist/state.d.ts +2 -1
  41. package/dist/state.js +4 -2
  42. package/dist/types.d.cts +63 -2
  43. package/dist/types.d.ts +63 -2
  44. package/package.json +15 -2
package/dist/index.cjs CHANGED
@@ -2761,6 +2761,7 @@ __export(index_exports, {
2761
2761
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
2762
2762
  RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION: () => RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION,
2763
2763
  RIDDLE_PROOF_PLAYABILITY_VERSION: () => RIDDLE_PROOF_PLAYABILITY_VERSION,
2764
+ RIDDLE_PROOF_RUN_CARD_VERSION: () => RIDDLE_PROOF_RUN_CARD_VERSION,
2764
2765
  RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
2765
2766
  RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION: () => RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION,
2766
2767
  RIDDLE_PROOF_VISUAL_SESSION_VERSION: () => RIDDLE_PROOF_VISUAL_SESSION_VERSION,
@@ -2774,13 +2775,17 @@ __export(index_exports, {
2774
2775
  buildAuthorCheckpointPacket: () => buildAuthorCheckpointPacket,
2775
2776
  buildCheckpointPacketForEngineResult: () => buildCheckpointPacketForEngineResult,
2776
2777
  buildProofAssessmentCheckpointPacket: () => buildProofAssessmentCheckpointPacket,
2778
+ buildStageCheckpointPacket: () => buildStageCheckpointPacket,
2777
2779
  buildVisualProofSession: () => buildVisualProofSession,
2778
2780
  checkpointResponseIdentity: () => checkpointResponseIdentity,
2779
2781
  checkpointSummaryFromState: () => checkpointSummaryFromState,
2780
2782
  compactRecord: () => compactRecord,
2781
2783
  compareVisualProofSessionFingerprint: () => compareVisualProofSessionFingerprint,
2782
2784
  createCaptureDiagnostic: () => createCaptureDiagnostic,
2785
+ createCodexExecAgentAdapter: () => createCodexExecAgentAdapter,
2786
+ createCodexExecJsonRunner: () => createCodexExecJsonRunner,
2783
2787
  createDisabledRiddleProofAgentAdapter: () => createDisabledRiddleProofAgentAdapter,
2788
+ createRiddleProofRunCard: () => createRiddleProofRunCard,
2784
2789
  createRunResult: () => createRunResult,
2785
2790
  createRunState: () => createRunState,
2786
2791
  createRunStatusSnapshot: () => createRunStatusSnapshot,
@@ -2800,6 +2805,7 @@ __export(index_exports, {
2800
2805
  readRiddleProofRunStatus: () => readRiddleProofRunStatus,
2801
2806
  recordValue: () => recordValue,
2802
2807
  redactForProofDiagnostics: () => redactForProofDiagnostics,
2808
+ runCodexExecAgentDoctor: () => runCodexExecAgentDoctor,
2803
2809
  runRiddleProof: () => runRiddleProof,
2804
2810
  runRiddleProofEngineHarness: () => runRiddleProofEngineHarness,
2805
2811
  setRunStatus: () => setRunStatus,
@@ -3018,248 +3024,18 @@ function createRunResult(input) {
3018
3024
  checkpoint_summary: state.checkpoint_summary,
3019
3025
  state_paths: state.state_paths,
3020
3026
  proof_contract: state.proof_contract,
3027
+ run_card: state.run_card,
3021
3028
  proof_session: state.proof_session,
3022
3029
  evidence_bundle: input.evidence_bundle,
3023
3030
  raw: input.raw
3024
3031
  });
3025
3032
  }
3026
3033
 
3027
- // src/state.ts
3028
- var RIDDLE_PROOF_RUN_STATE_VERSION = "riddle-proof.run-state.v1";
3029
- function timestamp() {
3030
- return (/* @__PURE__ */ new Date()).toISOString();
3031
- }
3032
- function createRunId(createdAt) {
3033
- const stamp = createdAt.replace(/\D/g, "").slice(0, 14) || "unknown";
3034
- const entropy = Math.random().toString(36).slice(2, 8) || "run";
3035
- return `rp_${stamp}_${entropy}`;
3036
- }
3037
- function elapsedMs(start, end) {
3038
- const startMs = start ? Date.parse(start) : NaN;
3039
- const endMs = end ? Date.parse(end) : NaN;
3040
- if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
3041
- return Math.max(0, endMs - startMs);
3042
- }
3043
- function normalizePrStatus2(value) {
3044
- const status = nonEmptyString(value)?.toLowerCase();
3045
- if (status === "merged") return "merged";
3046
- if (status === "open") return "open";
3047
- if (status === "closed") return "closed";
3048
- if (status === "not_found" || status === "not-found") return "not_found";
3049
- if (status === "unavailable") return "unavailable";
3050
- return status || "unknown";
3051
- }
3052
- function normalizePrLifecycleState(input, checkedAt = timestamp()) {
3053
- const value = recordValue(input);
3054
- if (!value) return void 0;
3055
- const cleanup = recordValue(value.cleanup);
3056
- const mergeCommit = nonEmptyString(value.merge_commit) || nonEmptyString(value.mergeCommit) || nonEmptyString(recordValue(value.mergeCommit)?.oid);
3057
- return compactRecord({
3058
- status: normalizePrStatus2(value.status || value.state),
3059
- pr_url: nonEmptyString(value.pr_url) || nonEmptyString(value.prUrl) || nonEmptyString(value.url),
3060
- pr_number: nonEmptyString(value.pr_number) || nonEmptyString(value.prNumber) || (typeof value.number === "number" ? String(value.number) : void 0),
3061
- repo: nonEmptyString(value.repo) || nonEmptyString(value.repository),
3062
- head_branch: nonEmptyString(value.head_branch) || nonEmptyString(value.headBranch) || nonEmptyString(value.headRefName),
3063
- base_branch: nonEmptyString(value.base_branch) || nonEmptyString(value.baseBranch) || nonEmptyString(value.baseRefName),
3064
- merge_commit: mergeCommit,
3065
- merged_at: nonEmptyString(value.merged_at) || nonEmptyString(value.mergedAt),
3066
- closed_at: nonEmptyString(value.closed_at) || nonEmptyString(value.closedAt),
3067
- checked_at: nonEmptyString(value.checked_at) || nonEmptyString(value.checkedAt) || checkedAt,
3068
- source: nonEmptyString(value.source),
3069
- next_action: nonEmptyString(value.next_action) || nonEmptyString(value.nextAction),
3070
- cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
3071
- });
3072
- }
3073
- function normalizeIntegrationContext(input, fallbackSource) {
3074
- const value = recordValue(input);
3075
- if (!value) {
3076
- return fallbackSource ? { source: fallbackSource } : void 0;
3077
- }
3078
- const metadata = recordValue(value.metadata);
3079
- return compactRecord({
3080
- source: nonEmptyString(value.source) || fallbackSource,
3081
- channel_id: nonEmptyString(value.channel_id),
3082
- thread_id: nonEmptyString(value.thread_id),
3083
- message_id: nonEmptyString(value.message_id),
3084
- source_url: nonEmptyString(value.source_url),
3085
- metadata: metadata && Object.keys(metadata).length ? metadata : void 0
3086
- });
3087
- }
3088
- function normalizeRunParams(input) {
3089
- return compactRecord({
3090
- repo: input.repo,
3091
- branch: input.branch,
3092
- change_request: input.change_request,
3093
- commit_message: input.commit_message,
3094
- prod_url: input.prod_url,
3095
- capture_script: input.capture_script,
3096
- success_criteria: input.success_criteria,
3097
- assertions: input.assertions,
3098
- verification_mode: input.verification_mode,
3099
- resume_session: input.resume_session,
3100
- target_image_url: input.target_image_url,
3101
- target_image_hash: input.target_image_hash,
3102
- viewport_matrix: input.viewport_matrix,
3103
- deterministic_setup: input.deterministic_setup,
3104
- reference: input.reference,
3105
- base_branch: input.base_branch,
3106
- before_ref: input.before_ref,
3107
- allow_static_preview_fallback: input.allow_static_preview_fallback,
3108
- context: input.context,
3109
- reviewer: input.reviewer,
3110
- mode: input.mode,
3111
- build_command: input.build_command,
3112
- build_output: input.build_output,
3113
- server_image: input.server_image,
3114
- server_command: input.server_command,
3115
- server_port: input.server_port,
3116
- server_path: input.server_path,
3117
- use_auth: input.use_auth,
3118
- auth_localStorage_json: input.auth_localStorage_json,
3119
- auth_cookies_json: input.auth_cookies_json,
3120
- auth_headers_json: input.auth_headers_json,
3121
- color_scheme: input.color_scheme,
3122
- wait_for_selector: input.wait_for_selector,
3123
- ship_mode: input.ship_mode,
3124
- leave_draft: input.leave_draft,
3125
- engine_state_path: input.engine_state_path,
3126
- harness_state_path: input.harness_state_path,
3127
- max_iterations: input.max_iterations,
3128
- auto_approve: input.auto_approve,
3129
- dry_run: input.dry_run,
3130
- integration_context: normalizeIntegrationContext(input.integration_context)
3131
- });
3132
- }
3133
- function createRunState(input) {
3134
- const createdAt = input.created_at || timestamp();
3135
- return compactRecord({
3136
- version: RIDDLE_PROOF_RUN_STATE_VERSION,
3137
- run_id: input.run_id || createRunId(createdAt),
3138
- state_path: input.state_path,
3139
- worktree_path: input.worktree_path,
3140
- branch: input.branch || input.request.branch,
3141
- current_stage: input.current_stage ?? null,
3142
- stage_started_at: input.stage_started_at ?? null,
3143
- status: input.status || "running",
3144
- created_at: createdAt,
3145
- updated_at: input.updated_at || createdAt,
3146
- request: normalizeRunParams(input.request),
3147
- iterations: input.iterations ?? 0,
3148
- last_checkpoint: input.last_checkpoint ?? null,
3149
- checkpoint_packet: input.checkpoint_packet,
3150
- checkpoint_summary: input.checkpoint_summary,
3151
- state_paths: input.state_paths,
3152
- proof_contract: input.proof_contract,
3153
- checkpoint_history: input.checkpoint_history,
3154
- events: input.events ? [...input.events] : []
3155
- });
3156
- }
3157
- function appendRunEvent(state, input) {
3158
- const event = {
3159
- ts: input.ts || timestamp(),
3160
- kind: input.kind,
3161
- checkpoint: input.checkpoint,
3162
- stage: input.stage,
3163
- summary: input.summary,
3164
- details: input.details
3165
- };
3166
- state.events.push(compactRecord({
3167
- ts: event.ts,
3168
- kind: event.kind,
3169
- checkpoint: event.checkpoint,
3170
- stage: event.stage,
3171
- summary: event.summary,
3172
- details: event.details
3173
- }));
3174
- if (input.checkpoint !== void 0) state.last_checkpoint = input.checkpoint;
3175
- if (input.stage !== void 0) {
3176
- if (state.current_stage !== input.stage) state.stage_started_at = event.ts;
3177
- state.current_stage = input.stage;
3178
- }
3179
- state.updated_at = event.ts;
3180
- return state;
3181
- }
3182
- function appendStageHeartbeat(state, input) {
3183
- const at = input.ts || timestamp();
3184
- return appendRunEvent(state, {
3185
- ts: at,
3186
- kind: "stage.heartbeat",
3187
- checkpoint: input.checkpoint || `${input.stage}_heartbeat`,
3188
- stage: input.stage,
3189
- summary: input.summary || `${input.stage} stage is active.`,
3190
- details: compactRecord({
3191
- elapsed_ms: elapsedMs(state.created_at, at),
3192
- stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
3193
- wait_reason: input.wait_reason,
3194
- blocker: input.blocker,
3195
- ...input.details
3196
- })
3197
- });
3198
- }
3199
- function createRunStatusSnapshot(state, at = timestamp()) {
3200
- const latestEvent = state.events[state.events.length - 1];
3201
- const runId = state.run_id || "unknown";
3202
- return compactRecord({
3203
- run_id: runId,
3204
- status: state.status,
3205
- is_terminal: isTerminalStatus(state.status),
3206
- monitor_should_continue: !isTerminalStatus(state.status),
3207
- current_stage: state.current_stage ?? null,
3208
- state_path: state.state_path ?? null,
3209
- worktree_path: state.worktree_path ?? null,
3210
- branch: state.branch ?? null,
3211
- pr_url: state.pr_url ?? null,
3212
- pr_branch: state.pr_branch ?? null,
3213
- pr_state: state.pr_state,
3214
- ci_status: state.ci_status,
3215
- ship_commit: state.ship_commit,
3216
- ship_remote_head: state.ship_remote_head,
3217
- merge_commit: state.merge_commit,
3218
- merged_at: state.merged_at,
3219
- proof_comment_url: state.proof_comment_url,
3220
- cleanup_report: state.cleanup_report,
3221
- iterations: state.iterations,
3222
- last_checkpoint: state.last_checkpoint ?? null,
3223
- updated_at: state.updated_at,
3224
- elapsed_ms: elapsedMs(state.created_at, at),
3225
- stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
3226
- blocker: state.blocker,
3227
- checkpoint_packet: state.checkpoint_packet,
3228
- checkpoint_summary: state.checkpoint_summary,
3229
- state_paths: state.state_paths,
3230
- proof_contract: state.proof_contract,
3231
- latest_event: latestEvent
3232
- });
3233
- }
3234
- function setRunStatus(state, status, at = timestamp()) {
3235
- state.status = status;
3236
- state.ok = status !== "blocked" && status !== "failed";
3237
- state.updated_at = at;
3238
- return state;
3239
- }
3240
- function applyPrLifecycleState(state, input, at = timestamp()) {
3241
- const prState = normalizePrLifecycleState(input, at);
3242
- if (!prState) return state;
3243
- state.pr_state = prState;
3244
- if (prState.pr_url) state.pr_url = prState.pr_url;
3245
- if (prState.head_branch) state.pr_branch = prState.head_branch;
3246
- if (prState.merge_commit) state.merge_commit = prState.merge_commit;
3247
- if (prState.merged_at) state.merged_at = prState.merged_at;
3248
- if (prState.cleanup) state.cleanup_report = prState.cleanup;
3249
- if (prState.status === "merged") {
3250
- state.finalized = true;
3251
- state.status = "completed";
3252
- state.ok = true;
3253
- }
3254
- state.updated_at = at;
3255
- return state;
3256
- }
3257
-
3258
3034
  // src/checkpoint.ts
3259
3035
  var import_node_crypto = __toESM(require("crypto"), 1);
3260
3036
  var RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION = "riddle-proof.checkpoint.v1";
3261
3037
  var RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION = "riddle-proof.checkpoint_response.v1";
3262
- function timestamp2() {
3038
+ function timestamp() {
3263
3039
  return (/* @__PURE__ */ new Date()).toISOString();
3264
3040
  }
3265
3041
  function jsonCloneRecord(value) {
@@ -3373,6 +3149,102 @@ function responseSchemaForProofAssessmentPacket() {
3373
3149
  }
3374
3150
  };
3375
3151
  }
3152
+ function responseSchemaForReconPacket() {
3153
+ return {
3154
+ type: "object",
3155
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
3156
+ additionalProperties: false,
3157
+ properties: {
3158
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
3159
+ run_id: { type: "string" },
3160
+ checkpoint: { type: "string" },
3161
+ resume_token: { type: "string" },
3162
+ decision: {
3163
+ type: "string",
3164
+ enum: ["ready_for_author", "retry_recon", "recon_stuck", "needs_recon", "blocked", "human_review"]
3165
+ },
3166
+ summary: { type: "string" },
3167
+ payload: {
3168
+ type: "object",
3169
+ description: "Optional recon assessment details such as baseline_understanding, refined_inputs, reasons, or diagnostic blocker context."
3170
+ },
3171
+ reasons: { type: "array", items: { type: "string" } },
3172
+ continue_with_stage: { type: "string", enum: ["recon", "author"] },
3173
+ source: {
3174
+ type: "object",
3175
+ properties: {
3176
+ kind: { type: "string" },
3177
+ session_id: { type: "string" },
3178
+ user_id: { type: "string" }
3179
+ }
3180
+ },
3181
+ created_at: { type: "string" }
3182
+ }
3183
+ };
3184
+ }
3185
+ function responseSchemaForImplementationPacket() {
3186
+ return {
3187
+ type: "object",
3188
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
3189
+ additionalProperties: false,
3190
+ properties: {
3191
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
3192
+ run_id: { type: "string" },
3193
+ checkpoint: { type: "string" },
3194
+ resume_token: { type: "string" },
3195
+ decision: {
3196
+ type: "string",
3197
+ enum: ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"]
3198
+ },
3199
+ summary: { type: "string" },
3200
+ payload: {
3201
+ type: "object",
3202
+ description: "Implementation details such as changed_files, tests_run, and implementation_notes. The changed worktree must contain a real git diff before verify can advance."
3203
+ },
3204
+ reasons: { type: "array", items: { type: "string" } },
3205
+ continue_with_stage: { type: "string", enum: ["implement", "verify", "author", "recon"] },
3206
+ source: {
3207
+ type: "object",
3208
+ properties: {
3209
+ kind: { type: "string" },
3210
+ session_id: { type: "string" },
3211
+ user_id: { type: "string" }
3212
+ }
3213
+ },
3214
+ created_at: { type: "string" }
3215
+ }
3216
+ };
3217
+ }
3218
+ function responseSchemaForAdvancePacket(stage) {
3219
+ return {
3220
+ type: "object",
3221
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
3222
+ additionalProperties: false,
3223
+ properties: {
3224
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
3225
+ run_id: { type: "string" },
3226
+ checkpoint: { type: "string" },
3227
+ resume_token: { type: "string" },
3228
+ decision: {
3229
+ type: "string",
3230
+ enum: ["continue_stage", "retry_stage", "needs_recon", "needs_implementation", "blocked", "human_review"]
3231
+ },
3232
+ summary: { type: "string" },
3233
+ payload: { type: "object" },
3234
+ reasons: { type: "array", items: { type: "string" } },
3235
+ continue_with_stage: { type: "string", enum: ["recon", "author", "implement", "verify", "ship", stage] },
3236
+ source: {
3237
+ type: "object",
3238
+ properties: {
3239
+ kind: { type: "string" },
3240
+ session_id: { type: "string" },
3241
+ user_id: { type: "string" }
3242
+ }
3243
+ },
3244
+ created_at: { type: "string" }
3245
+ }
3246
+ };
3247
+ }
3376
3248
  function resumeTokenFor(input) {
3377
3249
  const hash = import_node_crypto.default.createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 24);
3378
3250
  return `rpchk_${hash}`;
@@ -3400,6 +3272,106 @@ function artifactsFromState(state) {
3400
3272
  }
3401
3273
  return artifacts.slice(0, 16);
3402
3274
  }
3275
+ function stageFromCheckpoint(checkpoint) {
3276
+ if (checkpoint.startsWith("recon_")) return "recon";
3277
+ if (checkpoint.startsWith("author_")) return "author";
3278
+ if (checkpoint.startsWith("implement_")) return "implement";
3279
+ if (checkpoint.startsWith("verify_")) return "verify";
3280
+ if (checkpoint.startsWith("ship_")) return "ship";
3281
+ if (checkpoint.startsWith("pr_sync_")) return "notify";
3282
+ if (checkpoint.includes("capture")) return "prove";
3283
+ return "setup";
3284
+ }
3285
+ function allowedDecisionsForStage(stage, checkpoint) {
3286
+ if (stage === "recon") return ["ready_for_author", "retry_recon", "recon_stuck", "blocked", "human_review"];
3287
+ if (stage === "implement") return ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"];
3288
+ if (stage === "ship") return ["continue_stage", "needs_implementation", "needs_recon", "blocked", "human_review"];
3289
+ if (checkpoint === "awaiting_stage_advance") return ["continue_stage", "retry_stage", "blocked", "human_review"];
3290
+ return ["continue_stage", "needs_recon", "needs_implementation", "blocked", "human_review"];
3291
+ }
3292
+ function packetKindForStage(stage, checkpoint) {
3293
+ if (stage === "recon") return "assess_recon";
3294
+ if (stage === "implement") return "implement_change";
3295
+ if (checkpoint.includes("human")) return "human_review";
3296
+ return "advance_decision";
3297
+ }
3298
+ function responseSchemaForStage(stage, checkpoint) {
3299
+ if (stage === "recon") return responseSchemaForReconPacket();
3300
+ if (stage === "implement") return responseSchemaForImplementationPacket();
3301
+ return responseSchemaForAdvancePacket(stage);
3302
+ }
3303
+ function questionForStage(stage, checkpoint) {
3304
+ if (stage === "recon") {
3305
+ return "Assess the baseline/recon evidence. Return ready_for_author only when the baseline is trustworthy; otherwise choose retry_recon, recon_stuck, blocked, or human_review.";
3306
+ }
3307
+ if (stage === "implement") {
3308
+ return "Implement the requested change in the after worktree, leave a real git diff, then return implementation_complete with changed_files/tests_run/implementation_notes. Choose blocked or human_review if implementation cannot honestly advance.";
3309
+ }
3310
+ if (stage === "ship") {
3311
+ return "Assess whether the ship gate can continue. Return continue_stage only if proof, PR, and policy gates are satisfied; otherwise route to the appropriate earlier stage or block with a concrete reason.";
3312
+ }
3313
+ return "Choose the next Riddle Proof stage for this durable run, or block with a concrete reason if the run cannot honestly advance.";
3314
+ }
3315
+ function buildStageCheckpointPacket(input) {
3316
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "stage_checkpoint";
3317
+ const stage = nonEmptyString(input.engineResult.stage) || stageFromCheckpoint(checkpoint);
3318
+ const runId = input.runState.run_id || "unknown";
3319
+ const fullState = input.fullRiddleState || {};
3320
+ const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
3321
+ const checkpointContract = recordValue(input.engineResult.checkpointContract);
3322
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.stage_summary) || `${stage} checkpoint needs a supervising decision.`;
3323
+ const kind = packetKindForStage(stage, checkpoint);
3324
+ return {
3325
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
3326
+ run_id: runId,
3327
+ state_path: input.runState.state_path,
3328
+ stage,
3329
+ checkpoint,
3330
+ kind,
3331
+ summary,
3332
+ question: questionForStage(stage, checkpoint),
3333
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
3334
+ context: input.request.context,
3335
+ artifacts: artifactsFromState(fullState),
3336
+ state_excerpt: compactRecord({
3337
+ repo: input.request.repo || fullState.repo,
3338
+ branch: input.request.branch || fullState.branch,
3339
+ after_worktree: fullState.after_worktree || input.runState.worktree_path,
3340
+ verification_mode: input.request.verification_mode || fullState.verification_mode,
3341
+ reference: input.request.reference || fullState.reference,
3342
+ server_path: fullState.server_path,
3343
+ wait_for_selector: fullState.wait_for_selector,
3344
+ recon_status: fullState.recon_status,
3345
+ author_status: fullState.author_status,
3346
+ implementation_status: fullState.implementation_status,
3347
+ verify_status: fullState.verify_status,
3348
+ stage_decision_request: jsonCloneRecord(fullState.stage_decision_request)
3349
+ }),
3350
+ evidence_excerpt: compactRecord({
3351
+ before_cdn: fullState.before_cdn || null,
3352
+ prod_cdn: fullState.prod_cdn || null,
3353
+ after_cdn: fullState.after_cdn || null,
3354
+ recon_results: jsonCloneRecord(fullState.recon_results),
3355
+ checkpoint_contract: jsonCloneRecord(checkpointContract),
3356
+ decision_details: jsonCloneRecord(decisionDetails)
3357
+ }),
3358
+ allowed_decisions: allowedDecisionsForStage(stage, checkpoint),
3359
+ response_schema: responseSchemaForStage(stage, checkpoint),
3360
+ routing_hint: {
3361
+ suggested_role: stage === "implement" ? "builder_agent" : checkpoint.includes("human") ? "human" : "main_agent",
3362
+ visibility: input.visibility || "quiet",
3363
+ urgency: stage === "ship" ? "high" : "normal",
3364
+ can_auto_answer: input.visibility !== "manual"
3365
+ },
3366
+ resume_token: resumeTokenFor({
3367
+ runId,
3368
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
3369
+ checkpoint,
3370
+ stage
3371
+ }),
3372
+ created_at: input.created_at || timestamp()
3373
+ };
3374
+ }
3403
3375
  function buildAuthorCheckpointPacket(input) {
3404
3376
  const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "author_supervisor_judgment";
3405
3377
  const stage = "author";
@@ -3453,7 +3425,7 @@ function buildAuthorCheckpointPacket(input) {
3453
3425
  checkpoint,
3454
3426
  stage
3455
3427
  }),
3456
- created_at: input.created_at || timestamp2()
3428
+ created_at: input.created_at || timestamp()
3457
3429
  };
3458
3430
  }
3459
3431
  function visualDeltaFromState(fullState) {
@@ -3502,16 +3474,16 @@ function buildProofAssessmentCheckpointPacket(input) {
3502
3474
  const visualDelta = visualDeltaFromState(fullState);
3503
3475
  const verificationMode = nonEmptyString(input.request.verification_mode) || nonEmptyString(fullState.verification_mode) || nonEmptyString(bundle?.verification_mode) || "proof";
3504
3476
  const visualDeltaRequired = requiredSignals?.visual_delta === true || verificationModeRequiresVisualDelta(verificationMode);
3505
- const evidenceIssueCode = visualDeltaIssueCode(visualDelta, visualDeltaRequired);
3477
+ const evidenceIssueCode2 = visualDeltaIssueCode(visualDelta, visualDeltaRequired);
3506
3478
  const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.verify_summary) || "Verify captured evidence and needs a supervising proof assessment.";
3507
- const recoveryHint = evidenceIssueCode ? "Required visual_delta evidence is incomplete. Keep this same run in verify/evidence recovery with decision=revise_capture and continue_with_stage=verify unless the evidence proves an implementation or recon problem." : "Assess whether the current artifacts prove the requested change, then choose the next stage.";
3479
+ const recoveryHint = evidenceIssueCode2 ? "Required visual_delta evidence is incomplete. Keep this same run in verify/evidence recovery with decision=revise_capture and continue_with_stage=verify unless the evidence proves an implementation or recon problem." : "Assess whether the current artifacts prove the requested change, then choose the next stage.";
3508
3480
  return {
3509
3481
  version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
3510
3482
  run_id: runId,
3511
3483
  state_path: input.runState.state_path,
3512
3484
  stage,
3513
3485
  checkpoint,
3514
- kind: evidenceIssueCode ? "recover_evidence" : "assess_proof",
3486
+ kind: evidenceIssueCode2 ? "recover_evidence" : "assess_proof",
3515
3487
  summary,
3516
3488
  question: `Assess the current Riddle Proof evidence. ${recoveryHint} Return a CheckpointResponse using one allowed decision.`,
3517
3489
  change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
@@ -3536,7 +3508,7 @@ function buildProofAssessmentCheckpointPacket(input) {
3536
3508
  visual_delta_required: visualDeltaRequired,
3537
3509
  visual_delta_ready: visualDelta?.status === "measured" && visualDelta?.passed === true,
3538
3510
  visual_delta: jsonCloneRecord(visualDelta),
3539
- evidence_issue_code: evidenceIssueCode,
3511
+ evidence_issue_code: evidenceIssueCode2,
3540
3512
  proof_assessment_request: jsonCloneRecord(proofAssessmentRequest),
3541
3513
  verify_decision_request: jsonCloneRecord(fullState.verify_decision_request),
3542
3514
  checkpoint_contract: jsonCloneRecord(input.engineResult.checkpointContract)
@@ -3553,9 +3525,9 @@ function buildProofAssessmentCheckpointPacket(input) {
3553
3525
  ],
3554
3526
  response_schema: responseSchemaForProofAssessmentPacket(),
3555
3527
  routing_hint: {
3556
- suggested_role: evidenceIssueCode ? "proof_judge" : "proof_judge",
3528
+ suggested_role: evidenceIssueCode2 ? "proof_judge" : "proof_judge",
3557
3529
  visibility: input.visibility || "quiet",
3558
- urgency: evidenceIssueCode ? "high" : "normal",
3530
+ urgency: evidenceIssueCode2 ? "high" : "normal",
3559
3531
  can_auto_answer: input.visibility !== "manual"
3560
3532
  },
3561
3533
  resume_token: resumeTokenFor({
@@ -3564,7 +3536,7 @@ function buildProofAssessmentCheckpointPacket(input) {
3564
3536
  checkpoint,
3565
3537
  stage
3566
3538
  }),
3567
- created_at: input.created_at || timestamp2()
3539
+ created_at: input.created_at || timestamp()
3568
3540
  };
3569
3541
  }
3570
3542
  function buildCheckpointPacketForEngineResult(input) {
@@ -3572,7 +3544,12 @@ function buildCheckpointPacketForEngineResult(input) {
3572
3544
  if (checkpoint === "verify_supervisor_judgment" || checkpoint === "verify_supervisor_judgment_required" || checkpoint === "verify_human_escalation") {
3573
3545
  return buildProofAssessmentCheckpointPacket(input);
3574
3546
  }
3575
- return buildAuthorCheckpointPacket(input);
3547
+ const resume = recordValue(input.engineResult.checkpointContract?.resume);
3548
+ const continueStage = nonEmptyString(resume?.continue_with_stage);
3549
+ if (checkpoint === "author_supervisor_judgment" || checkpoint === "verify_capture_retry" || checkpoint === "verify_agent_retry" && continueStage === "author") {
3550
+ return buildAuthorCheckpointPacket(input);
3551
+ }
3552
+ return buildStageCheckpointPacket(input);
3576
3553
  }
3577
3554
  function normalizeCheckpointResponse(value) {
3578
3555
  const record = recordValue(value);
@@ -3596,7 +3573,7 @@ function normalizeCheckpointResponse(value) {
3596
3573
  reasons: Array.isArray(record.reasons) ? record.reasons.filter((item) => typeof item === "string") : void 0,
3597
3574
  continue_with_stage: nonEmptyString(record.continue_with_stage),
3598
3575
  source: jsonCloneRecord(record.source),
3599
- created_at: nonEmptyString(record.created_at) || timestamp2()
3576
+ created_at: nonEmptyString(record.created_at) || timestamp()
3600
3577
  });
3601
3578
  }
3602
3579
  function checkpointSummaryFromState(state, engineStatePath2) {
@@ -3685,9 +3662,389 @@ function proofContractFromAuthorCheckpointResponse(response, packet, payload) {
3685
3662
  rationale: jsonCloneValue(payload.rationale),
3686
3663
  verdict_dimensions: jsonCloneRecord(payload.verdict_dimensions),
3687
3664
  payload: jsonCloneRecord(payload),
3688
- created_at: timestamp2()
3665
+ created_at: timestamp()
3666
+ });
3667
+ }
3668
+
3669
+ // src/run-card.ts
3670
+ var RIDDLE_PROOF_RUN_CARD_VERSION = "riddle-proof.run-card.v1";
3671
+ function elapsedMs(start, end) {
3672
+ const startMs = start ? Date.parse(start) : NaN;
3673
+ const endMs = end ? Date.parse(end) : NaN;
3674
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
3675
+ return Math.max(0, endMs - startMs);
3676
+ }
3677
+ function jsonCloneRecord2(value) {
3678
+ const record = recordValue(value);
3679
+ if (!record) return void 0;
3680
+ try {
3681
+ return JSON.parse(JSON.stringify(record));
3682
+ } catch {
3683
+ return { ...record };
3684
+ }
3685
+ }
3686
+ function compactText2(value, limit = 600) {
3687
+ const text = nonEmptyString(value);
3688
+ if (!text) return void 0;
3689
+ return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
3690
+ }
3691
+ function visualDeltaFrom(input) {
3692
+ const fullState = input.fullRiddleState || {};
3693
+ const bundle = recordValue(fullState.evidence_bundle);
3694
+ const after = recordValue(bundle?.after);
3695
+ const afterDelta = recordValue(after?.visual_delta);
3696
+ if (afterDelta && Object.keys(afterDelta).length) return afterDelta;
3697
+ const requestDelta = recordValue(recordValue(fullState.proof_assessment_request)?.visual_delta);
3698
+ if (requestDelta && Object.keys(requestDelta).length) return requestDelta;
3699
+ const packetDelta = recordValue(input.runState.checkpoint_packet?.evidence_excerpt?.visual_delta);
3700
+ return packetDelta && Object.keys(packetDelta).length ? packetDelta : void 0;
3701
+ }
3702
+ function artifactsFrom(input) {
3703
+ const packetArtifacts = input.runState.checkpoint_packet?.artifacts;
3704
+ if (packetArtifacts?.length) return packetArtifacts.slice(0, 12);
3705
+ const fullState = input.fullRiddleState || {};
3706
+ const artifacts = [];
3707
+ for (const role of ["before", "prod", "after"]) {
3708
+ const url = nonEmptyString(fullState[`${role}_cdn`]) || nonEmptyString(input.runState[`${role}_artifact_url`]);
3709
+ if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
3710
+ }
3711
+ return artifacts.length ? artifacts : void 0;
3712
+ }
3713
+ function ownerFor(state) {
3714
+ if (state.status === "awaiting_checkpoint") {
3715
+ const role = nonEmptyString(state.checkpoint_packet?.routing_hint?.suggested_role);
3716
+ return role || "supervising_agent";
3717
+ }
3718
+ if (state.status === "running") return "engine";
3719
+ if (state.status === "blocked" || state.status === "failed") return "human_or_operator";
3720
+ return "none";
3721
+ }
3722
+ function actionFor(state) {
3723
+ if (state.status === "awaiting_checkpoint") return state.checkpoint_packet?.question || "Answer the pending checkpoint.";
3724
+ if (state.status === "running") return "Continue the current Riddle Proof stage.";
3725
+ if (state.status === "blocked" || state.status === "failed") return state.blocker?.message || "Inspect the blocker and decide whether a new run or infrastructure repair is needed.";
3726
+ if (state.status === "ready_to_ship") return "Ship is held by policy; review PR/ship policy before advancing.";
3727
+ return "No next action; run is terminal.";
3728
+ }
3729
+ function evidenceIssueCode(input) {
3730
+ const packetIssue = nonEmptyString(input.runState.checkpoint_packet?.evidence_excerpt?.evidence_issue_code);
3731
+ if (packetIssue) return packetIssue;
3732
+ const assessmentIssue = nonEmptyString(recordValue(input.fullRiddleState?.proof_assessment)?.evidence_issue_code);
3733
+ if (assessmentIssue) return assessmentIssue;
3734
+ const delta = visualDeltaFrom(input);
3735
+ const status = nonEmptyString(delta?.status);
3736
+ if (status === "unmeasured") {
3737
+ const reason = `${nonEmptyString(delta?.reason) || ""}
3738
+ ${input.runState.blocker?.message || ""}`.toLowerCase();
3739
+ return reason.includes("fetch") || reason.includes("allowlist") || reason.includes("registered domain") || reason.includes("high risk") || reason.includes("comparator") ? "comparator_fetch_blocked" : "visual_delta_unmeasured";
3740
+ }
3741
+ if (status === "measured" && delta?.passed === false) return "semantic_proof_failed";
3742
+ return void 0;
3743
+ }
3744
+ function createRiddleProofRunCard(state, input = {}) {
3745
+ const at = input.at || (/* @__PURE__ */ new Date()).toISOString();
3746
+ const fullState = input.fullRiddleState || {};
3747
+ const packet = state.checkpoint_packet;
3748
+ const latestEvent = state.events[state.events.length - 1];
3749
+ const bundle = recordValue(fullState.evidence_bundle);
3750
+ const artifactContract = jsonCloneRecord2(packet?.artifact_contract) || jsonCloneRecord2(recordValue(fullState.proof_assessment_request)?.artifact_contract) || jsonCloneRecord2(recordValue(bundle?.artifact_contract)) || jsonCloneRecord2(state.proof_contract?.artifact_contract);
3751
+ const required = jsonCloneRecord2(recordValue(artifactContract)?.required);
3752
+ const statePaths = input.state_paths || state.state_paths || statePathsForRunState(state);
3753
+ const visualDelta = visualDeltaFrom({ fullRiddleState: fullState, runState: state });
3754
+ const artifacts = artifactsFrom({ fullRiddleState: fullState, runState: state });
3755
+ return {
3756
+ version: RIDDLE_PROOF_RUN_CARD_VERSION,
3757
+ run_id: state.run_id || "unknown",
3758
+ status: state.status,
3759
+ goal: compactRecord({
3760
+ repo: state.request.repo || nonEmptyString(fullState.repo),
3761
+ branch: state.request.branch || nonEmptyString(fullState.branch),
3762
+ change_request: state.request.change_request || nonEmptyString(fullState.change_request),
3763
+ verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
3764
+ success_criteria: state.request.success_criteria
3765
+ }),
3766
+ durable_state: compactRecord({
3767
+ ...statePaths,
3768
+ worktree_path: state.worktree_path || nonEmptyString(fullState.after_worktree) || null,
3769
+ branch: state.branch || nonEmptyString(fullState.branch) || null
3770
+ }),
3771
+ current_phase: compactRecord({
3772
+ stage: state.current_stage ?? null,
3773
+ checkpoint: state.last_checkpoint ?? packet?.checkpoint ?? null,
3774
+ latest_event: latestEvent?.kind ?? null,
3775
+ elapsed_ms: elapsedMs(state.created_at, at),
3776
+ stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
3777
+ iterations: state.iterations
3778
+ }),
3779
+ owner_next_action: compactRecord({
3780
+ owner: ownerFor(state),
3781
+ action: actionFor(state),
3782
+ checkpoint_kind: packet?.kind || null,
3783
+ allowed_decisions: packet?.allowed_decisions,
3784
+ retryable: state.status === "running" || state.status === "awaiting_checkpoint",
3785
+ reason: state.blocker?.code || packet?.summary || latestEvent?.summary || null
3786
+ }),
3787
+ evidence_contract: compactRecord({
3788
+ verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
3789
+ required,
3790
+ artifact_contract: artifactContract,
3791
+ proof_plan: compactText2(state.proof_contract?.proof_plan || fullState.proof_plan, 600),
3792
+ stop_condition: compactText2(state.proof_contract?.stop_condition, 400)
3793
+ }),
3794
+ latest_evidence: compactRecord({
3795
+ before_url: nonEmptyString(fullState.before_cdn) || state.before_artifact_url || null,
3796
+ prod_url: nonEmptyString(fullState.prod_cdn) || state.prod_artifact_url || null,
3797
+ after_url: nonEmptyString(fullState.after_cdn) || state.after_artifact_url || null,
3798
+ visual_delta: visualDelta || null,
3799
+ evidence_issue_code: evidenceIssueCode({ fullRiddleState: fullState, runState: state }) || null,
3800
+ proof_evidence_present: fullState.proof_evidence_present === true || Boolean(bundle?.proof_evidence || bundle?.proof_evidence_sample),
3801
+ artifacts
3802
+ }),
3803
+ stop_condition: compactRecord({
3804
+ status: state.status,
3805
+ terminal: isTerminalStatus(state.status),
3806
+ blocker_code: state.blocker?.code || null,
3807
+ blocker_message: state.blocker?.message || null,
3808
+ proof_decision: state.proof_decision,
3809
+ merge_recommendation: state.merge_recommendation,
3810
+ monitor_should_continue: !isTerminalStatus(state.status)
3811
+ }),
3812
+ updated_at: state.updated_at
3813
+ };
3814
+ }
3815
+
3816
+ // src/state.ts
3817
+ var RIDDLE_PROOF_RUN_STATE_VERSION = "riddle-proof.run-state.v1";
3818
+ function timestamp2() {
3819
+ return (/* @__PURE__ */ new Date()).toISOString();
3820
+ }
3821
+ function createRunId(createdAt) {
3822
+ const stamp = createdAt.replace(/\D/g, "").slice(0, 14) || "unknown";
3823
+ const entropy = Math.random().toString(36).slice(2, 8) || "run";
3824
+ return `rp_${stamp}_${entropy}`;
3825
+ }
3826
+ function elapsedMs2(start, end) {
3827
+ const startMs = start ? Date.parse(start) : NaN;
3828
+ const endMs = end ? Date.parse(end) : NaN;
3829
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
3830
+ return Math.max(0, endMs - startMs);
3831
+ }
3832
+ function normalizePrStatus2(value) {
3833
+ const status = nonEmptyString(value)?.toLowerCase();
3834
+ if (status === "merged") return "merged";
3835
+ if (status === "open") return "open";
3836
+ if (status === "closed") return "closed";
3837
+ if (status === "not_found" || status === "not-found") return "not_found";
3838
+ if (status === "unavailable") return "unavailable";
3839
+ return status || "unknown";
3840
+ }
3841
+ function normalizePrLifecycleState(input, checkedAt = timestamp2()) {
3842
+ const value = recordValue(input);
3843
+ if (!value) return void 0;
3844
+ const cleanup = recordValue(value.cleanup);
3845
+ const mergeCommit = nonEmptyString(value.merge_commit) || nonEmptyString(value.mergeCommit) || nonEmptyString(recordValue(value.mergeCommit)?.oid);
3846
+ return compactRecord({
3847
+ status: normalizePrStatus2(value.status || value.state),
3848
+ pr_url: nonEmptyString(value.pr_url) || nonEmptyString(value.prUrl) || nonEmptyString(value.url),
3849
+ pr_number: nonEmptyString(value.pr_number) || nonEmptyString(value.prNumber) || (typeof value.number === "number" ? String(value.number) : void 0),
3850
+ repo: nonEmptyString(value.repo) || nonEmptyString(value.repository),
3851
+ head_branch: nonEmptyString(value.head_branch) || nonEmptyString(value.headBranch) || nonEmptyString(value.headRefName),
3852
+ base_branch: nonEmptyString(value.base_branch) || nonEmptyString(value.baseBranch) || nonEmptyString(value.baseRefName),
3853
+ merge_commit: mergeCommit,
3854
+ merged_at: nonEmptyString(value.merged_at) || nonEmptyString(value.mergedAt),
3855
+ closed_at: nonEmptyString(value.closed_at) || nonEmptyString(value.closedAt),
3856
+ checked_at: nonEmptyString(value.checked_at) || nonEmptyString(value.checkedAt) || checkedAt,
3857
+ source: nonEmptyString(value.source),
3858
+ next_action: nonEmptyString(value.next_action) || nonEmptyString(value.nextAction),
3859
+ cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
3860
+ });
3861
+ }
3862
+ function normalizeIntegrationContext(input, fallbackSource) {
3863
+ const value = recordValue(input);
3864
+ if (!value) {
3865
+ return fallbackSource ? { source: fallbackSource } : void 0;
3866
+ }
3867
+ const metadata = recordValue(value.metadata);
3868
+ return compactRecord({
3869
+ source: nonEmptyString(value.source) || fallbackSource,
3870
+ channel_id: nonEmptyString(value.channel_id),
3871
+ thread_id: nonEmptyString(value.thread_id),
3872
+ message_id: nonEmptyString(value.message_id),
3873
+ source_url: nonEmptyString(value.source_url),
3874
+ metadata: metadata && Object.keys(metadata).length ? metadata : void 0
3875
+ });
3876
+ }
3877
+ function normalizeRunParams(input) {
3878
+ return compactRecord({
3879
+ repo: input.repo,
3880
+ branch: input.branch,
3881
+ change_request: input.change_request,
3882
+ commit_message: input.commit_message,
3883
+ prod_url: input.prod_url,
3884
+ capture_script: input.capture_script,
3885
+ success_criteria: input.success_criteria,
3886
+ assertions: input.assertions,
3887
+ verification_mode: input.verification_mode,
3888
+ resume_session: input.resume_session,
3889
+ target_image_url: input.target_image_url,
3890
+ target_image_hash: input.target_image_hash,
3891
+ viewport_matrix: input.viewport_matrix,
3892
+ deterministic_setup: input.deterministic_setup,
3893
+ reference: input.reference,
3894
+ base_branch: input.base_branch,
3895
+ before_ref: input.before_ref,
3896
+ allow_static_preview_fallback: input.allow_static_preview_fallback,
3897
+ context: input.context,
3898
+ reviewer: input.reviewer,
3899
+ mode: input.mode,
3900
+ build_command: input.build_command,
3901
+ build_output: input.build_output,
3902
+ server_image: input.server_image,
3903
+ server_command: input.server_command,
3904
+ server_port: input.server_port,
3905
+ server_path: input.server_path,
3906
+ use_auth: input.use_auth,
3907
+ auth_localStorage_json: input.auth_localStorage_json,
3908
+ auth_cookies_json: input.auth_cookies_json,
3909
+ auth_headers_json: input.auth_headers_json,
3910
+ color_scheme: input.color_scheme,
3911
+ wait_for_selector: input.wait_for_selector,
3912
+ ship_mode: input.ship_mode,
3913
+ leave_draft: input.leave_draft,
3914
+ engine_state_path: input.engine_state_path,
3915
+ harness_state_path: input.harness_state_path,
3916
+ max_iterations: input.max_iterations,
3917
+ auto_approve: input.auto_approve,
3918
+ dry_run: input.dry_run,
3919
+ integration_context: normalizeIntegrationContext(input.integration_context)
3920
+ });
3921
+ }
3922
+ function createRunState(input) {
3923
+ const createdAt = input.created_at || timestamp2();
3924
+ return compactRecord({
3925
+ version: RIDDLE_PROOF_RUN_STATE_VERSION,
3926
+ run_id: input.run_id || createRunId(createdAt),
3927
+ state_path: input.state_path,
3928
+ worktree_path: input.worktree_path,
3929
+ branch: input.branch || input.request.branch,
3930
+ current_stage: input.current_stage ?? null,
3931
+ stage_started_at: input.stage_started_at ?? null,
3932
+ status: input.status || "running",
3933
+ created_at: createdAt,
3934
+ updated_at: input.updated_at || createdAt,
3935
+ request: normalizeRunParams(input.request),
3936
+ iterations: input.iterations ?? 0,
3937
+ last_checkpoint: input.last_checkpoint ?? null,
3938
+ checkpoint_packet: input.checkpoint_packet,
3939
+ checkpoint_summary: input.checkpoint_summary,
3940
+ state_paths: input.state_paths,
3941
+ proof_contract: input.proof_contract,
3942
+ run_card: input.run_card,
3943
+ checkpoint_history: input.checkpoint_history,
3944
+ events: input.events ? [...input.events] : []
3945
+ });
3946
+ }
3947
+ function appendRunEvent(state, input) {
3948
+ const event = {
3949
+ ts: input.ts || timestamp2(),
3950
+ kind: input.kind,
3951
+ checkpoint: input.checkpoint,
3952
+ stage: input.stage,
3953
+ summary: input.summary,
3954
+ details: input.details
3955
+ };
3956
+ state.events.push(compactRecord({
3957
+ ts: event.ts,
3958
+ kind: event.kind,
3959
+ checkpoint: event.checkpoint,
3960
+ stage: event.stage,
3961
+ summary: event.summary,
3962
+ details: event.details
3963
+ }));
3964
+ if (input.checkpoint !== void 0) state.last_checkpoint = input.checkpoint;
3965
+ if (input.stage !== void 0) {
3966
+ if (state.current_stage !== input.stage) state.stage_started_at = event.ts;
3967
+ state.current_stage = input.stage;
3968
+ }
3969
+ state.updated_at = event.ts;
3970
+ return state;
3971
+ }
3972
+ function appendStageHeartbeat(state, input) {
3973
+ const at = input.ts || timestamp2();
3974
+ return appendRunEvent(state, {
3975
+ ts: at,
3976
+ kind: "stage.heartbeat",
3977
+ checkpoint: input.checkpoint || `${input.stage}_heartbeat`,
3978
+ stage: input.stage,
3979
+ summary: input.summary || `${input.stage} stage is active.`,
3980
+ details: compactRecord({
3981
+ elapsed_ms: elapsedMs2(state.created_at, at),
3982
+ stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
3983
+ wait_reason: input.wait_reason,
3984
+ blocker: input.blocker,
3985
+ ...input.details
3986
+ })
3987
+ });
3988
+ }
3989
+ function createRunStatusSnapshot(state, at = timestamp2()) {
3990
+ const latestEvent = state.events[state.events.length - 1];
3991
+ const runId = state.run_id || "unknown";
3992
+ return compactRecord({
3993
+ run_id: runId,
3994
+ status: state.status,
3995
+ is_terminal: isTerminalStatus(state.status),
3996
+ monitor_should_continue: !isTerminalStatus(state.status),
3997
+ current_stage: state.current_stage ?? null,
3998
+ state_path: state.state_path ?? null,
3999
+ worktree_path: state.worktree_path ?? null,
4000
+ branch: state.branch ?? null,
4001
+ pr_url: state.pr_url ?? null,
4002
+ pr_branch: state.pr_branch ?? null,
4003
+ pr_state: state.pr_state,
4004
+ ci_status: state.ci_status,
4005
+ ship_commit: state.ship_commit,
4006
+ ship_remote_head: state.ship_remote_head,
4007
+ merge_commit: state.merge_commit,
4008
+ merged_at: state.merged_at,
4009
+ proof_comment_url: state.proof_comment_url,
4010
+ cleanup_report: state.cleanup_report,
4011
+ iterations: state.iterations,
4012
+ last_checkpoint: state.last_checkpoint ?? null,
4013
+ updated_at: state.updated_at,
4014
+ elapsed_ms: elapsedMs2(state.created_at, at),
4015
+ stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
4016
+ blocker: state.blocker,
4017
+ checkpoint_packet: state.checkpoint_packet,
4018
+ checkpoint_summary: state.checkpoint_summary,
4019
+ state_paths: state.state_paths,
4020
+ proof_contract: state.proof_contract,
4021
+ run_card: createRiddleProofRunCard(state, { at }),
4022
+ latest_event: latestEvent
3689
4023
  });
3690
4024
  }
4025
+ function setRunStatus(state, status, at = timestamp2()) {
4026
+ state.status = status;
4027
+ state.ok = status !== "blocked" && status !== "failed";
4028
+ state.updated_at = at;
4029
+ return state;
4030
+ }
4031
+ function applyPrLifecycleState(state, input, at = timestamp2()) {
4032
+ const prState = normalizePrLifecycleState(input, at);
4033
+ if (!prState) return state;
4034
+ state.pr_state = prState;
4035
+ if (prState.pr_url) state.pr_url = prState.pr_url;
4036
+ if (prState.head_branch) state.pr_branch = prState.head_branch;
4037
+ if (prState.merge_commit) state.merge_commit = prState.merge_commit;
4038
+ if (prState.merged_at) state.merged_at = prState.merged_at;
4039
+ if (prState.cleanup) state.cleanup_report = prState.cleanup;
4040
+ if (prState.status === "merged") {
4041
+ state.finalized = true;
4042
+ state.status = "completed";
4043
+ state.ok = true;
4044
+ }
4045
+ state.updated_at = at;
4046
+ return state;
4047
+ }
3691
4048
 
3692
4049
  // src/runner.ts
3693
4050
  function errorDetails(error) {
@@ -4252,6 +4609,10 @@ function shouldPreserveFinalizedRunState(filePath, incoming) {
4252
4609
  function persist(state) {
4253
4610
  state.state_paths = statePathsForRunState(state);
4254
4611
  state.checkpoint_summary = checkpointSummaryFromState(state);
4612
+ state.run_card = createRiddleProofRunCard(state, {
4613
+ fullRiddleState: readJson(state.request.engine_state_path),
4614
+ state_paths: state.state_paths
4615
+ });
4255
4616
  if (!state.state_path) return;
4256
4617
  if (shouldPreserveFinalizedRunState(state.state_path, state)) return;
4257
4618
  writeJson(state.state_path, state);
@@ -4331,7 +4692,7 @@ function removeEmptyToolArtifacts(workdir) {
4331
4692
  }
4332
4693
  return [];
4333
4694
  }
4334
- function stageFromCheckpoint(result) {
4695
+ function stageFromCheckpoint2(result) {
4335
4696
  const explicitStage = nonEmptyString(result.stage);
4336
4697
  if (explicitStage) return explicitStage;
4337
4698
  const checkpoint = String(result.checkpoint || "");
@@ -4476,6 +4837,41 @@ function proofAssessmentPayloadFromCheckpointResponse(response) {
4476
4837
  checkpoint_response_created_at: response.created_at
4477
4838
  });
4478
4839
  }
4840
+ function reconAssessmentPayloadFromCheckpointResponse(response) {
4841
+ if (![
4842
+ "ready_for_author",
4843
+ "retry_recon",
4844
+ "recon_stuck",
4845
+ "needs_recon"
4846
+ ].includes(response.decision)) {
4847
+ return null;
4848
+ }
4849
+ const payload = recordValue(response.payload) || {};
4850
+ const decision = response.decision === "needs_recon" ? "retry_recon" : response.decision;
4851
+ const continueStage = response.continue_with_stage || nonEmptyString(payload.continue_with_stage) || (decision === "ready_for_author" ? "author" : "recon");
4852
+ return compactRecord({
4853
+ ...payload,
4854
+ decision,
4855
+ summary: response.summary,
4856
+ continue_with_stage: continueStage,
4857
+ escalation_target: nonEmptyString(payload.escalation_target) || (decision === "recon_stuck" ? "human" : "agent"),
4858
+ reasons: Array.isArray(response.reasons) ? response.reasons : Array.isArray(payload.reasons) ? payload.reasons : [],
4859
+ source: "supervising_agent",
4860
+ checkpoint_response_source: response.source || null,
4861
+ checkpoint_response_created_at: response.created_at
4862
+ });
4863
+ }
4864
+ function implementationNotesFromCheckpointResponse(response) {
4865
+ const payload = recordValue(response.payload) || {};
4866
+ const notes = nonEmptyString(payload.implementation_notes) || nonEmptyString(payload.implementationNotes) || nonEmptyString(payload.summary) || response.summary;
4867
+ const changedFiles = Array.isArray(payload.changed_files) ? payload.changed_files.filter((item) => typeof item === "string") : [];
4868
+ const testsRun = Array.isArray(payload.tests_run) ? payload.tests_run.filter((item) => typeof item === "string") : [];
4869
+ return [
4870
+ notes,
4871
+ changedFiles.length ? `changed_files=${changedFiles.join(", ")}` : "",
4872
+ testsRun.length ? `tests_run=${testsRun.join(", ")}` : ""
4873
+ ].filter(Boolean).join("\n");
4874
+ }
4479
4875
  function proofAssessmentVisualBlocker(state, payload) {
4480
4876
  if (!proofAssessmentRequestsShip(payload)) return null;
4481
4877
  const source = nonEmptyString(payload.source) || "supervising_agent";
@@ -4564,7 +4960,7 @@ function engineFailureBlocker(result, checkpoint) {
4564
4960
  }
4565
4961
  function terminalResult(state, status, result, summary, raw = {}) {
4566
4962
  if (result) {
4567
- const terminalStage = stageFromCheckpoint(result);
4963
+ const terminalStage = stageFromCheckpoint2(result);
4568
4964
  if (terminalStage !== "setup") state.current_stage = terminalStage;
4569
4965
  }
4570
4966
  setRunStatus(state, status);
@@ -4590,7 +4986,7 @@ function terminalResult(state, status, result, summary, raw = {}) {
4590
4986
  function blockerResult(state, result, blocker) {
4591
4987
  state.blocker = blocker;
4592
4988
  const blockerStage = nonEmptyString(recordValue(blocker.details)?.stage);
4593
- const stage = blockerStage || stageFromCheckpoint(result || { checkpoint: blocker.checkpoint || void 0 });
4989
+ const stage = blockerStage || stageFromCheckpoint2(result || { checkpoint: blocker.checkpoint || void 0 });
4594
4990
  recordEvent(state, {
4595
4991
  kind: "run.blocked",
4596
4992
  checkpoint: blocker.checkpoint || result?.checkpoint || null,
@@ -4777,6 +5173,67 @@ function checkpointResponseContinuation(state, value) {
4777
5173
  appendCheckpointResponse(state, response);
4778
5174
  return { next: { ...base, author_packet_json: jsonParam(payload) } };
4779
5175
  }
5176
+ if (packet.kind === "assess_recon" || packet.stage === "recon") {
5177
+ const assessment = reconAssessmentPayloadFromCheckpointResponse(response);
5178
+ if (assessment) {
5179
+ appendCheckpointResponse(state, response);
5180
+ return { next: { ...base, recon_assessment_json: jsonParam(assessment) } };
5181
+ }
5182
+ if (response.decision === "blocked" || response.decision === "human_review") {
5183
+ appendCheckpointResponse(state, response, { clear_packet: false });
5184
+ return {
5185
+ blocker: {
5186
+ code: `checkpoint_response_${response.decision}`,
5187
+ checkpoint: packet.checkpoint,
5188
+ message: response.summary || `Checkpoint response stopped recon with decision=${response.decision}.`,
5189
+ details: { stage: packet.stage, response }
5190
+ }
5191
+ };
5192
+ }
5193
+ }
5194
+ if (packet.kind === "implement_change" || packet.stage === "implement") {
5195
+ if (response.decision === "implementation_complete") {
5196
+ const workdir = nonEmptyString(packet.state_excerpt?.after_worktree) || state.worktree_path;
5197
+ if (workdir) state.worktree_path = workdir;
5198
+ if (!hasGitDiff(workdir)) {
5199
+ return {
5200
+ blocker: {
5201
+ code: "implementation_diff_missing",
5202
+ checkpoint: packet.checkpoint,
5203
+ message: "Checkpoint response claimed implementation_complete, but the after worktree has no detectable git diff.",
5204
+ details: { stage: packet.stage, worktree_path: workdir || null, response }
5205
+ }
5206
+ };
5207
+ }
5208
+ appendCheckpointResponse(state, response);
5209
+ return {
5210
+ next: {
5211
+ ...base,
5212
+ advance_stage: "implement",
5213
+ implementation_notes: implementationNotesFromCheckpointResponse(response)
5214
+ }
5215
+ };
5216
+ }
5217
+ if (response.decision === "needs_author") {
5218
+ appendCheckpointResponse(state, response);
5219
+ return { next: { ...base, advance_stage: "author" } };
5220
+ }
5221
+ if (response.decision === "needs_recon") {
5222
+ appendCheckpointResponse(state, response);
5223
+ return { next: { ...base, advance_stage: "recon" } };
5224
+ }
5225
+ if (response.decision === "blocked" || response.decision === "human_review") {
5226
+ appendCheckpointResponse(state, response, { clear_packet: false });
5227
+ return {
5228
+ blocker: {
5229
+ code: `checkpoint_response_${response.decision}`,
5230
+ checkpoint: packet.checkpoint,
5231
+ message: response.summary || `Checkpoint response stopped implementation with decision=${response.decision}.`,
5232
+ details: { stage: packet.stage, response }
5233
+ }
5234
+ };
5235
+ }
5236
+ }
4780
5237
  if (response.decision === "needs_recon") {
4781
5238
  appendCheckpointResponse(state, response);
4782
5239
  if (packet.kind === "assess_proof" || packet.kind === "recover_evidence" || packet.stage === "verify") {
@@ -5044,6 +5501,9 @@ async function routeCheckpoint(request, state, result, agent, input) {
5044
5501
  };
5045
5502
  }
5046
5503
  if (checkpoint === "recon_supervisor_judgment") {
5504
+ if (input.checkpoint_mode === "yield") {
5505
+ return { terminal: checkpointAwaitingResult(state, result, input.checkpoint_visibility) };
5506
+ }
5047
5507
  const assessment = await agent.assessRecon(context);
5048
5508
  const blocker = requirePayload("recon_assessment", assessment, state, result);
5049
5509
  if (blocker) return { blocker };
@@ -5079,6 +5539,13 @@ async function routeCheckpoint(request, state, result, agent, input) {
5079
5539
  };
5080
5540
  }
5081
5541
  if (checkpoint === "implement_changes_missing" || checkpoint === "implement_required" || checkpoint === "verify_agent_retry" && continueStage === "implement") {
5542
+ if (input.checkpoint_mode === "yield") {
5543
+ const fullState = context.fullRiddleState || {};
5544
+ state.worktree_path = workdirFromState(fullState) || state.worktree_path;
5545
+ state.branch = nonEmptyString(fullState.branch) || state.branch;
5546
+ persist(state);
5547
+ return { terminal: checkpointAwaitingResult(state, result, input.checkpoint_visibility) };
5548
+ }
5082
5549
  return handleImplementation(request, state, result, agent);
5083
5550
  }
5084
5551
  if (checkpoint === "implement_review") {
@@ -5291,7 +5758,7 @@ async function runRiddleProofEngineHarness(input) {
5291
5758
  const engineState = engineStatePath(result, state);
5292
5759
  if (engineState) state.request.engine_state_path = engineState;
5293
5760
  state.last_checkpoint = result.checkpoint || state.last_checkpoint || null;
5294
- const resultStage = stageFromCheckpoint(result);
5761
+ const resultStage = stageFromCheckpoint2(result);
5295
5762
  stageIterations[resultStage] = (stageIterations[resultStage] || 0) + 1;
5296
5763
  heartbeat(state, {
5297
5764
  stage: resultStage,
@@ -5358,6 +5825,755 @@ async function runRiddleProofEngineHarness(input) {
5358
5825
  });
5359
5826
  }
5360
5827
 
5828
+ // src/codex-exec-agent.ts
5829
+ var import_node_child_process3 = require("child_process");
5830
+ var import_node_fs4 = require("fs");
5831
+ var import_node_os = __toESM(require("os"), 1);
5832
+ var import_node_path4 = __toESM(require("path"), 1);
5833
+ var REFINED_INPUTS_SCHEMA = {
5834
+ type: "object",
5835
+ additionalProperties: false,
5836
+ required: ["server_path", "wait_for_selector", "reference"],
5837
+ properties: {
5838
+ server_path: { type: ["string", "null"] },
5839
+ wait_for_selector: { type: ["string", "null"] },
5840
+ reference: { enum: ["before", "prod", "both", null] }
5841
+ }
5842
+ };
5843
+ var BASELINE_UNDERSTANDING_SCHEMA = {
5844
+ type: "object",
5845
+ additionalProperties: false,
5846
+ required: [
5847
+ "reference",
5848
+ "target_route",
5849
+ "before_evidence_url",
5850
+ "visible_before_state",
5851
+ "relevant_elements",
5852
+ "requested_change",
5853
+ "proof_focus",
5854
+ "stop_condition",
5855
+ "quality_risks"
5856
+ ],
5857
+ properties: {
5858
+ reference: { type: "string", enum: ["before", "prod", "both", "unknown"] },
5859
+ target_route: { type: "string" },
5860
+ before_evidence_url: { type: "string" },
5861
+ visible_before_state: { type: "string" },
5862
+ relevant_elements: { type: "array", items: { type: "string" } },
5863
+ requested_change: { type: "string" },
5864
+ proof_focus: { type: "string" },
5865
+ stop_condition: { type: "string" },
5866
+ quality_risks: { type: "array", items: { type: "string" } }
5867
+ }
5868
+ };
5869
+ var RECON_SCHEMA = {
5870
+ type: "object",
5871
+ additionalProperties: false,
5872
+ required: [
5873
+ "decision",
5874
+ "summary",
5875
+ "baseline_understanding",
5876
+ "continue_with_stage",
5877
+ "escalation_target",
5878
+ "refined_inputs",
5879
+ "reasons",
5880
+ "source"
5881
+ ],
5882
+ properties: {
5883
+ decision: { type: "string", enum: ["retry_recon", "ready_for_author", "recon_stuck"] },
5884
+ summary: { type: "string" },
5885
+ baseline_understanding: BASELINE_UNDERSTANDING_SCHEMA,
5886
+ continue_with_stage: { type: "string", enum: ["recon", "author"] },
5887
+ escalation_target: { type: "string", enum: ["agent", "human"] },
5888
+ refined_inputs: REFINED_INPUTS_SCHEMA,
5889
+ reasons: { type: "array", items: { type: "string" } },
5890
+ source: { type: "string", enum: ["supervising_agent"] }
5891
+ }
5892
+ };
5893
+ var AUTHOR_SCHEMA = {
5894
+ type: "object",
5895
+ additionalProperties: false,
5896
+ required: [
5897
+ "proof_plan",
5898
+ "capture_script",
5899
+ "baseline_understanding_used",
5900
+ "refined_inputs",
5901
+ "rationale",
5902
+ "confidence",
5903
+ "summary"
5904
+ ],
5905
+ properties: {
5906
+ proof_plan: { type: "string" },
5907
+ capture_script: { type: "string" },
5908
+ baseline_understanding_used: BASELINE_UNDERSTANDING_SCHEMA,
5909
+ refined_inputs: REFINED_INPUTS_SCHEMA,
5910
+ rationale: { type: "array", items: { type: "string" } },
5911
+ confidence: { type: "string", enum: ["low", "medium", "high"] },
5912
+ summary: { type: "string" }
5913
+ }
5914
+ };
5915
+ var IMPLEMENT_SCHEMA = {
5916
+ type: "object",
5917
+ additionalProperties: false,
5918
+ required: ["summary", "implementation_notes", "changed_files", "tests_run", "blockers"],
5919
+ properties: {
5920
+ summary: { type: "string" },
5921
+ implementation_notes: { type: "string" },
5922
+ changed_files: { type: "array", items: { type: "string" } },
5923
+ tests_run: { type: "array", items: { type: "string" } },
5924
+ blockers: { type: "array", items: { type: "string" } }
5925
+ }
5926
+ };
5927
+ var PROOF_SCHEMA = {
5928
+ type: "object",
5929
+ additionalProperties: false,
5930
+ required: [
5931
+ "decision",
5932
+ "summary",
5933
+ "recommended_stage",
5934
+ "continue_with_stage",
5935
+ "escalation_target",
5936
+ "reasons",
5937
+ "source"
5938
+ ],
5939
+ properties: {
5940
+ decision: {
5941
+ type: "string",
5942
+ enum: [
5943
+ "ready_to_ship",
5944
+ "needs_richer_proof",
5945
+ "revise_capture",
5946
+ "needs_recon",
5947
+ "needs_implementation"
5948
+ ]
5949
+ },
5950
+ summary: { type: "string" },
5951
+ recommended_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
5952
+ continue_with_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
5953
+ escalation_target: { type: "string", enum: ["agent", "human"] },
5954
+ reasons: { type: "array", items: { type: "string" } },
5955
+ source: { type: "string", enum: ["supervising_agent"] }
5956
+ }
5957
+ };
5958
+ var PROMPT_STRING_LIMIT = 2e3;
5959
+ var PROMPT_ARRAY_LIMIT = 12;
5960
+ var PROMPT_OBJECT_KEY_LIMIT = 70;
5961
+ var PROMPT_BLOCK_LIMIT = 12e4;
5962
+ var PROMPT_KEY_PRIORITY = [
5963
+ "ok",
5964
+ "status",
5965
+ "stage",
5966
+ "checkpoint",
5967
+ "summary",
5968
+ "state_path",
5969
+ "repo",
5970
+ "branch",
5971
+ "change_request",
5972
+ "context",
5973
+ "success_criteria",
5974
+ "verification_mode",
5975
+ "reference",
5976
+ "server_path",
5977
+ "wait_for_selector",
5978
+ "before_cdn",
5979
+ "prod_cdn",
5980
+ "after_cdn",
5981
+ "before_baseline",
5982
+ "prod_baseline",
5983
+ "recon_assessment",
5984
+ "baseline_understanding",
5985
+ "supervisor_author_packet",
5986
+ "proof_plan",
5987
+ "capture_script",
5988
+ "implementation_status",
5989
+ "implementation_summary",
5990
+ "implementation_notes",
5991
+ "changed_files",
5992
+ "verify_status",
5993
+ "verify_summary",
5994
+ "proof_assessment",
5995
+ "proof_assessment_request",
5996
+ "semantic_context",
5997
+ "visual_delta",
5998
+ "proof_evidence_present",
5999
+ "proof_evidence_sample",
6000
+ "artifacts",
6001
+ "assertions",
6002
+ "checkpointContract",
6003
+ "shipGate",
6004
+ "last_error",
6005
+ "errors",
6006
+ "events"
6007
+ ];
6008
+ var PROMPT_PRIORITY_INDEX = new Map(PROMPT_KEY_PRIORITY.map((key, index) => [key, index]));
6009
+ function truncatePromptString(value, limit = PROMPT_STRING_LIMIT) {
6010
+ if (value.length <= limit) return value;
6011
+ return `${value.slice(0, limit)}
6012
+ ...[truncated ${value.length - limit} chars]`;
6013
+ }
6014
+ function compactPromptValue(value, depth = 0, key = "") {
6015
+ if (value === null || typeof value === "boolean" || typeof value === "number") return value;
6016
+ if (typeof value === "string") {
6017
+ const lowerKey = key.toLowerCase();
6018
+ const looksLikeUrl = /^https?:\/\//.test(value);
6019
+ if (!looksLikeUrl && (lowerKey.includes("base64") || lowerKey.includes("data_url") || lowerKey.includes("screenshot_blob"))) {
6020
+ return `[omitted ${value.length} chars from ${key || "large artifact"}]`;
6021
+ }
6022
+ const limit = looksLikeUrl ? 1e3 : depth <= 1 ? PROMPT_STRING_LIMIT : 1200;
6023
+ return truncatePromptString(value, limit);
6024
+ }
6025
+ if (Array.isArray(value)) {
6026
+ const lowerKey = key.toLowerCase();
6027
+ const items = lowerKey.includes("event") || lowerKey.includes("histor") || lowerKey.includes("retry") ? value.slice(-PROMPT_ARRAY_LIMIT) : value.slice(0, PROMPT_ARRAY_LIMIT);
6028
+ const compacted = items.map((item) => compactPromptValue(item, depth + 1, key));
6029
+ if (value.length > items.length) {
6030
+ const omitted = value.length - items.length;
6031
+ return lowerKey.includes("event") || lowerKey.includes("histor") || lowerKey.includes("retry") ? [{ omittedEarlierItems: omitted }, ...compacted] : [...compacted, { omittedItems: omitted }];
6032
+ }
6033
+ return compacted;
6034
+ }
6035
+ if (!value || typeof value !== "object") return String(value);
6036
+ const entries = Object.entries(value).sort(([left], [right]) => {
6037
+ const leftPriority = PROMPT_PRIORITY_INDEX.get(left) ?? 1e3;
6038
+ const rightPriority = PROMPT_PRIORITY_INDEX.get(right) ?? 1e3;
6039
+ if (leftPriority !== rightPriority) return leftPriority - rightPriority;
6040
+ return left.localeCompare(right);
6041
+ });
6042
+ const result = {};
6043
+ for (const [entryKey, entryValue] of entries.slice(0, PROMPT_OBJECT_KEY_LIMIT)) {
6044
+ result[entryKey] = compactPromptValue(entryValue, depth + 1, entryKey);
6045
+ }
6046
+ if (entries.length > PROMPT_OBJECT_KEY_LIMIT) {
6047
+ result.__omitted_keys = entries.length - PROMPT_OBJECT_KEY_LIMIT;
6048
+ }
6049
+ return result;
6050
+ }
6051
+ function jsonBlock(label, value) {
6052
+ let json = JSON.stringify(compactPromptValue(value), null, 2);
6053
+ if (json.length > PROMPT_BLOCK_LIMIT) {
6054
+ json = `${json.slice(0, PROMPT_BLOCK_LIMIT)}
6055
+ ...[truncated ${json.length - PROMPT_BLOCK_LIMIT} chars from compacted ${label}]`;
6056
+ }
6057
+ return `${label}:
6058
+ ${json}`;
6059
+ }
6060
+ function resolveWorkdir(context, fallback = "/tmp") {
6061
+ const after = typeof context.fullRiddleState?.after_worktree === "string" ? context.fullRiddleState.after_worktree.trim() : "";
6062
+ return after || fallback;
6063
+ }
6064
+ function basePrompt(context, role) {
6065
+ return [
6066
+ role,
6067
+ "",
6068
+ "You are the supervising Codex worker inside the Riddle Proof harness.",
6069
+ "Return only JSON matching the provided output schema.",
6070
+ "Do not ask the human to manually continue. If blocked, encode the blocker in the JSON fields allowed by the schema.",
6071
+ "Large raw artifacts are summarized before this prompt. Use preserved state summaries, URLs, file paths, and proof evidence samples instead of expecting full raw logs or binary artifacts inline.",
6072
+ "",
6073
+ jsonBlock("Original request", context.request),
6074
+ jsonBlock("Riddle checkpoint result", context.engineResult),
6075
+ jsonBlock("Full riddle state", context.fullRiddleState || {})
6076
+ ].join("\n");
6077
+ }
6078
+ function schemaRequiredKeys(schema) {
6079
+ const required = schema?.required;
6080
+ return Array.isArray(required) ? required.filter((key) => typeof key === "string" && key.length > 0) : [];
6081
+ }
6082
+ function isSchemaShapedObject(value, schema) {
6083
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
6084
+ const required = schemaRequiredKeys(schema);
6085
+ return required.every((key) => Object.prototype.hasOwnProperty.call(value, key));
6086
+ }
6087
+ function parseJsonCandidate(raw, schema) {
6088
+ try {
6089
+ const parsed = JSON.parse(raw);
6090
+ return isSchemaShapedObject(parsed, schema) ? parsed : null;
6091
+ } catch {
6092
+ return null;
6093
+ }
6094
+ }
6095
+ function extractJsonObjectCandidates(raw) {
6096
+ const candidates = [];
6097
+ let depth = 0;
6098
+ let start = -1;
6099
+ let inString = false;
6100
+ let escaped = false;
6101
+ for (let index = 0; index < raw.length; index += 1) {
6102
+ const char = raw[index];
6103
+ if (inString) {
6104
+ if (escaped) {
6105
+ escaped = false;
6106
+ } else if (char === "\\") {
6107
+ escaped = true;
6108
+ } else if (char === '"') {
6109
+ inString = false;
6110
+ }
6111
+ continue;
6112
+ }
6113
+ if (char === '"') {
6114
+ inString = true;
6115
+ continue;
6116
+ }
6117
+ if (char === "{") {
6118
+ if (depth === 0) start = index;
6119
+ depth += 1;
6120
+ continue;
6121
+ }
6122
+ if (char === "}" && depth > 0) {
6123
+ depth -= 1;
6124
+ if (depth === 0 && start >= 0) {
6125
+ candidates.push(raw.slice(start, index + 1));
6126
+ start = -1;
6127
+ }
6128
+ }
6129
+ }
6130
+ return candidates;
6131
+ }
6132
+ function parseJsonObject(raw, schema) {
6133
+ const trimmed = raw.trim();
6134
+ if (!trimmed) return null;
6135
+ const whole = parseJsonCandidate(trimmed, schema);
6136
+ if (whole) return whole;
6137
+ const lines = trimmed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
6138
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
6139
+ const parsed = parseJsonCandidate(lines[index], schema);
6140
+ if (parsed) return parsed;
6141
+ }
6142
+ const candidates = extractJsonObjectCandidates(trimmed);
6143
+ for (let index = candidates.length - 1; index >= 0; index -= 1) {
6144
+ const parsed = parseJsonCandidate(candidates[index], schema);
6145
+ if (parsed) return parsed;
6146
+ }
6147
+ return null;
6148
+ }
6149
+ function isHarnessVerificationOnlyBlocker(blocker) {
6150
+ const text = blocker.toLowerCase();
6151
+ return (text.includes("erofs") || text.includes("read-only file system")) && text.includes("node_modules") && (text.includes(".vite-temp") || text.includes("vite.config"));
6152
+ }
6153
+ function createCodexExecJsonRunner(config = {}) {
6154
+ return (request) => {
6155
+ if (!request.workdir || !(0, import_node_fs4.existsSync)(request.workdir)) {
6156
+ return {
6157
+ ok: false,
6158
+ blocker: {
6159
+ code: "codex_workdir_missing",
6160
+ message: `Codex workdir does not exist for ${request.purpose}.`,
6161
+ details: { workdir: request.workdir }
6162
+ }
6163
+ };
6164
+ }
6165
+ const tmpDir = (0, import_node_fs4.mkdtempSync)(import_node_path4.default.join(import_node_os.default.tmpdir(), "riddle-proof-codex-"));
6166
+ const schemaPath = import_node_path4.default.join(tmpDir, "schema.json");
6167
+ const lastMessagePath = import_node_path4.default.join(tmpDir, "last-message.json");
6168
+ (0, import_node_fs4.writeFileSync)(schemaPath, JSON.stringify(request.schema, null, 2));
6169
+ const args = [
6170
+ "exec",
6171
+ "--json",
6172
+ "--output-schema",
6173
+ schemaPath,
6174
+ "--output-last-message",
6175
+ lastMessagePath,
6176
+ "--cd",
6177
+ request.workdir,
6178
+ "--sandbox",
6179
+ config.codexSandbox || "workspace-write",
6180
+ "--skip-git-repo-check"
6181
+ ];
6182
+ if (config.codexFullAuto !== false) args.push("--full-auto");
6183
+ if (config.codexModel) args.push("-m", config.codexModel);
6184
+ args.push("-");
6185
+ const env = { ...process.env };
6186
+ if (config.codexHome) env.CODEX_HOME = config.codexHome;
6187
+ delete env.OPENAI_API_KEY;
6188
+ try {
6189
+ const proc = (0, import_node_child_process3.spawnSync)(config.codexCommand || "codex", args, {
6190
+ input: request.prompt,
6191
+ encoding: "utf-8",
6192
+ timeout: Number(config.codexTimeoutMs || 6e5),
6193
+ maxBuffer: 10 * 1024 * 1024,
6194
+ env
6195
+ });
6196
+ if (proc.error) {
6197
+ const timedOut = proc.error.code === "ETIMEDOUT";
6198
+ return {
6199
+ ok: false,
6200
+ stdout: proc.stdout || "",
6201
+ stderr: proc.stderr || "",
6202
+ blocker: {
6203
+ code: timedOut ? "codex_timeout" : "codex_exec_error",
6204
+ message: timedOut ? `Codex timed out during ${request.purpose}.` : `Codex failed to start or complete ${request.purpose}.`,
6205
+ details: { error: proc.error.message }
6206
+ }
6207
+ };
6208
+ }
6209
+ if (proc.status !== 0) {
6210
+ return {
6211
+ ok: false,
6212
+ stdout: proc.stdout || "",
6213
+ stderr: proc.stderr || "",
6214
+ blocker: {
6215
+ code: "codex_nonzero_exit",
6216
+ message: `Codex exited with status ${proc.status} during ${request.purpose}.`,
6217
+ details: { stdout: proc.stdout || "", stderr: proc.stderr || "" }
6218
+ }
6219
+ };
6220
+ }
6221
+ const finalText = (0, import_node_fs4.existsSync)(lastMessagePath) ? (0, import_node_fs4.readFileSync)(lastMessagePath, "utf-8") : String(proc.stdout || "");
6222
+ const parsed = parseJsonObject(finalText, request.schema);
6223
+ if (!parsed) {
6224
+ return {
6225
+ ok: false,
6226
+ stdout: proc.stdout || "",
6227
+ stderr: proc.stderr || "",
6228
+ blocker: {
6229
+ code: "codex_invalid_json",
6230
+ message: `Codex completed ${request.purpose}, but did not return valid JSON.`,
6231
+ details: { finalText, stdout: proc.stdout || "", stderr: proc.stderr || "" }
6232
+ }
6233
+ };
6234
+ }
6235
+ return {
6236
+ ok: true,
6237
+ json: parsed,
6238
+ stdout: proc.stdout || "",
6239
+ stderr: proc.stderr || ""
6240
+ };
6241
+ } finally {
6242
+ (0, import_node_fs4.rmSync)(tmpDir, { recursive: true, force: true });
6243
+ }
6244
+ };
6245
+ }
6246
+ async function callRunner(runner, request) {
6247
+ return runner(request);
6248
+ }
6249
+ function payloadOrBlocker(raw, checkpoint) {
6250
+ if (!raw.ok || !raw.json) {
6251
+ const blocker = raw.blocker || {
6252
+ code: "codex_runner_failed",
6253
+ message: "Codex runner failed without a detailed blocker.",
6254
+ details: { stdout: raw.stdout || "", stderr: raw.stderr || "" }
6255
+ };
6256
+ return {
6257
+ ok: false,
6258
+ blocker: {
6259
+ ...blocker,
6260
+ checkpoint
6261
+ }
6262
+ };
6263
+ }
6264
+ return {
6265
+ ok: true,
6266
+ payload: raw.json,
6267
+ summary: typeof raw.json.summary === "string" ? raw.json.summary : void 0
6268
+ };
6269
+ }
6270
+ function stringArray(value) {
6271
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
6272
+ }
6273
+ function parseGitStatusPaths2(status) {
6274
+ return status.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean).map((line) => {
6275
+ let item = line.length > 3 ? line.slice(3) : line;
6276
+ if (item.includes(" -> ")) item = item.split(" -> ").pop() || item;
6277
+ return item.trim();
6278
+ }).filter(Boolean);
6279
+ }
6280
+ function isToolNoisePath2(filePath) {
6281
+ return filePath === ".codex" || filePath.startsWith(".codex/") || filePath === ".oc-smoke" || filePath.startsWith(".oc-smoke/");
6282
+ }
6283
+ function hasGitDiff2(workdir) {
6284
+ try {
6285
+ const status = git(["status", "--porcelain"], workdir);
6286
+ return parseGitStatusPaths2(status).some((filePath) => !isToolNoisePath2(filePath));
6287
+ } catch {
6288
+ return false;
6289
+ }
6290
+ }
6291
+ function buildImplementationPrompt(context, extraLines = []) {
6292
+ return [
6293
+ basePrompt(context, "Implement the requested code change in the after worktree."),
6294
+ "Make the code changes directly in this repository.",
6295
+ "Use the recon-approved baseline understanding in the state to decide exactly what prior UI/state is being changed.",
6296
+ "Run focused checks when practical.",
6297
+ "If a focused check is blocked only by the harness sandbox writing Vite temp config into a shared/symlinked node_modules path (for example EROFS on node_modules/.vite-temp/vite.config...), do not treat that as an implementation blocker when the requested git diff exists. Record it in tests_run or implementation_notes instead so the harness can advance to its own verify stage.",
6298
+ "Leave a real git diff in the after worktree. Do not commit or push.",
6299
+ "Before you return success, run git status --short and git diff --name-only in this repository and verify they show the intended change.",
6300
+ "Do not return success with empty changed_files or a clean git status. If you cannot create the requested diff, explain why in blockers instead.",
6301
+ "changed_files should match the real git diff as closely as practical.",
6302
+ "Return changed_files, implementation_notes, tests_run, and blockers if any.",
6303
+ "Use empty arrays for tests_run or blockers when none apply.",
6304
+ ...extraLines
6305
+ ].join("\n");
6306
+ }
6307
+ function createCodexExecAgentAdapter(config = {}, runner = createCodexExecJsonRunner(config)) {
6308
+ return {
6309
+ async assessRecon(context) {
6310
+ const raw = await callRunner(runner, {
6311
+ purpose: "recon assessment",
6312
+ workdir: resolveWorkdir(context),
6313
+ schema: RECON_SCHEMA,
6314
+ prompt: [
6315
+ basePrompt(context, "Judge the latest recon packet."),
6316
+ "Decide whether recon should retry, continue to author, or escalate to the human.",
6317
+ "This is the first intelligent before-evidence gate. It runs before proof authoring and before any code edits.",
6318
+ "Prefer ready_for_author only when the baseline evidence is trustworthy for the requested change.",
6319
+ "Do not approve recon just because telemetry_ready is true or a screenshot URL exists.",
6320
+ "Inspect the baseline evidence in the state: screenshot URLs, structured pageState details, visible_text_sample, headings, buttons, links, canvas_count, large_visible_elements, observed_path, and route candidates.",
6321
+ "Fill baseline_understanding with concrete observations about what the before/prod evidence shows, what exact user request it anchors, what proof should focus on, and what stop condition would satisfy the request.",
6322
+ "If you cannot write a specific baseline_understanding from the current evidence, choose retry_recon or recon_stuck; do not choose ready_for_author.",
6323
+ "Reject blank, banner-only, app-shell-only, loading-only, generic landing, source-import path, or wrong-feature baselines; retry recon with a better server_path or selector instead.",
6324
+ "Your summary must say what is visibly present in the approved baseline or why the current baseline is not good enough.",
6325
+ "Always include refined_inputs; use null values for server_path, wait_for_selector, or reference when no refinement is needed."
6326
+ ].join("\n")
6327
+ });
6328
+ return payloadOrBlocker(raw, context.checkpoint);
6329
+ },
6330
+ async authorProofPacket(context) {
6331
+ const raw = await callRunner(runner, {
6332
+ purpose: "proof packet authoring",
6333
+ workdir: resolveWorkdir(context),
6334
+ schema: AUTHOR_SCHEMA,
6335
+ prompt: [
6336
+ basePrompt(context, "Author the proof packet."),
6337
+ "Write a proof_plan and capture_script that will verify the exact user-facing change.",
6338
+ "Use recon_assessment.baseline_understanding as the source of truth. Do not author a proof plan unless it names the observed before state and the requested delta from that state.",
6339
+ "Use the recon-approved route and baseline context; make the plan name the concrete target, expected before state, expected after state, and stop condition.",
6340
+ "Choose the evidence modality from verification_mode and success_criteria: screenshots for visual/UI proof, interactions plus screenshots for interaction proof, structured metrics/logs/JSON/audio analysis for non-visual proof.",
6341
+ "For playable/gameplay proof, treat screenshots as supporting artifacts only: start the game, send keyboard or pointer input, measure state before/after, measure non-HUD canvas/playfield pixel deltas across time, and return playability evidence with version riddle-proof.playability.v1.",
6342
+ "For structured proof, collect meaningful measurements inside page.evaluate and set window.__riddleProofEvidence in that browser page context to a JSON-serializable object. Screenshots are optional supporting context for data/audio/log/metric/custom modes.",
6343
+ "Do not assign globalThis.__riddleProofEvidence, window.__riddleProofEvidence, or self.__riddleProofEvidence outside page.evaluate; the Riddle worker context may not expose those globals safely.",
6344
+ "Do not call Playwright page.* APIs inside page.evaluate; page.evaluate runs in the browser page, while page.waitForFunction, page.waitForSelector, page.click, and saveScreenshot belong in the outer capture script.",
6345
+ "When page.evaluate needs data from the outer Playwright script, pass exactly one serializable argument object; do not pass multiple positional arguments.",
6346
+ "When setting Playwright wait timeouts, use the correct signature: await page.waitForFunction(fn, undefined, { timeout: 60000 }). Do not write page.waitForFunction(fn, { timeout: 60000 }); that passes the object as the page argument and leaves the default timeout in place.",
6347
+ "For audio/data/metric proof, return and persist the same evidence object: const evidence = await page.evaluate(async () => { /* browser measurements */ window.__riddleProofEvidence = { ... }; return window.__riddleProofEvidence; }); Then assert evidence fields before saving screenshots.",
6348
+ "If a capture attempt errors or proof_evidence is absent, revise the capture_script to make structured evidence easier to collect; do not only add more screenshots for non-visual proof.",
6349
+ "When checking visible copy, normalize text before exact matching: const normalizedText = (document.body?.innerText || '').replace(/\\s+/g, ' ').trim(); Avoid raw innerText.includes(exact sentence) because browser line wrapping can split copy.",
6350
+ "Prefer success-oriented evidence booleans such as newCopyVisible: true and oldCopyAbsent: true. If a positive assertion is false while screenshots/text samples look right, fix the capture script instead of leaving contradictory proof evidence.",
6351
+ "Include a short matchedSnippet or normalizedTextSample when proofing copy so assertion mismatches are diagnosable.",
6352
+ "For visual/UI proof, include saveScreenshot('after-proof') exactly once.",
6353
+ "Avoid generic proof language. The packet should be specific enough that verify can tell whether the requested change actually happened.",
6354
+ "Echo the baseline understanding you used in baseline_understanding_used so later stages can detect drift.",
6355
+ "Use refined_inputs for server_path, wait_for_selector, or reference when useful; use null values when no refinement is needed."
6356
+ ].join("\n")
6357
+ });
6358
+ return payloadOrBlocker(raw, context.checkpoint);
6359
+ },
6360
+ async implementChange(context) {
6361
+ if (!context.workdir || !(0, import_node_fs4.existsSync)(context.workdir)) {
6362
+ return {
6363
+ ok: false,
6364
+ blocker: {
6365
+ code: "implementation_workdir_missing",
6366
+ checkpoint: context.checkpoint,
6367
+ message: "The Riddle Proof state does not include an after worktree that exists on disk.",
6368
+ details: { workdir: context.workdir || null }
6369
+ }
6370
+ };
6371
+ }
6372
+ const workdir = context.workdir;
6373
+ const attemptSummaries = [];
6374
+ const runImplementationAttempt = async (purpose, extraLines = []) => {
6375
+ const raw = await callRunner(runner, {
6376
+ purpose,
6377
+ workdir,
6378
+ schema: IMPLEMENT_SCHEMA,
6379
+ prompt: buildImplementationPrompt(context, extraLines)
6380
+ });
6381
+ if (!raw.ok || !raw.json) {
6382
+ return {
6383
+ ok: false,
6384
+ payload: payloadOrBlocker(raw, context.checkpoint)
6385
+ };
6386
+ }
6387
+ const changedFiles = stringArray(raw.json.changed_files);
6388
+ const blockers = stringArray(raw.json.blockers);
6389
+ const testsRun = stringArray(raw.json.tests_run);
6390
+ const softVerificationBlockers = changedFiles.length ? blockers.filter(isHarnessVerificationOnlyBlocker) : [];
6391
+ const hardBlockers = blockers.filter((item) => !softVerificationBlockers.includes(item));
6392
+ const implementationNotesRaw = typeof raw.json.implementation_notes === "string" ? raw.json.implementation_notes : "";
6393
+ const summary = typeof raw.json.summary === "string" ? raw.json.summary : "";
6394
+ const implementationNotes = [
6395
+ implementationNotesRaw,
6396
+ ...softVerificationBlockers.map((item) => `Harness verification note: ${item}`)
6397
+ ].filter(Boolean).join("\n");
6398
+ const agentDetails = {
6399
+ agent_purpose: purpose,
6400
+ agent_summary: summary,
6401
+ agent_changed_files: changedFiles,
6402
+ agent_tests_run: testsRun,
6403
+ agent_blockers: blockers
6404
+ };
6405
+ attemptSummaries.push({
6406
+ purpose,
6407
+ summary,
6408
+ changed_files: changedFiles,
6409
+ tests_run: testsRun,
6410
+ blockers
6411
+ });
6412
+ if (hardBlockers.length) {
6413
+ return {
6414
+ ok: false,
6415
+ payload: {
6416
+ ok: false,
6417
+ blocker: {
6418
+ code: "codex_implementation_blocked",
6419
+ checkpoint: context.checkpoint,
6420
+ message: summary || "Codex reported implementation blockers.",
6421
+ details: {
6422
+ blockers: hardBlockers,
6423
+ changedFiles,
6424
+ testsRun,
6425
+ implementationNotes: implementationNotesRaw,
6426
+ ...agentDetails
6427
+ }
6428
+ }
6429
+ }
6430
+ };
6431
+ }
6432
+ return {
6433
+ ok: true,
6434
+ summary,
6435
+ changedFiles,
6436
+ testsRun,
6437
+ implementationNotes,
6438
+ implementationNotesRaw,
6439
+ softVerificationBlockers,
6440
+ hardBlockers,
6441
+ agentDetails
6442
+ };
6443
+ };
6444
+ let attempt = await runImplementationAttempt("implementation");
6445
+ if (!attempt.ok) return attempt.payload;
6446
+ let diffDetected = hasGitDiff2(workdir);
6447
+ if (!diffDetected) {
6448
+ attempt = await runImplementationAttempt("implementation retry", [
6449
+ "The previous implementation attempt returned without a detectable git diff in this repository.",
6450
+ `Previous summary: ${attempt.summary || "(none)"}`,
6451
+ `Previous changed_files: ${JSON.stringify(attempt.changedFiles)}`,
6452
+ "Before you return success this time, run git status --short and git diff --name-only. If they are still empty, do not return success; either keep editing or explain the blocker."
6453
+ ]);
6454
+ if (!attempt.ok) return attempt.payload;
6455
+ diffDetected = hasGitDiff2(workdir);
6456
+ }
6457
+ return {
6458
+ ok: true,
6459
+ summary: attempt.summary || void 0,
6460
+ implementationNotes: attempt.implementationNotes || void 0,
6461
+ changedFiles: attempt.changedFiles,
6462
+ testsRun: attempt.testsRun,
6463
+ details: {
6464
+ ...attempt.agentDetails,
6465
+ implementation_notes: attempt.implementationNotes || attempt.implementationNotesRaw || "",
6466
+ soft_verification_blockers: attempt.softVerificationBlockers,
6467
+ hard_blocker_count: attempt.hardBlockers.length,
6468
+ retry_attempted: attemptSummaries.length > 1,
6469
+ attempt_count: attemptSummaries.length,
6470
+ attempt_summaries: attemptSummaries,
6471
+ post_agent_diff_detected: diffDetected
6472
+ }
6473
+ };
6474
+ },
6475
+ async assessProof(context) {
6476
+ const raw = await callRunner(runner, {
6477
+ purpose: "proof assessment",
6478
+ workdir: resolveWorkdir(context),
6479
+ schema: PROOF_SCHEMA,
6480
+ prompt: [
6481
+ basePrompt(context, "Judge the proof bundle."),
6482
+ "Decide whether the evidence is ready_to_ship or which internal stage should run next.",
6483
+ "Only use ready_to_ship when the before/prod and after evidence actually prove the requested change.",
6484
+ "Do not assume screenshots are required for every verification_mode. For data/audio/log/metric/custom proof, inspect the structured evidence bundle, proof_evidence_sample, artifacts, assertions, and success criteria directly.",
6485
+ "Use semantic_context.route, headings, buttons, and text anchors to ground route/content judgment before calling screenshot evidence wrong-route or unrelated.",
6486
+ "If structured proof evidence contains failed positive assertions, such as newCopyVisible: false or hasExpectedText: false, do not choose ready_to_ship until the evidence is reconciled or a richer proof is produced.",
6487
+ "For visual/UI proof, screenshots and route/page-state quality still matter, but capture success alone is not proof.",
6488
+ "For playable/gameplay proof, do not choose ready_to_ship unless playability evidence shows accepted input, state/time progression, and playfield/canvas pixel motion; a static generated scene is not playable proof.",
6489
+ "For visual/UI polish, reject changes that are technically different but not legible to a reviewer. If visual_delta.status is measured and visual_delta.passed is false, choose needs_implementation when the visible result is wrong, or needs_richer_proof only when non-visual proof artifacts are insufficient.",
6490
+ "If required visual_delta is unmeasured, missing, or not_applicable, choose revise_capture with recommended_stage=verify and continue_with_stage=verify so the same run stays in evidence/comparison recovery; do not choose ready_to_ship or generic needs_richer_proof for that missing metric.",
6491
+ "Do not ship if the baseline is blank, shell-only, generic, or unrelated to the requested feature.",
6492
+ "Your summary must name the concrete change, the target that was tested, what changed between baseline and after evidence, and why the stop condition is satisfied."
6493
+ ].join("\n")
6494
+ });
6495
+ return payloadOrBlocker(raw, context.checkpoint);
6496
+ }
6497
+ };
6498
+ }
6499
+ function git(args, workdir) {
6500
+ return (0, import_node_child_process3.execFileSync)("git", args, {
6501
+ cwd: workdir,
6502
+ encoding: "utf-8",
6503
+ timeout: 1e4
6504
+ });
6505
+ }
6506
+ async function runCodexExecAgentDoctor(config = {}, runner = createCodexExecJsonRunner(config)) {
6507
+ const workdir = (0, import_node_fs4.mkdtempSync)(import_node_path4.default.join(import_node_os.default.tmpdir(), "riddle-proof-codex-doctor-"));
6508
+ const targetPath = import_node_path4.default.join(workdir, "target.txt");
6509
+ (0, import_node_fs4.writeFileSync)(targetPath, "color=red\n");
6510
+ try {
6511
+ git(["init", "-b", "main"], workdir);
6512
+ git(["config", "user.email", "doctor@example.com"], workdir);
6513
+ git(["config", "user.name", "Riddle Proof Doctor"], workdir);
6514
+ git(["add", "target.txt"], workdir);
6515
+ git(["commit", "-m", "initial doctor fixture"], workdir);
6516
+ } catch (error) {
6517
+ return {
6518
+ ok: false,
6519
+ status: "blocked",
6520
+ blocker: {
6521
+ code: "doctor_git_setup_failed",
6522
+ message: "Could not create the temporary doctor git fixture.",
6523
+ details: { error: error instanceof Error ? error.message : String(error), workdir }
6524
+ }
6525
+ };
6526
+ }
6527
+ const raw = await callRunner(runner, {
6528
+ purpose: "codex exec doctor implementation",
6529
+ workdir,
6530
+ schema: IMPLEMENT_SCHEMA,
6531
+ prompt: [
6532
+ "You are running a Riddle Proof Codex exec doctor check.",
6533
+ "In this temporary git repository, edit target.txt so it says exactly: color=blue",
6534
+ "Do not commit. Leave a git diff.",
6535
+ "Return JSON matching the schema with changed_files containing target.txt.",
6536
+ "Use empty arrays for tests_run and blockers."
6537
+ ].join("\n")
6538
+ });
6539
+ if (!raw.ok || !raw.json) {
6540
+ return {
6541
+ ok: false,
6542
+ status: "blocked",
6543
+ blocker: {
6544
+ ...raw.blocker || {
6545
+ code: "doctor_codex_failed",
6546
+ message: "Codex doctor runner failed.",
6547
+ details: { stdout: raw.stdout || "", stderr: raw.stderr || "" }
6548
+ },
6549
+ details: {
6550
+ ...raw.blocker?.details || {},
6551
+ workdir
6552
+ }
6553
+ }
6554
+ };
6555
+ }
6556
+ const content = (0, import_node_fs4.readFileSync)(targetPath, "utf-8");
6557
+ const status = git(["status", "--porcelain"], workdir);
6558
+ const changedFiles = stringArray(raw.json.changed_files);
6559
+ const ok = content.trim() === "color=blue" && status.includes("target.txt");
6560
+ return {
6561
+ ok,
6562
+ status: ok ? "passed" : "blocked",
6563
+ workdir,
6564
+ changedFiles,
6565
+ implementationSummary: raw.json.summary || null,
6566
+ implementationNotes: raw.json.implementation_notes || null,
6567
+ gitStatus: status,
6568
+ targetContent: content,
6569
+ blocker: ok ? null : {
6570
+ code: "doctor_diff_missing_or_wrong",
6571
+ message: "Codex doctor completed, but target.txt was not changed to color=blue with a git diff.",
6572
+ details: { workdir, changedFiles, gitStatus: status, targetContent: content }
6573
+ }
6574
+ };
6575
+ }
6576
+
5361
6577
  // src/diagnostics.ts
5362
6578
  var RIDDLE_PROOF_CAPTURE_DIAGNOSTIC_VERSION = "riddle-proof.capture-diagnostic.v1";
5363
6579
  var DEFAULT_DIAGNOSTIC_STRING_LIMIT = 2e3;
@@ -5975,6 +7191,7 @@ function parseJson(value) {
5975
7191
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
5976
7192
  RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION,
5977
7193
  RIDDLE_PROOF_PLAYABILITY_VERSION,
7194
+ RIDDLE_PROOF_RUN_CARD_VERSION,
5978
7195
  RIDDLE_PROOF_RUN_STATE_VERSION,
5979
7196
  RIDDLE_PROOF_VISUAL_SESSION_FINGERPRINT_VERSION,
5980
7197
  RIDDLE_PROOF_VISUAL_SESSION_VERSION,
@@ -5988,13 +7205,17 @@ function parseJson(value) {
5988
7205
  buildAuthorCheckpointPacket,
5989
7206
  buildCheckpointPacketForEngineResult,
5990
7207
  buildProofAssessmentCheckpointPacket,
7208
+ buildStageCheckpointPacket,
5991
7209
  buildVisualProofSession,
5992
7210
  checkpointResponseIdentity,
5993
7211
  checkpointSummaryFromState,
5994
7212
  compactRecord,
5995
7213
  compareVisualProofSessionFingerprint,
5996
7214
  createCaptureDiagnostic,
7215
+ createCodexExecAgentAdapter,
7216
+ createCodexExecJsonRunner,
5997
7217
  createDisabledRiddleProofAgentAdapter,
7218
+ createRiddleProofRunCard,
5998
7219
  createRunResult,
5999
7220
  createRunState,
6000
7221
  createRunStatusSnapshot,
@@ -6014,6 +7235,7 @@ function parseJson(value) {
6014
7235
  readRiddleProofRunStatus,
6015
7236
  recordValue,
6016
7237
  redactForProofDiagnostics,
7238
+ runCodexExecAgentDoctor,
6017
7239
  runRiddleProof,
6018
7240
  runRiddleProofEngineHarness,
6019
7241
  setRunStatus,