@riddledc/riddle-proof 0.7.226 → 0.8.1

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 (132) hide show
  1. package/dist/adapters/codex-exec-agent.cjs +893 -0
  2. package/dist/adapters/codex-exec-agent.d.cts +3 -0
  3. package/dist/adapters/codex-exec-agent.d.ts +3 -0
  4. package/dist/adapters/codex-exec-agent.js +13 -0
  5. package/dist/adapters/codex.cjs +893 -0
  6. package/dist/adapters/codex.d.cts +3 -0
  7. package/dist/adapters/codex.d.ts +3 -0
  8. package/dist/adapters/codex.js +13 -0
  9. package/dist/adapters/local-agent.cjs +893 -0
  10. package/dist/adapters/local-agent.d.cts +3 -0
  11. package/dist/adapters/local-agent.d.ts +3 -0
  12. package/dist/adapters/local-agent.js +13 -0
  13. package/dist/adapters/openclaw.cjs +213 -0
  14. package/dist/adapters/openclaw.d.cts +2 -0
  15. package/dist/adapters/openclaw.d.ts +2 -0
  16. package/dist/adapters/openclaw.js +17 -0
  17. package/dist/advanced/engine-harness.cjs +5701 -0
  18. package/dist/advanced/engine-harness.d.cts +2 -0
  19. package/dist/advanced/engine-harness.d.ts +2 -0
  20. package/dist/advanced/engine-harness.js +16 -0
  21. package/dist/advanced/index.cjs +6242 -0
  22. package/dist/advanced/index.d.cts +5 -0
  23. package/dist/advanced/index.d.ts +5 -0
  24. package/dist/advanced/index.js +23 -0
  25. package/dist/advanced/proof-run-core.cjs +1085 -0
  26. package/dist/advanced/proof-run-core.d.cts +1 -0
  27. package/dist/advanced/proof-run-core.d.ts +1 -0
  28. package/dist/advanced/proof-run-core.js +59 -0
  29. package/dist/advanced/proof-run-engine.cjs +2905 -0
  30. package/dist/advanced/proof-run-engine.d.cts +2 -0
  31. package/dist/advanced/proof-run-engine.d.ts +2 -0
  32. package/dist/advanced/proof-run-engine.js +10 -0
  33. package/dist/advanced/runner.cjs +833 -0
  34. package/dist/advanced/runner.d.cts +2 -0
  35. package/dist/advanced/runner.d.ts +2 -0
  36. package/dist/advanced/runner.js +12 -0
  37. package/dist/app-contract/index.cjs +24 -0
  38. package/dist/app-contract/index.d.cts +1 -0
  39. package/dist/app-contract/index.d.ts +1 -0
  40. package/dist/app-contract/index.js +2 -0
  41. package/dist/basic-gameplay.js +1 -0
  42. package/dist/checkpoint.js +1 -0
  43. package/dist/chunk-BHL4JSGM.js +1900 -0
  44. package/dist/chunk-BTN76IGW.js +115 -0
  45. package/dist/{chunk-TGHTM66Z.js → chunk-COERZX63.js} +10 -2
  46. package/dist/{chunk-QUAZAMOM.js → chunk-IWLQQ5S5.js} +12 -2
  47. package/dist/chunk-MLKGABMK.js +9 -0
  48. package/dist/chunk-OFSECTSC.js +0 -0
  49. package/dist/{chunk-GBVEQQIM.js → chunk-TJ63IE65.js} +36 -1
  50. package/dist/chunk-VZD5LH7U.js +4138 -0
  51. package/dist/cli/index.cjs +18 -0
  52. package/dist/cli/index.d.cts +2 -0
  53. package/dist/cli/index.d.ts +2 -0
  54. package/dist/cli/index.js +12 -0
  55. package/dist/cli.d.cts +1 -0
  56. package/dist/cli.d.ts +1 -0
  57. package/dist/cli.js +8 -4139
  58. package/dist/codex-exec-agent.d.cts +1 -1
  59. package/dist/codex-exec-agent.d.ts +1 -1
  60. package/dist/codex-exec-agent.js +1 -0
  61. package/dist/diagnostics.js +1 -0
  62. package/dist/engine-harness-CMACHP6A.d.ts +96 -0
  63. package/dist/engine-harness-LBfqbFSe.d.cts +96 -0
  64. package/dist/engine-harness.d.cts +2 -79
  65. package/dist/engine-harness.d.ts +2 -79
  66. package/dist/engine-harness.js +3 -2
  67. package/dist/index.d.cts +2 -2
  68. package/dist/index.d.ts +2 -2
  69. package/dist/index.js +4 -3
  70. package/dist/local-agent.d.cts +1 -1
  71. package/dist/local-agent.d.ts +1 -1
  72. package/dist/local-agent.js +1 -0
  73. package/dist/openclaw.js +8 -107
  74. package/dist/playability.js +1 -0
  75. package/dist/profile/index.cjs +9403 -0
  76. package/dist/profile/index.d.cts +2 -0
  77. package/dist/profile/index.d.ts +2 -0
  78. package/dist/profile/index.js +53 -0
  79. package/dist/profile.js +1 -0
  80. package/dist/proof-run-core-CE0jx7wL.d.cts +359 -0
  81. package/dist/proof-run-core-CE0jx7wL.d.ts +359 -0
  82. package/dist/proof-run-core.d.cts +1 -322
  83. package/dist/proof-run-core.d.ts +1 -322
  84. package/dist/proof-run-core.js +2 -1
  85. package/dist/proof-run-engine-CSSc0mNn.d.ts +764 -0
  86. package/dist/proof-run-engine-HSRpUeBi.d.cts +764 -0
  87. package/dist/proof-run-engine.d.cts +2 -757
  88. package/dist/proof-run-engine.d.ts +2 -757
  89. package/dist/proof-run-engine.js +5 -1885
  90. package/dist/proof-session.js +1 -0
  91. package/dist/result.js +1 -0
  92. package/dist/riddle-client.js +1 -0
  93. package/dist/run-card.js +1 -0
  94. package/dist/runner-4LJ5z0D-.d.cts +29 -0
  95. package/dist/runner-BdQpOkZD.d.ts +29 -0
  96. package/dist/runner.d.cts +2 -22
  97. package/dist/runner.d.ts +2 -22
  98. package/dist/runner.js +3 -2
  99. package/dist/runtime/index.cjs +528 -0
  100. package/dist/runtime/index.d.cts +1 -0
  101. package/dist/runtime/index.d.ts +1 -0
  102. package/dist/runtime/index.js +37 -0
  103. package/dist/runtime/riddle-client.cjs +528 -0
  104. package/dist/runtime/riddle-client.d.cts +1 -0
  105. package/dist/runtime/riddle-client.d.ts +1 -0
  106. package/dist/runtime/riddle-client.js +37 -0
  107. package/dist/spec/checkpoint.cjs +807 -0
  108. package/dist/spec/checkpoint.d.cts +2 -0
  109. package/dist/spec/checkpoint.d.ts +2 -0
  110. package/dist/spec/checkpoint.js +34 -0
  111. package/dist/spec/index.cjs +1510 -0
  112. package/dist/spec/index.d.cts +5 -0
  113. package/dist/spec/index.d.ts +5 -0
  114. package/dist/spec/index.js +80 -0
  115. package/dist/spec/result.cjs +259 -0
  116. package/dist/spec/result.d.cts +2 -0
  117. package/dist/spec/result.d.ts +2 -0
  118. package/dist/spec/result.js +21 -0
  119. package/dist/spec/run-card.cjs +287 -0
  120. package/dist/spec/run-card.d.cts +2 -0
  121. package/dist/spec/run-card.d.ts +2 -0
  122. package/dist/spec/run-card.js +11 -0
  123. package/dist/spec/state.cjs +541 -0
  124. package/dist/spec/state.d.cts +2 -0
  125. package/dist/spec/state.d.ts +2 -0
  126. package/dist/spec/state.js +28 -0
  127. package/dist/spec/types.cjs +18 -0
  128. package/dist/spec/types.d.cts +1 -0
  129. package/dist/spec/types.d.ts +1 -0
  130. package/dist/spec/types.js +1 -0
  131. package/dist/state.js +1 -0
  132. package/package.json +95 -2
@@ -0,0 +1,1510 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/spec/index.ts
31
+ var spec_exports = {};
32
+ __export(spec_exports, {
33
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: () => RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
34
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
35
+ RIDDLE_PROOF_RUN_CARD_VERSION: () => RIDDLE_PROOF_RUN_CARD_VERSION,
36
+ RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
37
+ appendRunEvent: () => appendRunEvent,
38
+ appendStageHeartbeat: () => appendStageHeartbeat,
39
+ applyPrLifecycleState: () => applyPrLifecycleState,
40
+ applyTerminalMetadata: () => applyTerminalMetadata,
41
+ authorPacketPayloadFromCheckpointResponse: () => authorPacketPayloadFromCheckpointResponse,
42
+ buildAuthorCheckpointPacket: () => buildAuthorCheckpointPacket,
43
+ buildCheckpointPacketForEngineResult: () => buildCheckpointPacketForEngineResult,
44
+ buildProofAssessmentCheckpointPacket: () => buildProofAssessmentCheckpointPacket,
45
+ buildStageCheckpointPacket: () => buildStageCheckpointPacket,
46
+ checkpointResponseIdentity: () => checkpointResponseIdentity,
47
+ checkpointSummaryFromState: () => checkpointSummaryFromState,
48
+ compactRecord: () => compactRecord,
49
+ createCheckpointResponseTemplate: () => createCheckpointResponseTemplate,
50
+ createRiddleProofRunCard: () => createRiddleProofRunCard,
51
+ createRunResult: () => createRunResult,
52
+ createRunState: () => createRunState,
53
+ createRunStatusSnapshot: () => createRunStatusSnapshot,
54
+ isDuplicateCheckpointResponse: () => isDuplicateCheckpointResponse,
55
+ isSuccessfulStatus: () => isSuccessfulStatus,
56
+ isTerminalStatus: () => isTerminalStatus,
57
+ nonEmptyString: () => nonEmptyString,
58
+ normalizeCheckpointResponse: () => normalizeCheckpointResponse,
59
+ normalizeIntegrationContext: () => normalizeIntegrationContext,
60
+ normalizePrLifecycleState: () => normalizePrLifecycleState,
61
+ normalizeRunParams: () => normalizeRunParams,
62
+ normalizeTerminalMetadata: () => normalizeTerminalMetadata,
63
+ proofContractFromAuthorCheckpointResponse: () => proofContractFromAuthorCheckpointResponse,
64
+ recordValue: () => recordValue,
65
+ setRunStatus: () => setRunStatus,
66
+ statePathsForRunState: () => statePathsForRunState
67
+ });
68
+ module.exports = __toCommonJS(spec_exports);
69
+
70
+ // src/result.ts
71
+ function isTerminalStatus(status) {
72
+ return status === "blocked" || status === "failed" || status === "ready_to_ship" || status === "shipped" || status === "completed";
73
+ }
74
+ function isSuccessfulStatus(status) {
75
+ return status !== "blocked" && status !== "failed";
76
+ }
77
+ function compactRecord(input) {
78
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0 && value !== null && value !== ""));
79
+ }
80
+ function nonEmptyString(value) {
81
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
82
+ }
83
+ function recordValue(value) {
84
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
85
+ }
86
+ function firstNonEmptyString(...values) {
87
+ for (const value of values) {
88
+ const normalized = nonEmptyString(value);
89
+ if (normalized) return normalized;
90
+ }
91
+ return void 0;
92
+ }
93
+ function firstBoolean(...values) {
94
+ for (const value of values) {
95
+ if (typeof value === "boolean") return value;
96
+ }
97
+ return void 0;
98
+ }
99
+ function normalizePrStatus(value) {
100
+ const status = nonEmptyString(value)?.toLowerCase();
101
+ if (status === "merged") return "merged";
102
+ if (status === "open") return "open";
103
+ if (status === "closed") return "closed";
104
+ if (status === "not_found" || status === "not-found") return "not_found";
105
+ if (status === "unavailable") return "unavailable";
106
+ return status || "unknown";
107
+ }
108
+ function normalizePrLifecycleStateInput(input) {
109
+ if (!input) return void 0;
110
+ const cleanup = recordValue(input.cleanup);
111
+ const mergeCommit = nonEmptyString(input.merge_commit) || nonEmptyString(input.mergeCommit) || nonEmptyString(recordValue(input.mergeCommit)?.oid);
112
+ return compactRecord({
113
+ status: normalizePrStatus(input.status || input.state),
114
+ pr_url: nonEmptyString(input.pr_url) || nonEmptyString(input.prUrl) || nonEmptyString(input.url),
115
+ pr_number: nonEmptyString(input.pr_number) || nonEmptyString(input.prNumber) || (typeof input.number === "number" ? String(input.number) : void 0),
116
+ repo: nonEmptyString(input.repo) || nonEmptyString(input.repository),
117
+ head_branch: nonEmptyString(input.head_branch) || nonEmptyString(input.headBranch) || nonEmptyString(input.headRefName),
118
+ base_branch: nonEmptyString(input.base_branch) || nonEmptyString(input.baseBranch) || nonEmptyString(input.baseRefName),
119
+ merge_commit: mergeCommit,
120
+ merged_at: nonEmptyString(input.merged_at) || nonEmptyString(input.mergedAt),
121
+ closed_at: nonEmptyString(input.closed_at) || nonEmptyString(input.closedAt),
122
+ checked_at: nonEmptyString(input.checked_at) || nonEmptyString(input.checkedAt),
123
+ source: nonEmptyString(input.source),
124
+ next_action: nonEmptyString(input.next_action) || nonEmptyString(input.nextAction),
125
+ cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
126
+ });
127
+ }
128
+ function normalizeTerminalMetadata(input) {
129
+ const riddleState = recordValue(input.riddleState) || {};
130
+ const result = recordValue(input.engineResult) || {};
131
+ const contract = recordValue(result.checkpointContract) || {};
132
+ const details = recordValue(input.checkpointDetails) || recordValue(contract.details) || {};
133
+ const shipReport = recordValue(riddleState.ship_report) || recordValue(result.ship_report) || recordValue(result.shipReport) || recordValue(details.ship_report) || recordValue(details.shipReport) || {};
134
+ const markedReady = firstBoolean(
135
+ riddleState.marked_ready,
136
+ result.marked_ready,
137
+ result.markedReady,
138
+ details.marked_ready,
139
+ details.markedReady,
140
+ shipReport.marked_ready
141
+ );
142
+ const leftDraft = firstBoolean(
143
+ riddleState.left_draft,
144
+ result.left_draft,
145
+ result.leftDraft,
146
+ details.left_draft,
147
+ details.leftDraft,
148
+ shipReport.left_draft
149
+ );
150
+ const finalized = firstBoolean(riddleState.finalized, result.finalized, details.finalized);
151
+ const prState = normalizePrLifecycleStateInput(
152
+ recordValue(riddleState.pr_state) || recordValue(riddleState.prState) || recordValue(result.pr_state) || recordValue(result.prState) || recordValue(details.pr_state) || recordValue(details.prState) || recordValue(shipReport.pr_state) || recordValue(shipReport.prState)
153
+ );
154
+ const cleanupReport = recordValue(riddleState.cleanup_report) || recordValue(riddleState.cleanupReport) || recordValue(result.cleanup_report) || recordValue(result.cleanupReport) || recordValue(details.cleanup_report) || recordValue(details.cleanupReport) || recordValue(prState?.cleanup);
155
+ return compactRecord({
156
+ pr_url: firstNonEmptyString(riddleState.pr_url, result.pr_url, result.prUrl, details.pr_url, details.prUrl, shipReport.pr_url),
157
+ pr_branch: firstNonEmptyString(
158
+ riddleState.pr_branch,
159
+ riddleState.target_branch,
160
+ result.pr_branch,
161
+ result.prBranch,
162
+ details.pr_branch,
163
+ details.prBranch,
164
+ shipReport.pr_branch,
165
+ shipReport.branch,
166
+ prState?.head_branch
167
+ ),
168
+ pr_state: prState,
169
+ marked_ready: markedReady,
170
+ left_draft: leftDraft,
171
+ ci_status: firstNonEmptyString(riddleState.ci_status, result.ci_status, result.ciStatus, details.ci_status, details.ciStatus, shipReport.ci_status),
172
+ ship_commit: firstNonEmptyString(riddleState.ship_commit, result.ship_commit, result.shipCommit, details.ship_commit, details.shipCommit, shipReport.shipped_commit, shipReport.ship_commit),
173
+ ship_remote_head: firstNonEmptyString(riddleState.ship_remote_head, result.ship_remote_head, result.shipRemoteHead, details.ship_remote_head, details.shipRemoteHead, shipReport.ship_remote_head),
174
+ merge_commit: firstNonEmptyString(riddleState.merge_commit, riddleState.mergeCommit, result.merge_commit, result.mergeCommit, details.merge_commit, details.mergeCommit, prState?.merge_commit),
175
+ merged_at: firstNonEmptyString(riddleState.merged_at, riddleState.mergedAt, result.merged_at, result.mergedAt, details.merged_at, details.mergedAt, prState?.merged_at),
176
+ proof_comment_url: firstNonEmptyString(riddleState.proof_comment_url, result.proof_comment_url, result.proofCommentUrl, details.proof_comment_url, details.proofCommentUrl, shipReport.proof_comment_url),
177
+ before_artifact_url: firstNonEmptyString(riddleState.before_artifact_url, riddleState.before_cdn, result.before_artifact_url, result.beforeArtifactUrl, details.before_artifact_url, details.beforeArtifactUrl, shipReport.before_artifact_url),
178
+ prod_artifact_url: firstNonEmptyString(riddleState.prod_artifact_url, riddleState.prod_cdn, result.prod_artifact_url, result.prodArtifactUrl, details.prod_artifact_url, details.prodArtifactUrl, shipReport.prod_artifact_url),
179
+ after_artifact_url: firstNonEmptyString(riddleState.after_artifact_url, riddleState.after_cdn, result.after_artifact_url, result.afterArtifactUrl, details.after_artifact_url, details.afterArtifactUrl, shipReport.after_artifact_url),
180
+ ship_report: Object.keys(shipReport).length ? shipReport : void 0,
181
+ cleanup_report: cleanupReport,
182
+ notification: recordValue(riddleState.notification) || recordValue(riddleState.discord_notification) || recordValue(result.notification) || recordValue(result.discord_notification),
183
+ proof_decision: nonEmptyString(riddleState.proof_decision) || nonEmptyString(result.proof_decision),
184
+ merge_recommendation: nonEmptyString(riddleState.merge_recommendation) || nonEmptyString(result.merge_recommendation),
185
+ finalized: typeof finalized === "boolean" ? finalized : void 0
186
+ });
187
+ }
188
+ function applyTerminalMetadata(state, metadata) {
189
+ if (metadata.pr_state) {
190
+ state.pr_state = metadata.pr_state;
191
+ if (metadata.pr_state.pr_url) state.pr_url = metadata.pr_state.pr_url;
192
+ if (metadata.pr_state.head_branch) state.pr_branch = metadata.pr_state.head_branch;
193
+ if (metadata.pr_state.merge_commit) state.merge_commit = metadata.pr_state.merge_commit;
194
+ if (metadata.pr_state.merged_at) state.merged_at = metadata.pr_state.merged_at;
195
+ if (metadata.pr_state.cleanup) state.cleanup_report = metadata.pr_state.cleanup;
196
+ if (metadata.pr_state.status === "merged") state.finalized = true;
197
+ }
198
+ const prUrl = nonEmptyString(metadata.pr_url);
199
+ if (prUrl) state.pr_url = prUrl;
200
+ const prBranch = nonEmptyString(metadata.pr_branch);
201
+ if (prBranch) state.pr_branch = prBranch;
202
+ if (typeof metadata.marked_ready === "boolean") state.marked_ready = metadata.marked_ready;
203
+ if (typeof metadata.left_draft === "boolean") state.left_draft = metadata.left_draft;
204
+ const ciStatus = nonEmptyString(metadata.ci_status);
205
+ if (ciStatus) state.ci_status = ciStatus;
206
+ const shipCommit = nonEmptyString(metadata.ship_commit);
207
+ if (shipCommit) state.ship_commit = shipCommit;
208
+ const shipRemoteHead = nonEmptyString(metadata.ship_remote_head);
209
+ if (shipRemoteHead) state.ship_remote_head = shipRemoteHead;
210
+ const mergeCommit = nonEmptyString(metadata.merge_commit);
211
+ if (mergeCommit) state.merge_commit = mergeCommit;
212
+ const mergedAt = nonEmptyString(metadata.merged_at);
213
+ if (mergedAt) state.merged_at = mergedAt;
214
+ const proofCommentUrl = nonEmptyString(metadata.proof_comment_url);
215
+ if (proofCommentUrl) state.proof_comment_url = proofCommentUrl;
216
+ const beforeArtifactUrl = nonEmptyString(metadata.before_artifact_url);
217
+ if (beforeArtifactUrl) state.before_artifact_url = beforeArtifactUrl;
218
+ const prodArtifactUrl = nonEmptyString(metadata.prod_artifact_url);
219
+ if (prodArtifactUrl) state.prod_artifact_url = prodArtifactUrl;
220
+ const afterArtifactUrl = nonEmptyString(metadata.after_artifact_url);
221
+ if (afterArtifactUrl) state.after_artifact_url = afterArtifactUrl;
222
+ const shipReport = recordValue(metadata.ship_report);
223
+ if (shipReport) state.ship_report = shipReport;
224
+ const cleanupReport = recordValue(metadata.cleanup_report);
225
+ if (cleanupReport) state.cleanup_report = cleanupReport;
226
+ const notification = recordValue(metadata.notification);
227
+ if (notification) state.notification = notification;
228
+ const proofDecision = nonEmptyString(metadata.proof_decision);
229
+ if (proofDecision) state.proof_decision = proofDecision;
230
+ const mergeRecommendation = nonEmptyString(metadata.merge_recommendation);
231
+ if (mergeRecommendation) state.merge_recommendation = mergeRecommendation;
232
+ if (typeof metadata.finalized === "boolean") state.finalized = metadata.finalized;
233
+ return state;
234
+ }
235
+ function createRunResult(input) {
236
+ const status = input.status || input.state.status;
237
+ const ok = isSuccessfulStatus(status);
238
+ const state = input.metadata ? applyTerminalMetadata(input.state, input.metadata) : input.state;
239
+ state.status = status;
240
+ state.ok = ok;
241
+ return compactRecord({
242
+ ok,
243
+ status,
244
+ run_id: state.run_id,
245
+ state_path: input.state_path ?? state.state_path ?? null,
246
+ worktree_path: state.worktree_path ?? null,
247
+ branch: state.branch ?? null,
248
+ current_stage: state.current_stage ?? null,
249
+ iterations: state.iterations,
250
+ last_checkpoint: state.last_checkpoint ?? null,
251
+ last_summary: input.last_summary ?? null,
252
+ event_count: state.events.length,
253
+ pr_url: state.pr_url,
254
+ pr_branch: state.pr_branch,
255
+ pr_state: state.pr_state,
256
+ marked_ready: state.marked_ready,
257
+ left_draft: state.left_draft,
258
+ ci_status: state.ci_status,
259
+ ship_commit: state.ship_commit,
260
+ ship_remote_head: state.ship_remote_head,
261
+ merge_commit: state.merge_commit,
262
+ merged_at: state.merged_at,
263
+ proof_comment_url: state.proof_comment_url,
264
+ before_artifact_url: state.before_artifact_url,
265
+ prod_artifact_url: state.prod_artifact_url,
266
+ after_artifact_url: state.after_artifact_url,
267
+ ship_report: state.ship_report,
268
+ cleanup_report: state.cleanup_report,
269
+ notification: state.notification,
270
+ proof_decision: state.proof_decision,
271
+ merge_recommendation: state.merge_recommendation,
272
+ finalized: state.finalized,
273
+ blocker: state.blocker,
274
+ checkpoint_packet: state.checkpoint_packet,
275
+ checkpoint_summary: state.checkpoint_summary,
276
+ state_paths: state.state_paths,
277
+ proof_contract: state.proof_contract,
278
+ run_card: state.run_card,
279
+ proof_session: state.proof_session,
280
+ viewport_matrix_status: state.viewport_matrix_status,
281
+ evidence_bundle: input.evidence_bundle,
282
+ raw: input.raw
283
+ });
284
+ }
285
+
286
+ // src/checkpoint.ts
287
+ var import_node_crypto = __toESM(require("crypto"), 1);
288
+ var RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION = "riddle-proof.checkpoint.v1";
289
+ var RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION = "riddle-proof.checkpoint_response.v1";
290
+ function timestamp() {
291
+ return (/* @__PURE__ */ new Date()).toISOString();
292
+ }
293
+ function jsonCloneRecord(value) {
294
+ const record = recordValue(value);
295
+ if (!record) return void 0;
296
+ try {
297
+ return JSON.parse(JSON.stringify(record));
298
+ } catch {
299
+ return { ...record };
300
+ }
301
+ }
302
+ function jsonCloneValue(value) {
303
+ if (value === void 0 || value === null) return void 0;
304
+ try {
305
+ return JSON.parse(JSON.stringify(value));
306
+ } catch {
307
+ return value;
308
+ }
309
+ }
310
+ function stableJson(value) {
311
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
312
+ const record = recordValue(value);
313
+ if (record) {
314
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
315
+ }
316
+ return JSON.stringify(value);
317
+ }
318
+ function compactText(value, limit = 1600) {
319
+ const text = nonEmptyString(value);
320
+ if (!text) return void 0;
321
+ return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
322
+ }
323
+ function statePathsForRunState(state, engineStatePath) {
324
+ return compactRecord({
325
+ wrapper_state_path: state.state_path || state.request.harness_state_path || null,
326
+ engine_state_path: engineStatePath || state.request.engine_state_path || null,
327
+ resume_state_path: engineStatePath || state.request.engine_state_path || null
328
+ });
329
+ }
330
+ function responseSchemaForAuthorPacket() {
331
+ return {
332
+ type: "object",
333
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "payload", "created_at"],
334
+ additionalProperties: false,
335
+ properties: {
336
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
337
+ run_id: { type: "string" },
338
+ checkpoint: { type: "string" },
339
+ resume_token: { type: "string" },
340
+ decision: {
341
+ type: "string",
342
+ enum: ["author_packet", "needs_recon", "blocked", "human_review"]
343
+ },
344
+ summary: { type: "string" },
345
+ payload: {
346
+ type: "object",
347
+ description: "For decision=author_packet, provide the proof packet itself or {author_packet:{...}} with proof_plan and capture_script."
348
+ },
349
+ reasons: { type: "array", items: { type: "string" } },
350
+ continue_with_stage: { type: "string", enum: ["author", "recon"] },
351
+ source: {
352
+ type: "object",
353
+ properties: {
354
+ kind: { type: "string" },
355
+ session_id: { type: "string" },
356
+ user_id: { type: "string" }
357
+ }
358
+ },
359
+ created_at: { type: "string" }
360
+ }
361
+ };
362
+ }
363
+ function responseSchemaForProofAssessmentPacket() {
364
+ return {
365
+ type: "object",
366
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
367
+ additionalProperties: false,
368
+ properties: {
369
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
370
+ run_id: { type: "string" },
371
+ checkpoint: { type: "string" },
372
+ resume_token: { type: "string" },
373
+ decision: {
374
+ type: "string",
375
+ enum: [
376
+ "ready_to_ship",
377
+ "needs_richer_proof",
378
+ "revise_capture",
379
+ "needs_recon",
380
+ "needs_implementation",
381
+ "blocked",
382
+ "human_review"
383
+ ]
384
+ },
385
+ summary: { type: "string" },
386
+ payload: {
387
+ type: "object",
388
+ description: "Optional structured assessment details, including recommended_stage, continue_with_stage, visual_delta notes, or blocker diagnostics."
389
+ },
390
+ reasons: { type: "array", items: { type: "string" } },
391
+ continue_with_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
392
+ source: {
393
+ type: "object",
394
+ properties: {
395
+ kind: { type: "string" },
396
+ session_id: { type: "string" },
397
+ user_id: { type: "string" }
398
+ }
399
+ },
400
+ created_at: { type: "string" }
401
+ }
402
+ };
403
+ }
404
+ function responseSchemaForReconPacket() {
405
+ return {
406
+ type: "object",
407
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
408
+ additionalProperties: false,
409
+ properties: {
410
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
411
+ run_id: { type: "string" },
412
+ checkpoint: { type: "string" },
413
+ resume_token: { type: "string" },
414
+ decision: {
415
+ type: "string",
416
+ enum: ["ready_for_author", "retry_recon", "recon_stuck", "needs_recon", "blocked", "human_review"]
417
+ },
418
+ summary: { type: "string" },
419
+ payload: {
420
+ type: "object",
421
+ description: "Optional recon assessment details such as baseline_understanding, refined_inputs, reasons, or diagnostic blocker context."
422
+ },
423
+ reasons: { type: "array", items: { type: "string" } },
424
+ continue_with_stage: { type: "string", enum: ["recon", "author"] },
425
+ source: {
426
+ type: "object",
427
+ properties: {
428
+ kind: { type: "string" },
429
+ session_id: { type: "string" },
430
+ user_id: { type: "string" }
431
+ }
432
+ },
433
+ created_at: { type: "string" }
434
+ }
435
+ };
436
+ }
437
+ function responseSchemaForImplementationPacket() {
438
+ return {
439
+ type: "object",
440
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
441
+ additionalProperties: false,
442
+ properties: {
443
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
444
+ run_id: { type: "string" },
445
+ checkpoint: { type: "string" },
446
+ resume_token: { type: "string" },
447
+ decision: {
448
+ type: "string",
449
+ enum: ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"]
450
+ },
451
+ summary: { type: "string" },
452
+ payload: {
453
+ type: "object",
454
+ 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."
455
+ },
456
+ reasons: { type: "array", items: { type: "string" } },
457
+ continue_with_stage: { type: "string", enum: ["implement", "verify", "author", "recon"] },
458
+ source: {
459
+ type: "object",
460
+ properties: {
461
+ kind: { type: "string" },
462
+ session_id: { type: "string" },
463
+ user_id: { type: "string" }
464
+ }
465
+ },
466
+ created_at: { type: "string" }
467
+ }
468
+ };
469
+ }
470
+ function responseSchemaForAdvancePacket(stage) {
471
+ return {
472
+ type: "object",
473
+ required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
474
+ additionalProperties: false,
475
+ properties: {
476
+ version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
477
+ run_id: { type: "string" },
478
+ checkpoint: { type: "string" },
479
+ resume_token: { type: "string" },
480
+ decision: {
481
+ type: "string",
482
+ enum: ["continue_stage", "retry_stage", "needs_recon", "needs_implementation", "blocked", "human_review"]
483
+ },
484
+ summary: { type: "string" },
485
+ payload: { type: "object" },
486
+ reasons: { type: "array", items: { type: "string" } },
487
+ continue_with_stage: { type: "string", enum: ["recon", "author", "implement", "verify", "ship", stage] },
488
+ source: {
489
+ type: "object",
490
+ properties: {
491
+ kind: { type: "string" },
492
+ session_id: { type: "string" },
493
+ user_id: { type: "string" }
494
+ }
495
+ },
496
+ created_at: { type: "string" }
497
+ }
498
+ };
499
+ }
500
+ function resumeTokenFor(input) {
501
+ const hash = import_node_crypto.default.createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 24);
502
+ return `rpchk_${hash}`;
503
+ }
504
+ function artifactsFromState(state) {
505
+ const artifacts = [];
506
+ for (const role of ["before", "prod", "after"]) {
507
+ const url = nonEmptyString(state?.[`${role}_cdn`]);
508
+ if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
509
+ }
510
+ const authorRequest = recordValue(state?.author_request);
511
+ const latestAttempt = recordValue(authorRequest?.latest_attempt);
512
+ const observations = recordValue(latestAttempt?.observations);
513
+ for (const [label, observation] of Object.entries(observations || {})) {
514
+ const record = recordValue(observation);
515
+ const url = nonEmptyString(record?.url);
516
+ if (url && !artifacts.some((artifact) => artifact.url === url)) {
517
+ artifacts.push({
518
+ role: label === "before" || label === "prod" ? label : "json",
519
+ url,
520
+ name: `${label}-observation`,
521
+ summary: compactText(record?.reason, 240)
522
+ });
523
+ }
524
+ }
525
+ return artifacts.slice(0, 16);
526
+ }
527
+ function stageFromCheckpoint(checkpoint) {
528
+ if (checkpoint.startsWith("recon_")) return "recon";
529
+ if (checkpoint.startsWith("author_")) return "author";
530
+ if (checkpoint.startsWith("implement_")) return "implement";
531
+ if (checkpoint.startsWith("verify_")) return "verify";
532
+ if (checkpoint.startsWith("ship_")) return "ship";
533
+ if (checkpoint.startsWith("pr_sync_")) return "notify";
534
+ if (checkpoint.includes("capture")) return "prove";
535
+ return "setup";
536
+ }
537
+ function allowedDecisionsForStage(stage, checkpoint) {
538
+ if (stage === "recon") return ["ready_for_author", "retry_recon", "recon_stuck", "blocked", "human_review"];
539
+ if (stage === "implement") return ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"];
540
+ if (stage === "ship") return ["continue_stage", "needs_implementation", "needs_recon", "blocked", "human_review"];
541
+ if (checkpoint === "awaiting_stage_advance") return ["continue_stage", "retry_stage", "blocked", "human_review"];
542
+ return ["continue_stage", "needs_recon", "needs_implementation", "blocked", "human_review"];
543
+ }
544
+ function packetKindForStage(stage, checkpoint) {
545
+ if (stage === "recon") return "assess_recon";
546
+ if (stage === "implement") return "implement_change";
547
+ if (checkpoint.includes("human")) return "human_review";
548
+ return "advance_decision";
549
+ }
550
+ function responseSchemaForStage(stage, checkpoint) {
551
+ if (stage === "recon") return responseSchemaForReconPacket();
552
+ if (stage === "implement") return responseSchemaForImplementationPacket();
553
+ return responseSchemaForAdvancePacket(stage);
554
+ }
555
+ function questionForStage(stage, checkpoint) {
556
+ if (stage === "recon") {
557
+ 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.";
558
+ }
559
+ if (stage === "implement") {
560
+ 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.";
561
+ }
562
+ if (stage === "ship") {
563
+ 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.";
564
+ }
565
+ return "Choose the next Riddle Proof stage for this durable run, or block with a concrete reason if the run cannot honestly advance.";
566
+ }
567
+ function buildStageCheckpointPacket(input) {
568
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "stage_checkpoint";
569
+ const stage = nonEmptyString(input.engineResult.stage) || stageFromCheckpoint(checkpoint);
570
+ const runId = input.runState.run_id || "unknown";
571
+ const fullState = input.fullRiddleState || {};
572
+ const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
573
+ const checkpointContract = recordValue(input.engineResult.checkpointContract);
574
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.stage_summary) || `${stage} checkpoint needs a supervising decision.`;
575
+ const kind = packetKindForStage(stage, checkpoint);
576
+ return {
577
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
578
+ run_id: runId,
579
+ state_path: input.runState.state_path,
580
+ stage,
581
+ checkpoint,
582
+ kind,
583
+ summary,
584
+ question: questionForStage(stage, checkpoint),
585
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
586
+ context: input.request.context,
587
+ artifacts: artifactsFromState(fullState),
588
+ state_excerpt: compactRecord({
589
+ repo: input.request.repo || fullState.repo,
590
+ branch: input.request.branch || fullState.branch,
591
+ after_worktree: fullState.after_worktree || input.runState.worktree_path,
592
+ verification_mode: input.request.verification_mode || fullState.verification_mode,
593
+ reference: input.request.reference || fullState.reference,
594
+ server_path: fullState.server_path,
595
+ wait_for_selector: fullState.wait_for_selector,
596
+ recon_status: fullState.recon_status,
597
+ author_status: fullState.author_status,
598
+ implementation_status: fullState.implementation_status,
599
+ verify_status: fullState.verify_status,
600
+ stage_decision_request: jsonCloneRecord(fullState.stage_decision_request)
601
+ }),
602
+ evidence_excerpt: compactRecord({
603
+ before_cdn: fullState.before_cdn || null,
604
+ prod_cdn: fullState.prod_cdn || null,
605
+ after_cdn: fullState.after_cdn || null,
606
+ recon_results: jsonCloneRecord(fullState.recon_results),
607
+ checkpoint_contract: jsonCloneRecord(checkpointContract),
608
+ decision_details: jsonCloneRecord(decisionDetails)
609
+ }),
610
+ allowed_decisions: allowedDecisionsForStage(stage, checkpoint),
611
+ response_schema: responseSchemaForStage(stage, checkpoint),
612
+ routing_hint: {
613
+ suggested_role: stage === "implement" ? "builder_agent" : checkpoint.includes("human") ? "human" : "main_agent",
614
+ visibility: input.visibility || "quiet",
615
+ urgency: stage === "ship" ? "high" : "normal",
616
+ can_auto_answer: input.visibility !== "manual"
617
+ },
618
+ resume_token: resumeTokenFor({
619
+ runId,
620
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
621
+ checkpoint,
622
+ stage
623
+ }),
624
+ created_at: input.created_at || timestamp()
625
+ };
626
+ }
627
+ function buildAuthorCheckpointPacket(input) {
628
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "author_supervisor_judgment";
629
+ const stage = "author";
630
+ const runId = input.runState.run_id || "unknown";
631
+ const fullState = input.fullRiddleState || {};
632
+ const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
633
+ const authorRequest = recordValue(fullState.author_request) || recordValue(fullState.proof_plan_request) || recordValue(decisionDetails?.authorRequest) || {};
634
+ const fallbackDefaults = recordValue(authorRequest.fallback_defaults) || {};
635
+ const reconResults = recordValue(fullState.recon_results);
636
+ const checkpointContract = recordValue(input.engineResult.checkpointContract);
637
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.author_summary) || "Author checkpoint needs a supervising proof packet.";
638
+ return {
639
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
640
+ run_id: runId,
641
+ state_path: input.runState.state_path,
642
+ stage,
643
+ checkpoint,
644
+ kind: "author_proof",
645
+ summary,
646
+ question: "Author the proof packet for this Riddle Proof run. Return a CheckpointResponse with decision=author_packet and payload containing proof_plan and capture_script.",
647
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
648
+ context: input.request.context,
649
+ artifacts: artifactsFromState(fullState),
650
+ state_excerpt: compactRecord({
651
+ repo: input.request.repo || fullState.repo,
652
+ branch: input.request.branch || fullState.branch,
653
+ verification_mode: input.request.verification_mode || fullState.verification_mode,
654
+ reference: input.request.reference || fullState.reference,
655
+ server_path: fullState.server_path,
656
+ wait_for_selector: fullState.wait_for_selector,
657
+ author_summary: fullState.author_summary,
658
+ author_request: jsonCloneRecord(authorRequest),
659
+ recon_baseline_understanding: jsonCloneRecord(fullState.recon_baseline_understanding),
660
+ fallback_defaults: jsonCloneRecord(fallbackDefaults)
661
+ }),
662
+ evidence_excerpt: compactRecord({
663
+ recon_results: jsonCloneRecord(reconResults),
664
+ checkpoint_contract: jsonCloneRecord(checkpointContract)
665
+ }),
666
+ allowed_decisions: ["author_packet", "needs_recon", "blocked", "human_review"],
667
+ response_schema: responseSchemaForAuthorPacket(),
668
+ routing_hint: {
669
+ suggested_role: "proof_author",
670
+ visibility: input.visibility || "quiet",
671
+ urgency: "normal",
672
+ can_auto_answer: input.visibility !== "manual"
673
+ },
674
+ resume_token: resumeTokenFor({
675
+ runId,
676
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
677
+ checkpoint,
678
+ stage
679
+ }),
680
+ created_at: input.created_at || timestamp()
681
+ };
682
+ }
683
+ function visualDeltaFromState(fullState) {
684
+ const bundle = recordValue(fullState.evidence_bundle);
685
+ const after = recordValue(bundle?.after);
686
+ const afterDelta = recordValue(after?.visual_delta);
687
+ if (afterDelta && Object.keys(afterDelta).length) return afterDelta;
688
+ const proofAssessmentRequest = recordValue(fullState.proof_assessment_request);
689
+ return recordValue(proofAssessmentRequest?.visual_delta) || null;
690
+ }
691
+ function normalizedText(value) {
692
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
693
+ }
694
+ function noImplementationModeForCheckpoint(request, fullState) {
695
+ const requestRecord = recordValue(request) || {};
696
+ const mode = normalizedText(
697
+ requestRecord.mode || requestRecord.workflow_mode || fullState.mode || fullState.workflow_mode
698
+ );
699
+ const implementationMode = normalizedText(requestRecord.implementation_mode || fullState.implementation_mode);
700
+ const requireDiff = requestRecord.require_diff ?? fullState.require_diff;
701
+ const allowCodeChanges = requestRecord.allow_code_changes ?? fullState.allow_code_changes;
702
+ return mode === "audit" || mode === "profile" || implementationMode === "none" || requireDiff === false || allowCodeChanges === false;
703
+ }
704
+ function visualDeltaNotApplicableForNoImplementation(visualDelta) {
705
+ if (String(visualDelta?.status || "").trim() !== "not_applicable") return false;
706
+ const reason = String(visualDelta?.reason || "").toLowerCase();
707
+ return reason.includes("audit/no-diff") || reason.includes("does not require a before/after implementation delta");
708
+ }
709
+ function verificationModeRequiresVisualDelta(value) {
710
+ const mode = String(value || "proof").trim().toLowerCase();
711
+ return [
712
+ "visual",
713
+ "render",
714
+ "interaction",
715
+ "ui",
716
+ "layout",
717
+ "screenshot",
718
+ "canvas",
719
+ "animation"
720
+ ].includes(mode);
721
+ }
722
+ function visualDeltaIssueCode(visualDelta, required) {
723
+ const status = String(visualDelta?.status || "").trim();
724
+ const reason = String(visualDelta?.reason || "").toLowerCase();
725
+ if (status === "unmeasured") {
726
+ if (reason.includes("fetch") || reason.includes("allowlist") || reason.includes("registered domain") || reason.includes("high risk") || reason.includes("comparator")) {
727
+ return "comparator_fetch_blocked";
728
+ }
729
+ return "visual_delta_unmeasured";
730
+ }
731
+ if (status === "measured" && visualDelta?.passed === false) return "semantic_proof_failed";
732
+ if (required && status !== "measured") return "visual_delta_unmeasured";
733
+ return null;
734
+ }
735
+ function buildProofAssessmentCheckpointPacket(input) {
736
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "verify_supervisor_judgment";
737
+ const stage = "verify";
738
+ const runId = input.runState.run_id || "unknown";
739
+ const fullState = input.fullRiddleState || {};
740
+ const proofAssessmentRequest = recordValue(fullState.proof_assessment_request) || recordValue(recordValue(fullState.verify_decision_request)?.assessment_request) || recordValue(input.engineResult.decisionRequest?.details) || {};
741
+ const bundle = recordValue(fullState.evidence_bundle);
742
+ const artifactContract = recordValue(proofAssessmentRequest.artifact_contract) || recordValue(bundle?.artifact_contract);
743
+ const requiredSignals = recordValue(recordValue(artifactContract)?.required);
744
+ const visualDelta = visualDeltaFromState(fullState);
745
+ const verificationMode = nonEmptyString(bundle?.verification_mode) || nonEmptyString(fullState.verification_mode) || nonEmptyString(input.request.verification_mode) || "proof";
746
+ const noImplementationMode = noImplementationModeForCheckpoint(input.request, fullState);
747
+ const noImplementationVisualDelta = visualDeltaNotApplicableForNoImplementation(visualDelta);
748
+ const visualDeltaRequired = !noImplementationMode && !noImplementationVisualDelta && requiredSignals?.visual_delta !== false && (requiredSignals?.visual_delta === true || verificationModeRequiresVisualDelta(verificationMode));
749
+ const evidenceIssueCode2 = visualDeltaIssueCode(visualDelta, visualDeltaRequired);
750
+ const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.verify_summary) || "Verify captured evidence and needs a supervising proof assessment.";
751
+ 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.";
752
+ return {
753
+ version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
754
+ run_id: runId,
755
+ state_path: input.runState.state_path,
756
+ stage,
757
+ checkpoint,
758
+ kind: evidenceIssueCode2 ? "recover_evidence" : "assess_proof",
759
+ summary,
760
+ question: `Assess the current Riddle Proof evidence. ${recoveryHint} Return a CheckpointResponse using one allowed decision.`,
761
+ change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
762
+ context: input.request.context,
763
+ artifacts: artifactsFromState(fullState),
764
+ state_excerpt: compactRecord({
765
+ repo: input.request.repo || fullState.repo,
766
+ branch: input.request.branch || fullState.branch,
767
+ verification_mode: verificationMode,
768
+ reference: input.request.reference || fullState.reference,
769
+ server_path: fullState.server_path,
770
+ wait_for_selector: fullState.wait_for_selector,
771
+ implementation_status: fullState.implementation_status,
772
+ implementation_summary: fullState.implementation_summary,
773
+ changed_files: jsonCloneValue(fullState.changed_files),
774
+ proof_plan: compactText(fullState.proof_plan, 1200)
775
+ }),
776
+ evidence_excerpt: compactRecord({
777
+ before_cdn: fullState.before_cdn || null,
778
+ prod_cdn: fullState.prod_cdn || null,
779
+ after_cdn: fullState.after_cdn || null,
780
+ visual_delta_required: visualDeltaRequired,
781
+ visual_delta_ready: !visualDeltaRequired || visualDelta?.status === "measured" && visualDelta?.passed === true,
782
+ visual_delta: jsonCloneRecord(visualDelta),
783
+ evidence_issue_code: evidenceIssueCode2,
784
+ proof_assessment_request: jsonCloneRecord(proofAssessmentRequest),
785
+ verify_decision_request: jsonCloneRecord(fullState.verify_decision_request),
786
+ checkpoint_contract: jsonCloneRecord(input.engineResult.checkpointContract)
787
+ }),
788
+ artifact_contract: jsonCloneRecord(artifactContract),
789
+ allowed_decisions: [
790
+ "ready_to_ship",
791
+ "needs_richer_proof",
792
+ "revise_capture",
793
+ "needs_recon",
794
+ "needs_implementation",
795
+ "blocked",
796
+ "human_review"
797
+ ],
798
+ response_schema: responseSchemaForProofAssessmentPacket(),
799
+ routing_hint: {
800
+ suggested_role: evidenceIssueCode2 ? "proof_judge" : "proof_judge",
801
+ visibility: input.visibility || "quiet",
802
+ urgency: evidenceIssueCode2 ? "high" : "normal",
803
+ can_auto_answer: input.visibility !== "manual"
804
+ },
805
+ resume_token: resumeTokenFor({
806
+ runId,
807
+ statePath: input.engineResult.state_path || input.request.engine_state_path || null,
808
+ checkpoint,
809
+ stage
810
+ }),
811
+ created_at: input.created_at || timestamp()
812
+ };
813
+ }
814
+ function buildCheckpointPacketForEngineResult(input) {
815
+ const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "";
816
+ if (checkpoint === "verify_supervisor_judgment" || checkpoint === "verify_supervisor_judgment_required" || checkpoint === "verify_human_escalation") {
817
+ return buildProofAssessmentCheckpointPacket(input);
818
+ }
819
+ const resume = recordValue(input.engineResult.checkpointContract?.resume);
820
+ const continueStage = nonEmptyString(resume?.continue_with_stage);
821
+ if (checkpoint === "author_supervisor_judgment" || checkpoint === "verify_capture_retry" || checkpoint === "verify_agent_retry" && continueStage === "author") {
822
+ return buildAuthorCheckpointPacket(input);
823
+ }
824
+ return buildStageCheckpointPacket(input);
825
+ }
826
+ function normalizeCheckpointResponse(value) {
827
+ const record = recordValue(value);
828
+ if (!record) return null;
829
+ const version = nonEmptyString(record.version);
830
+ const runId = nonEmptyString(record.run_id);
831
+ const checkpoint = nonEmptyString(record.checkpoint);
832
+ const decision = nonEmptyString(record.decision);
833
+ const summary = nonEmptyString(record.summary);
834
+ if (version !== RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION || !runId || !checkpoint || !decision || !summary) {
835
+ return null;
836
+ }
837
+ return compactRecord({
838
+ version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
839
+ run_id: runId,
840
+ checkpoint,
841
+ resume_token: nonEmptyString(record.resume_token),
842
+ decision,
843
+ summary,
844
+ payload: jsonCloneRecord(record.payload),
845
+ reasons: Array.isArray(record.reasons) ? record.reasons.filter((item) => typeof item === "string") : void 0,
846
+ continue_with_stage: nonEmptyString(record.continue_with_stage),
847
+ source: jsonCloneRecord(record.source),
848
+ created_at: nonEmptyString(record.created_at) || timestamp()
849
+ });
850
+ }
851
+ function defaultContinueStage(packet, decision) {
852
+ if (decision === "ready_for_author" || decision === "author_packet" || decision === "needs_author") return "author";
853
+ if (decision === "implementation_complete") return "verify";
854
+ if (decision === "ready_to_ship") return "ship";
855
+ if (decision === "revise_capture") return "verify";
856
+ if (decision === "retry_recon" || decision === "recon_stuck" || decision === "needs_recon") return "recon";
857
+ if (decision === "needs_implementation") return "implement";
858
+ if (decision === "continue_stage" || decision === "retry_stage") return packet.stage;
859
+ return void 0;
860
+ }
861
+ function templatePayloadFor(packet, decision) {
862
+ if (decision === "author_packet") {
863
+ return {
864
+ proof_plan: "TODO: describe the exact proof plan and stop condition.",
865
+ capture_script: "TODO: provide the capture script that collects required artifacts/evidence.",
866
+ summary: "TODO: summarize why this proof packet targets the requested change."
867
+ };
868
+ }
869
+ if (decision === "implementation_complete") {
870
+ return {
871
+ changed_files: [],
872
+ tests_run: [],
873
+ implementation_notes: "TODO: summarize the direct edits made in the after worktree."
874
+ };
875
+ }
876
+ if (decision === "ready_for_author") {
877
+ return {
878
+ baseline_understanding: {
879
+ reference: "TODO",
880
+ target_route: "TODO",
881
+ before_evidence_url: "TODO",
882
+ visible_before_state: "TODO",
883
+ relevant_elements: [],
884
+ requested_change: packet.change_request,
885
+ proof_focus: "TODO",
886
+ stop_condition: "TODO",
887
+ quality_risks: []
888
+ },
889
+ refined_inputs: {
890
+ server_path: null,
891
+ wait_for_selector: null,
892
+ reference: null
893
+ }
894
+ };
895
+ }
896
+ if (packet.kind === "assess_proof" || packet.kind === "recover_evidence" || packet.stage === "verify") {
897
+ return {
898
+ recommended_stage: defaultContinueStage(packet, decision) || packet.stage,
899
+ evidence_issue_code: packet.evidence_excerpt?.evidence_issue_code || null,
900
+ visual_delta: packet.evidence_excerpt?.visual_delta || null
901
+ };
902
+ }
903
+ return void 0;
904
+ }
905
+ function createCheckpointResponseTemplate(packet, input = {}) {
906
+ const allowed = Array.isArray(packet.allowed_decisions) ? packet.allowed_decisions : [];
907
+ const decision = input.decision && allowed.includes(input.decision) ? input.decision : allowed[0] || "blocked";
908
+ const continueStage = input.continue_with_stage || defaultContinueStage(packet, decision);
909
+ return compactRecord({
910
+ version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
911
+ run_id: packet.run_id,
912
+ checkpoint: packet.checkpoint,
913
+ resume_token: packet.resume_token,
914
+ decision,
915
+ summary: input.summary || `TODO: explain checkpoint decision ${decision}.`,
916
+ payload: input.payload || templatePayloadFor(packet, decision),
917
+ reasons: input.reasons || ["TODO: replace with concrete reason(s)."],
918
+ continue_with_stage: continueStage,
919
+ source: {
920
+ kind: input.source_kind || "codex"
921
+ },
922
+ created_at: input.created_at || timestamp()
923
+ });
924
+ }
925
+ function checkpointSummaryFromState(state, engineStatePath) {
926
+ const history = state.checkpoint_history || [];
927
+ const packets = history.filter((entry) => entry.packet);
928
+ const responses = history.filter((entry) => entry.response);
929
+ const duplicateResponses = (state.events || []).filter((event) => event.kind === "checkpoint.response.duplicate");
930
+ const latestPacketEntry = [...history].reverse().find((entry) => entry.packet);
931
+ const latestResponseEntry = [...history].reverse().find((entry) => entry.response);
932
+ const latestPacket = state.checkpoint_packet || latestPacketEntry?.packet;
933
+ const latestResponse = latestResponseEntry?.response;
934
+ const latestResumeToken = latestPacket?.resume_token || null;
935
+ const latestResponseToken = latestResponse?.resume_token || null;
936
+ const tokenMatches = latestResumeToken && latestResponseToken ? latestResumeToken === latestResponseToken : latestResumeToken || latestResponseToken ? false : null;
937
+ return compactRecord({
938
+ pending: Boolean(state.checkpoint_packet),
939
+ packet_count: packets.length,
940
+ response_count: responses.length,
941
+ duplicate_response_count: duplicateResponses.length,
942
+ latest_checkpoint: state.checkpoint_packet?.checkpoint || latestResponse?.checkpoint || state.last_checkpoint || null,
943
+ latest_stage: state.checkpoint_packet?.stage || latestResponse?.continue_with_stage || state.current_stage || null,
944
+ latest_kind: state.checkpoint_packet?.kind || latestPacket?.kind || null,
945
+ latest_decision: latestResponse?.decision || null,
946
+ latest_packet_summary: latestPacket?.summary || null,
947
+ latest_response_summary: latestResponse?.summary || null,
948
+ latest_resume_token: latestResumeToken,
949
+ latest_response_token: latestResponseToken,
950
+ token_matches: tokenMatches,
951
+ last_packet_at: latestPacketEntry?.ts || null,
952
+ last_response_at: latestResponseEntry?.ts || null,
953
+ state_paths: statePathsForRunState(state, engineStatePath)
954
+ });
955
+ }
956
+ function isDuplicateCheckpointResponse(state, response) {
957
+ const identity = checkpointResponseIdentity(response);
958
+ return (state.checkpoint_history || []).some((entry) => entry.response ? checkpointResponseIdentity(entry.response) === identity : false);
959
+ }
960
+ function checkpointResponseIdentity(response) {
961
+ const logicalResponse = compactRecord({
962
+ run_id: response.run_id,
963
+ checkpoint: response.checkpoint,
964
+ resume_token: response.resume_token,
965
+ decision: response.decision,
966
+ summary: response.summary,
967
+ payload: response.payload,
968
+ reasons: response.reasons,
969
+ continue_with_stage: response.continue_with_stage,
970
+ source: response.source
971
+ });
972
+ return import_node_crypto.default.createHash("sha256").update(stableJson(logicalResponse)).digest("hex").slice(0, 24);
973
+ }
974
+ function authorPacketPayloadFromCheckpointResponse(response) {
975
+ if (response.decision !== "author_packet") return null;
976
+ const payload = recordValue(response.payload);
977
+ if (!payload) return null;
978
+ const nested = recordValue(payload.author_packet);
979
+ const candidate = nested || payload;
980
+ if (!nonEmptyString(candidate.proof_plan) || !nonEmptyString(candidate.capture_script)) return null;
981
+ return candidate;
982
+ }
983
+ function proofContractFromAuthorCheckpointResponse(response, packet, payload) {
984
+ const refinedInputs = recordValue(payload.refined_inputs) || {};
985
+ return compactRecord({
986
+ version: "riddle-proof.proof-contract.v1",
987
+ checkpoint: packet.checkpoint,
988
+ source_response: compactRecord({
989
+ run_id: response.run_id,
990
+ checkpoint: response.checkpoint,
991
+ resume_token: response.resume_token,
992
+ decision: response.decision,
993
+ summary: response.summary,
994
+ created_at: response.created_at
995
+ }),
996
+ proof_plan: nonEmptyString(payload.proof_plan),
997
+ capture_script: nonEmptyString(payload.capture_script),
998
+ artifact_contract: jsonCloneRecord(payload.artifact_contract),
999
+ assertions: jsonCloneValue(payload.assertions),
1000
+ baseline_understanding: jsonCloneRecord(payload.baseline_understanding) || jsonCloneRecord(payload.recon_baseline_understanding) || jsonCloneRecord(packet.state_excerpt?.recon_baseline_understanding),
1001
+ route_assumptions: compactRecord({
1002
+ server_path: nonEmptyString(refinedInputs.server_path) || nonEmptyString(payload.server_path) || nonEmptyString(packet.state_excerpt?.server_path),
1003
+ wait_for_selector: nonEmptyString(refinedInputs.wait_for_selector) || nonEmptyString(payload.wait_for_selector) || nonEmptyString(packet.state_excerpt?.wait_for_selector),
1004
+ reference: nonEmptyString(refinedInputs.reference) || nonEmptyString(payload.reference),
1005
+ expected_path: nonEmptyString(payload.expected_path) || nonEmptyString(refinedInputs.expected_path)
1006
+ }),
1007
+ stop_condition: nonEmptyString(payload.stop_condition),
1008
+ rationale: jsonCloneValue(payload.rationale),
1009
+ verdict_dimensions: jsonCloneRecord(payload.verdict_dimensions),
1010
+ payload: jsonCloneRecord(payload),
1011
+ created_at: timestamp()
1012
+ });
1013
+ }
1014
+
1015
+ // src/run-card.ts
1016
+ var RIDDLE_PROOF_RUN_CARD_VERSION = "riddle-proof.run-card.v1";
1017
+ function elapsedMs(start, end) {
1018
+ const startMs = start ? Date.parse(start) : NaN;
1019
+ const endMs = end ? Date.parse(end) : NaN;
1020
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
1021
+ return Math.max(0, endMs - startMs);
1022
+ }
1023
+ function jsonCloneRecord2(value) {
1024
+ const record = recordValue(value);
1025
+ if (!record) return void 0;
1026
+ try {
1027
+ return JSON.parse(JSON.stringify(record));
1028
+ } catch {
1029
+ return { ...record };
1030
+ }
1031
+ }
1032
+ function compactText2(value, limit = 600) {
1033
+ const text = nonEmptyString(value);
1034
+ if (!text) return void 0;
1035
+ return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
1036
+ }
1037
+ function numericValue(value) {
1038
+ const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
1039
+ return Number.isFinite(number) ? number : void 0;
1040
+ }
1041
+ function eventDetails(event) {
1042
+ return recordValue(recordValue(event)?.details) || {};
1043
+ }
1044
+ function collectRunnerMetrics(details) {
1045
+ const metrics = [];
1046
+ const adapterDetails = recordValue(details.adapter_details);
1047
+ const direct = recordValue(adapterDetails?.runner_metrics);
1048
+ if (direct) metrics.push(direct);
1049
+ const attempts = Array.isArray(adapterDetails?.attempt_summaries) ? adapterDetails.attempt_summaries : [];
1050
+ for (const attempt of attempts) {
1051
+ const attemptMetrics = recordValue(recordValue(attempt)?.runner_metrics);
1052
+ if (attemptMetrics) metrics.push(attemptMetrics);
1053
+ }
1054
+ return metrics;
1055
+ }
1056
+ function observabilityFrom(state) {
1057
+ const engineEvents = state.events.filter((event) => event.kind === "engine.result").map((event) => ({ event, details: eventDetails(event) }));
1058
+ const agentEvents = state.events.filter((event) => event.kind.startsWith("agent.")).map((event) => ({ event, details: eventDetails(event) })).filter(({ details }) => numericValue(details.duration_ms) !== void 0);
1059
+ const retryEvents = state.events.filter((event) => /retry|recovery/i.test(event.kind) || /retry|recovery/i.test(event.summary || "")).slice(-8);
1060
+ const runnerMetrics = agentEvents.flatMap(({ details }) => collectRunnerMetrics(details));
1061
+ const promptChars = runnerMetrics.map((metrics) => numericValue(metrics.prompt_chars)).filter((value) => value !== void 0);
1062
+ const sum = (values) => values.reduce((total, value) => total + (value ?? 0), 0);
1063
+ const recentEngineTimings = engineEvents.slice(-8).map(({ event, details }) => compactRecord({
1064
+ checkpoint: event.checkpoint || null,
1065
+ stage: event.stage || null,
1066
+ duration_ms: numericValue(details.duration_ms),
1067
+ ok: details.ok ?? null
1068
+ }));
1069
+ const recentAgentTimings = agentEvents.slice(-8).map(({ event, details }) => {
1070
+ const metrics = collectRunnerMetrics(details);
1071
+ const localPromptChars = metrics.map((item) => numericValue(item.prompt_chars)).filter((value) => value !== void 0);
1072
+ return compactRecord({
1073
+ kind: event.kind,
1074
+ checkpoint: event.checkpoint || null,
1075
+ stage: event.stage || null,
1076
+ duration_ms: numericValue(details.duration_ms),
1077
+ prompt_chars: localPromptChars.length ? Math.max(...localPromptChars) : void 0,
1078
+ attempt_count: numericValue(recordValue(details.adapter_details)?.attempt_count)
1079
+ });
1080
+ });
1081
+ return compactRecord({
1082
+ engine_call_count: engineEvents.length,
1083
+ agent_call_count: agentEvents.length,
1084
+ engine_total_ms: sum(engineEvents.map(({ details }) => numericValue(details.duration_ms))),
1085
+ agent_total_ms: sum(agentEvents.map(({ details }) => numericValue(details.duration_ms))),
1086
+ max_agent_prompt_chars: promptChars.length ? Math.max(...promptChars) : void 0,
1087
+ total_agent_prompt_chars: promptChars.length ? sum(promptChars) : void 0,
1088
+ recent_engine_timings: recentEngineTimings.length ? recentEngineTimings : void 0,
1089
+ recent_agent_timings: recentAgentTimings.length ? recentAgentTimings : void 0,
1090
+ retry_event_count: retryEvents.length,
1091
+ recent_retry_reasons: retryEvents.length ? retryEvents.map((event) => compactRecord({
1092
+ kind: event.kind,
1093
+ checkpoint: event.checkpoint || null,
1094
+ stage: event.stage || null,
1095
+ summary: compactText2(event.summary, 240)
1096
+ })) : void 0
1097
+ });
1098
+ }
1099
+ function visualDeltaFrom(input) {
1100
+ const fullState = input.fullRiddleState || {};
1101
+ const bundle = recordValue(fullState.evidence_bundle);
1102
+ const after = recordValue(bundle?.after);
1103
+ const afterDelta = recordValue(after?.visual_delta);
1104
+ if (afterDelta && Object.keys(afterDelta).length) return afterDelta;
1105
+ const requestDelta = recordValue(recordValue(fullState.proof_assessment_request)?.visual_delta);
1106
+ if (requestDelta && Object.keys(requestDelta).length) return requestDelta;
1107
+ const packetDelta = recordValue(input.runState.checkpoint_packet?.evidence_excerpt?.visual_delta);
1108
+ return packetDelta && Object.keys(packetDelta).length ? packetDelta : void 0;
1109
+ }
1110
+ function artifactsFrom(input) {
1111
+ const packetArtifacts = input.runState.checkpoint_packet?.artifacts;
1112
+ if (packetArtifacts?.length) return packetArtifacts.slice(0, 12);
1113
+ const fullState = input.fullRiddleState || {};
1114
+ const artifacts = [];
1115
+ for (const role of ["before", "prod", "after"]) {
1116
+ const url = nonEmptyString(fullState[`${role}_cdn`]) || nonEmptyString(input.runState[`${role}_artifact_url`]);
1117
+ if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
1118
+ }
1119
+ return artifacts.length ? artifacts : void 0;
1120
+ }
1121
+ function viewportMatrixFrom(input) {
1122
+ const fullState = input.fullRiddleState || {};
1123
+ const bundle = recordValue(fullState.evidence_bundle);
1124
+ const fromBundle = recordValue(bundle?.viewport_matrix);
1125
+ if (fromBundle && Object.keys(fromBundle).length) return jsonCloneRecord2(fromBundle);
1126
+ const fromRequest = recordValue(recordValue(fullState.proof_assessment_request)?.viewport_matrix);
1127
+ if (fromRequest && Object.keys(fromRequest).length) return jsonCloneRecord2(fromRequest);
1128
+ const fromState = recordValue(fullState.viewport_matrix_status) || recordValue(input.runState.viewport_matrix_status);
1129
+ return fromState && Object.keys(fromState).length ? jsonCloneRecord2(fromState) : void 0;
1130
+ }
1131
+ function ownerFor(state) {
1132
+ if (state.status === "awaiting_checkpoint") {
1133
+ const role = nonEmptyString(state.checkpoint_packet?.routing_hint?.suggested_role);
1134
+ return role || "supervising_agent";
1135
+ }
1136
+ if (state.status === "running") return "engine";
1137
+ if (state.status === "blocked" || state.status === "failed") return "human_or_operator";
1138
+ return "none";
1139
+ }
1140
+ function actionFor(state) {
1141
+ if (state.status === "awaiting_checkpoint") return state.checkpoint_packet?.question || "Answer the pending checkpoint.";
1142
+ if (state.status === "running") return "Continue the current Riddle Proof stage.";
1143
+ 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.";
1144
+ if (state.status === "ready_to_ship") return "Ship is held by policy; review PR/ship policy before advancing.";
1145
+ return "No next action; run is terminal.";
1146
+ }
1147
+ function evidenceIssueCode(input) {
1148
+ const packetIssue = nonEmptyString(input.runState.checkpoint_packet?.evidence_excerpt?.evidence_issue_code);
1149
+ if (packetIssue) return packetIssue;
1150
+ const assessmentIssue = nonEmptyString(recordValue(input.fullRiddleState?.proof_assessment)?.evidence_issue_code);
1151
+ if (assessmentIssue) return assessmentIssue;
1152
+ const delta = visualDeltaFrom(input);
1153
+ const status = nonEmptyString(delta?.status);
1154
+ if (status === "unmeasured") {
1155
+ const reason = `${nonEmptyString(delta?.reason) || ""}
1156
+ ${input.runState.blocker?.message || ""}`.toLowerCase();
1157
+ return reason.includes("fetch") || reason.includes("allowlist") || reason.includes("registered domain") || reason.includes("high risk") || reason.includes("comparator") ? "comparator_fetch_blocked" : "visual_delta_unmeasured";
1158
+ }
1159
+ if (status === "measured" && delta?.passed === false) return "semantic_proof_failed";
1160
+ return void 0;
1161
+ }
1162
+ function createRiddleProofRunCard(state, input = {}) {
1163
+ const at = input.at || (/* @__PURE__ */ new Date()).toISOString();
1164
+ const fullState = input.fullRiddleState || {};
1165
+ const packet = state.checkpoint_packet;
1166
+ const latestEvent = state.events[state.events.length - 1];
1167
+ const bundle = recordValue(fullState.evidence_bundle);
1168
+ 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);
1169
+ const required = jsonCloneRecord2(recordValue(artifactContract)?.required);
1170
+ const statePaths = input.state_paths || state.state_paths || statePathsForRunState(state);
1171
+ const visualDelta = visualDeltaFrom({ fullRiddleState: fullState, runState: state });
1172
+ const artifacts = artifactsFrom({ fullRiddleState: fullState, runState: state });
1173
+ const viewportMatrix = viewportMatrixFrom({ fullRiddleState: fullState, runState: state });
1174
+ return {
1175
+ version: RIDDLE_PROOF_RUN_CARD_VERSION,
1176
+ run_id: state.run_id || "unknown",
1177
+ status: state.status,
1178
+ goal: compactRecord({
1179
+ repo: state.request.repo || nonEmptyString(fullState.repo),
1180
+ branch: state.request.branch || nonEmptyString(fullState.branch),
1181
+ change_request: state.request.change_request || nonEmptyString(fullState.change_request),
1182
+ verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
1183
+ success_criteria: state.request.success_criteria
1184
+ }),
1185
+ durable_state: compactRecord({
1186
+ ...statePaths,
1187
+ worktree_path: state.worktree_path || nonEmptyString(fullState.after_worktree) || null,
1188
+ branch: state.branch || nonEmptyString(fullState.branch) || null
1189
+ }),
1190
+ current_phase: compactRecord({
1191
+ stage: state.current_stage ?? null,
1192
+ checkpoint: state.last_checkpoint ?? packet?.checkpoint ?? null,
1193
+ latest_event: latestEvent?.kind ?? null,
1194
+ elapsed_ms: elapsedMs(state.created_at, at),
1195
+ stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
1196
+ iterations: state.iterations
1197
+ }),
1198
+ owner_next_action: compactRecord({
1199
+ owner: ownerFor(state),
1200
+ action: actionFor(state),
1201
+ checkpoint_kind: packet?.kind || null,
1202
+ allowed_decisions: packet?.allowed_decisions,
1203
+ retryable: state.status === "running" || state.status === "awaiting_checkpoint",
1204
+ reason: state.blocker?.code || packet?.summary || latestEvent?.summary || null
1205
+ }),
1206
+ evidence_contract: compactRecord({
1207
+ verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
1208
+ required,
1209
+ artifact_contract: artifactContract,
1210
+ proof_plan: compactText2(state.proof_contract?.proof_plan || fullState.proof_plan, 600),
1211
+ stop_condition: compactText2(state.proof_contract?.stop_condition, 400)
1212
+ }),
1213
+ latest_evidence: compactRecord({
1214
+ before_url: nonEmptyString(fullState.before_cdn) || state.before_artifact_url || null,
1215
+ prod_url: nonEmptyString(fullState.prod_cdn) || state.prod_artifact_url || null,
1216
+ after_url: nonEmptyString(fullState.after_cdn) || state.after_artifact_url || null,
1217
+ visual_delta: visualDelta || null,
1218
+ evidence_issue_code: evidenceIssueCode({ fullRiddleState: fullState, runState: state }) || null,
1219
+ proof_evidence_present: fullState.proof_evidence_present === true || Boolean(bundle?.proof_evidence || bundle?.proof_evidence_sample),
1220
+ viewport_matrix: viewportMatrix,
1221
+ artifacts
1222
+ }),
1223
+ observability: observabilityFrom(state),
1224
+ stop_condition: compactRecord({
1225
+ status: state.status,
1226
+ terminal: isTerminalStatus(state.status),
1227
+ blocker_code: state.blocker?.code || null,
1228
+ blocker_message: state.blocker?.message || null,
1229
+ proof_decision: state.proof_decision,
1230
+ merge_recommendation: state.merge_recommendation,
1231
+ monitor_should_continue: !isTerminalStatus(state.status)
1232
+ }),
1233
+ updated_at: state.updated_at
1234
+ };
1235
+ }
1236
+
1237
+ // src/state.ts
1238
+ var RIDDLE_PROOF_RUN_STATE_VERSION = "riddle-proof.run-state.v1";
1239
+ function timestamp2() {
1240
+ return (/* @__PURE__ */ new Date()).toISOString();
1241
+ }
1242
+ function createRunId(createdAt) {
1243
+ const stamp = createdAt.replace(/\D/g, "").slice(0, 14) || "unknown";
1244
+ const entropy = Math.random().toString(36).slice(2, 8) || "run";
1245
+ return `rp_${stamp}_${entropy}`;
1246
+ }
1247
+ function elapsedMs2(start, end) {
1248
+ const startMs = start ? Date.parse(start) : NaN;
1249
+ const endMs = end ? Date.parse(end) : NaN;
1250
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
1251
+ return Math.max(0, endMs - startMs);
1252
+ }
1253
+ function normalizePrStatus2(value) {
1254
+ const status = nonEmptyString(value)?.toLowerCase();
1255
+ if (status === "merged") return "merged";
1256
+ if (status === "open") return "open";
1257
+ if (status === "closed") return "closed";
1258
+ if (status === "not_found" || status === "not-found") return "not_found";
1259
+ if (status === "unavailable") return "unavailable";
1260
+ return status || "unknown";
1261
+ }
1262
+ function normalizePrLifecycleState(input, checkedAt = timestamp2()) {
1263
+ const value = recordValue(input);
1264
+ if (!value) return void 0;
1265
+ const cleanup = recordValue(value.cleanup);
1266
+ const mergeCommit = nonEmptyString(value.merge_commit) || nonEmptyString(value.mergeCommit) || nonEmptyString(recordValue(value.mergeCommit)?.oid);
1267
+ return compactRecord({
1268
+ status: normalizePrStatus2(value.status || value.state),
1269
+ pr_url: nonEmptyString(value.pr_url) || nonEmptyString(value.prUrl) || nonEmptyString(value.url),
1270
+ pr_number: nonEmptyString(value.pr_number) || nonEmptyString(value.prNumber) || (typeof value.number === "number" ? String(value.number) : void 0),
1271
+ repo: nonEmptyString(value.repo) || nonEmptyString(value.repository),
1272
+ head_branch: nonEmptyString(value.head_branch) || nonEmptyString(value.headBranch) || nonEmptyString(value.headRefName),
1273
+ base_branch: nonEmptyString(value.base_branch) || nonEmptyString(value.baseBranch) || nonEmptyString(value.baseRefName),
1274
+ merge_commit: mergeCommit,
1275
+ merged_at: nonEmptyString(value.merged_at) || nonEmptyString(value.mergedAt),
1276
+ closed_at: nonEmptyString(value.closed_at) || nonEmptyString(value.closedAt),
1277
+ checked_at: nonEmptyString(value.checked_at) || nonEmptyString(value.checkedAt) || checkedAt,
1278
+ source: nonEmptyString(value.source),
1279
+ next_action: nonEmptyString(value.next_action) || nonEmptyString(value.nextAction),
1280
+ cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
1281
+ });
1282
+ }
1283
+ function normalizeIntegrationContext(input, fallbackSource) {
1284
+ const value = recordValue(input);
1285
+ if (!value) {
1286
+ return fallbackSource ? { source: fallbackSource } : void 0;
1287
+ }
1288
+ const metadata = recordValue(value.metadata);
1289
+ return compactRecord({
1290
+ source: nonEmptyString(value.source) || fallbackSource,
1291
+ channel_id: nonEmptyString(value.channel_id),
1292
+ thread_id: nonEmptyString(value.thread_id),
1293
+ message_id: nonEmptyString(value.message_id),
1294
+ source_url: nonEmptyString(value.source_url),
1295
+ metadata: metadata && Object.keys(metadata).length ? metadata : void 0
1296
+ });
1297
+ }
1298
+ function normalizeRunParams(input) {
1299
+ return compactRecord({
1300
+ repo: input.repo,
1301
+ branch: input.branch,
1302
+ change_request: input.change_request,
1303
+ commit_message: input.commit_message,
1304
+ prod_url: input.prod_url,
1305
+ capture_script: input.capture_script,
1306
+ success_criteria: input.success_criteria,
1307
+ assertions: input.assertions,
1308
+ verification_mode: input.verification_mode,
1309
+ resume_session: input.resume_session,
1310
+ target_image_url: input.target_image_url,
1311
+ target_image_hash: input.target_image_hash,
1312
+ viewport_matrix: input.viewport_matrix,
1313
+ deterministic_setup: input.deterministic_setup,
1314
+ reference: input.reference,
1315
+ base_branch: input.base_branch,
1316
+ before_ref: input.before_ref,
1317
+ allow_static_preview_fallback: input.allow_static_preview_fallback,
1318
+ context: input.context,
1319
+ reviewer: input.reviewer,
1320
+ mode: input.mode,
1321
+ implementation_mode: input.implementation_mode,
1322
+ require_diff: input.require_diff,
1323
+ allow_code_changes: input.allow_code_changes,
1324
+ build_command: input.build_command,
1325
+ build_output: input.build_output,
1326
+ server_image: input.server_image,
1327
+ server_command: input.server_command,
1328
+ server_port: input.server_port,
1329
+ server_path: input.server_path,
1330
+ use_auth: input.use_auth,
1331
+ auth_localStorage_json: input.auth_localStorage_json,
1332
+ auth_cookies_json: input.auth_cookies_json,
1333
+ auth_headers_json: input.auth_headers_json,
1334
+ color_scheme: input.color_scheme,
1335
+ wait_for_selector: input.wait_for_selector,
1336
+ ship_mode: input.ship_mode,
1337
+ leave_draft: input.leave_draft,
1338
+ engine_state_path: input.engine_state_path,
1339
+ harness_state_path: input.harness_state_path,
1340
+ riddle_engine_module_url: input.riddle_engine_module_url,
1341
+ max_iterations: input.max_iterations,
1342
+ auto_approve: input.auto_approve,
1343
+ dry_run: input.dry_run,
1344
+ integration_context: normalizeIntegrationContext(input.integration_context)
1345
+ });
1346
+ }
1347
+ function createRunState(input) {
1348
+ const createdAt = input.created_at || timestamp2();
1349
+ return compactRecord({
1350
+ version: RIDDLE_PROOF_RUN_STATE_VERSION,
1351
+ run_id: input.run_id || createRunId(createdAt),
1352
+ state_path: input.state_path,
1353
+ worktree_path: input.worktree_path,
1354
+ branch: input.branch || input.request.branch,
1355
+ current_stage: input.current_stage ?? null,
1356
+ stage_started_at: input.stage_started_at ?? null,
1357
+ status: input.status || "running",
1358
+ created_at: createdAt,
1359
+ updated_at: input.updated_at || createdAt,
1360
+ request: normalizeRunParams(input.request),
1361
+ iterations: input.iterations ?? 0,
1362
+ last_checkpoint: input.last_checkpoint ?? null,
1363
+ checkpoint_packet: input.checkpoint_packet,
1364
+ checkpoint_summary: input.checkpoint_summary,
1365
+ state_paths: input.state_paths,
1366
+ proof_contract: input.proof_contract,
1367
+ run_card: input.run_card,
1368
+ checkpoint_history: input.checkpoint_history,
1369
+ events: input.events ? [...input.events] : []
1370
+ });
1371
+ }
1372
+ function appendRunEvent(state, input) {
1373
+ const event = {
1374
+ ts: input.ts || timestamp2(),
1375
+ kind: input.kind,
1376
+ checkpoint: input.checkpoint,
1377
+ stage: input.stage,
1378
+ summary: input.summary,
1379
+ details: input.details
1380
+ };
1381
+ state.events.push(compactRecord({
1382
+ ts: event.ts,
1383
+ kind: event.kind,
1384
+ checkpoint: event.checkpoint,
1385
+ stage: event.stage,
1386
+ summary: event.summary,
1387
+ details: event.details
1388
+ }));
1389
+ if (input.checkpoint !== void 0) state.last_checkpoint = input.checkpoint;
1390
+ if (input.stage !== void 0) {
1391
+ if (state.current_stage !== input.stage) state.stage_started_at = event.ts;
1392
+ state.current_stage = input.stage;
1393
+ }
1394
+ state.updated_at = event.ts;
1395
+ return state;
1396
+ }
1397
+ function appendStageHeartbeat(state, input) {
1398
+ const at = input.ts || timestamp2();
1399
+ return appendRunEvent(state, {
1400
+ ts: at,
1401
+ kind: "stage.heartbeat",
1402
+ checkpoint: input.checkpoint || `${input.stage}_heartbeat`,
1403
+ stage: input.stage,
1404
+ summary: input.summary || `${input.stage} stage is active.`,
1405
+ details: compactRecord({
1406
+ elapsed_ms: elapsedMs2(state.created_at, at),
1407
+ stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
1408
+ wait_reason: input.wait_reason,
1409
+ blocker: input.blocker,
1410
+ ...input.details
1411
+ })
1412
+ });
1413
+ }
1414
+ function createRunStatusSnapshot(state, at = timestamp2()) {
1415
+ const latestEvent = state.events[state.events.length - 1];
1416
+ const runId = state.run_id || "unknown";
1417
+ return compactRecord({
1418
+ run_id: runId,
1419
+ status: state.status,
1420
+ is_terminal: isTerminalStatus(state.status),
1421
+ monitor_should_continue: !isTerminalStatus(state.status),
1422
+ current_stage: state.current_stage ?? null,
1423
+ state_path: state.state_path ?? null,
1424
+ worktree_path: state.worktree_path ?? null,
1425
+ branch: state.branch ?? null,
1426
+ pr_url: state.pr_url ?? null,
1427
+ pr_branch: state.pr_branch ?? null,
1428
+ pr_state: state.pr_state,
1429
+ ci_status: state.ci_status,
1430
+ ship_commit: state.ship_commit,
1431
+ ship_remote_head: state.ship_remote_head,
1432
+ merge_commit: state.merge_commit,
1433
+ merged_at: state.merged_at,
1434
+ proof_comment_url: state.proof_comment_url,
1435
+ cleanup_report: state.cleanup_report,
1436
+ iterations: state.iterations,
1437
+ last_checkpoint: state.last_checkpoint ?? null,
1438
+ updated_at: state.updated_at,
1439
+ elapsed_ms: elapsedMs2(state.created_at, at),
1440
+ stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
1441
+ blocker: state.blocker,
1442
+ checkpoint_packet: state.checkpoint_packet,
1443
+ checkpoint_summary: state.checkpoint_summary,
1444
+ state_paths: state.state_paths,
1445
+ proof_contract: state.proof_contract,
1446
+ run_card: state.run_card || createRiddleProofRunCard(state, { at }),
1447
+ viewport_matrix_status: state.viewport_matrix_status,
1448
+ latest_event: latestEvent
1449
+ });
1450
+ }
1451
+ function setRunStatus(state, status, at = timestamp2()) {
1452
+ state.status = status;
1453
+ state.ok = status !== "blocked" && status !== "failed";
1454
+ state.updated_at = at;
1455
+ return state;
1456
+ }
1457
+ function applyPrLifecycleState(state, input, at = timestamp2()) {
1458
+ const prState = normalizePrLifecycleState(input, at);
1459
+ if (!prState) return state;
1460
+ state.pr_state = prState;
1461
+ if (prState.pr_url) state.pr_url = prState.pr_url;
1462
+ if (prState.head_branch) state.pr_branch = prState.head_branch;
1463
+ if (prState.merge_commit) state.merge_commit = prState.merge_commit;
1464
+ if (prState.merged_at) state.merged_at = prState.merged_at;
1465
+ if (prState.cleanup) state.cleanup_report = prState.cleanup;
1466
+ if (prState.status === "merged") {
1467
+ state.finalized = true;
1468
+ state.status = "completed";
1469
+ state.ok = true;
1470
+ }
1471
+ state.updated_at = at;
1472
+ return state;
1473
+ }
1474
+ // Annotate the CommonJS export names for ESM import in node:
1475
+ 0 && (module.exports = {
1476
+ RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
1477
+ RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
1478
+ RIDDLE_PROOF_RUN_CARD_VERSION,
1479
+ RIDDLE_PROOF_RUN_STATE_VERSION,
1480
+ appendRunEvent,
1481
+ appendStageHeartbeat,
1482
+ applyPrLifecycleState,
1483
+ applyTerminalMetadata,
1484
+ authorPacketPayloadFromCheckpointResponse,
1485
+ buildAuthorCheckpointPacket,
1486
+ buildCheckpointPacketForEngineResult,
1487
+ buildProofAssessmentCheckpointPacket,
1488
+ buildStageCheckpointPacket,
1489
+ checkpointResponseIdentity,
1490
+ checkpointSummaryFromState,
1491
+ compactRecord,
1492
+ createCheckpointResponseTemplate,
1493
+ createRiddleProofRunCard,
1494
+ createRunResult,
1495
+ createRunState,
1496
+ createRunStatusSnapshot,
1497
+ isDuplicateCheckpointResponse,
1498
+ isSuccessfulStatus,
1499
+ isTerminalStatus,
1500
+ nonEmptyString,
1501
+ normalizeCheckpointResponse,
1502
+ normalizeIntegrationContext,
1503
+ normalizePrLifecycleState,
1504
+ normalizeRunParams,
1505
+ normalizeTerminalMetadata,
1506
+ proofContractFromAuthorCheckpointResponse,
1507
+ recordValue,
1508
+ setRunStatus,
1509
+ statePathsForRunState
1510
+ });