@astrosheep/keiyaku 2.9.12 → 2.9.13

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 (212) hide show
  1. package/README.md +22 -18
  2. package/build/.tsbuildinfo +1 -1
  3. package/build/agents/call-terms.js +1 -0
  4. package/build/agents/providers/claude-agent-sdk/adapter.js +2 -2
  5. package/build/cli/commands/akuma/akuma/handler.js +2 -1
  6. package/build/cli/commands/akuma/akuma/meta.js +4 -3
  7. package/build/cli/commands/akuma/catalog.js +2 -0
  8. package/build/cli/commands/akuma/list/handler.js +1 -1
  9. package/build/cli/commands/akuma/list/meta-list.js +12 -0
  10. package/build/cli/commands/akuma/list/meta-ls.js +2 -2
  11. package/build/cli/commands/akuma.js +5 -0
  12. package/build/cli/commands/contract/amend/meta.js +4 -3
  13. package/build/cli/commands/contract/arc/meta.js +2 -0
  14. package/build/cli/commands/contract/audit/handler.js +28 -2
  15. package/build/cli/commands/contract/audit/meta.js +4 -3
  16. package/build/cli/commands/contract/petition/handler.js +2 -1
  17. package/build/cli/commands/contract/petition/meta.js +2 -2
  18. package/build/cli/commands/contract/renew/handler.js +44 -3
  19. package/build/cli/commands/contract/renew/meta.js +5 -4
  20. package/build/cli/commands/metadata.js +12 -9
  21. package/build/cli/commands/projection/call/handler.js +1 -1
  22. package/build/cli/commands/projection/call/meta.js +1 -1
  23. package/build/cli/commands/projection/catalog.js +2 -2
  24. package/build/cli/commands/projection/{revive → fork}/handler.js +10 -5
  25. package/build/cli/commands/projection/fork/meta.js +12 -0
  26. package/build/cli/commands/projection/history/handler.js +46 -2
  27. package/build/cli/commands/projection/history/meta.js +3 -3
  28. package/build/cli/commands/projection/kill/meta.js +2 -2
  29. package/build/cli/commands/projection/status/handler.js +29 -13
  30. package/build/cli/commands/projection/status/meta.js +14 -3
  31. package/build/cli/commands/projection/tell/handler.js +8 -4
  32. package/build/cli/commands/projection/tell/meta.js +1 -1
  33. package/build/cli/commands/projection/wait/handler.js +45 -20
  34. package/build/cli/commands/projection/wait/meta.js +1 -1
  35. package/build/cli/commands/shared.js +1 -1
  36. package/build/cli/commands/system/catalog.js +2 -0
  37. package/build/cli/commands/task/add/handler.js +28 -12
  38. package/build/cli/commands/task/add/meta.js +18 -6
  39. package/build/cli/commands/task/catalog.js +2 -0
  40. package/build/cli/commands/task/compose/handler.js +2 -2
  41. package/build/cli/commands/task/compose/meta.js +2 -2
  42. package/build/cli/commands/task/doctor/handler.js +2 -3
  43. package/build/cli/commands/task/doctor/meta.js +2 -2
  44. package/build/cli/commands/task/done/meta.js +2 -2
  45. package/build/cli/commands/task/drop/handler.js +7 -2
  46. package/build/cli/commands/task/drop/meta.js +6 -3
  47. package/build/cli/commands/task/hold/meta.js +2 -2
  48. package/build/cli/commands/task/log/meta.js +2 -2
  49. package/build/cli/commands/task/ls/meta.js +2 -2
  50. package/build/cli/commands/task/note/handler.js +6 -0
  51. package/build/cli/commands/task/note/meta.js +11 -0
  52. package/build/cli/commands/task/resume/meta.js +2 -2
  53. package/build/cli/commands/task/shared.js +29 -15
  54. package/build/cli/commands/task/show/meta.js +2 -2
  55. package/build/cli/commands/task/start/meta.js +2 -2
  56. package/build/cli/commands/task/stop/meta.js +2 -2
  57. package/build/cli/commands/task/update/meta.js +3 -2
  58. package/build/cli/commands/verification/handler.js +43 -0
  59. package/build/cli/commands/verification/meta.js +13 -0
  60. package/build/cli/completion.js +16 -13
  61. package/build/cli/flags.js +43 -11
  62. package/build/cli/help.js +29 -30
  63. package/build/cli/index.js +6 -5
  64. package/build/cli/parse-flags.js +39 -0
  65. package/build/cli/parse-metadata.js +5 -2
  66. package/build/cli/parse-selectors.js +18 -0
  67. package/build/cli/parse.js +21 -8
  68. package/build/cli/render/arc.js +12 -3
  69. package/build/cli/render/audit.js +2 -2
  70. package/build/cli/render/call.js +4 -4
  71. package/build/cli/render/kanshi.js +122 -85
  72. package/build/cli/render/misc.js +2 -2
  73. package/build/cli/render/petition.js +16 -1
  74. package/build/cli/render/projection-history.js +17 -4
  75. package/build/cli/render/shared.js +5 -5
  76. package/build/cli/render/status-indicator.js +47 -0
  77. package/build/cli/render/status.js +106 -76
  78. package/build/cli/render/success-response.js +20 -5
  79. package/build/cli/render/task.js +6 -5
  80. package/build/cli/render/tell.js +10 -4
  81. package/build/cli/render/tool-command-normalization.js +137 -0
  82. package/build/cli/render/tool-presentation.js +2 -1
  83. package/build/cli/render/verification.js +23 -0
  84. package/build/cli/render/wait.js +101 -33
  85. package/build/cli/types.js +2 -1
  86. package/build/config/akuma-loader.js +21 -1
  87. package/build/config/settings/knobs.js +7 -1
  88. package/build/config/settings/schema.js +10 -5
  89. package/build/core/amend.js +102 -17
  90. package/build/core/arc.js +4 -4
  91. package/build/core/audit/candidate.js +10 -18
  92. package/build/core/audit/coordinates.js +12 -17
  93. package/build/core/audit/evidence.js +6 -4
  94. package/build/core/audit/facade.js +3 -3
  95. package/build/core/audit/report.js +1 -1
  96. package/build/core/bind-reconciliation.js +42 -23
  97. package/build/core/bind.js +182 -81
  98. package/build/core/call/call.js +6 -7
  99. package/build/core/call/context.js +43 -30
  100. package/build/core/call/execution.js +21 -6
  101. package/build/core/call/prompt.js +11 -42
  102. package/build/core/contract-carrier-runtime.js +209 -105
  103. package/build/core/contract-carrier.js +156 -73
  104. package/build/core/contract-view.js +42 -5
  105. package/build/core/contract.js +2 -1
  106. package/build/core/derived-replay.js +168 -35
  107. package/build/core/draft.js +9 -5
  108. package/build/core/forfeit.js +1 -1
  109. package/build/core/lifecycle-history.js +13 -0
  110. package/build/core/lifecycle-recovery.js +32 -27
  111. package/build/core/lifecycle-runner.js +14 -14
  112. package/build/core/log.js +1 -1
  113. package/build/core/outcome-base.js +2 -2
  114. package/build/core/projection/akuma-name.js +43 -0
  115. package/build/core/projection/generation/database.js +141 -79
  116. package/build/core/projection/generation/ledger.js +91 -0
  117. package/build/core/projection/generation/model.js +18 -13
  118. package/build/core/projection/generation/projection-generation-continuation.js +1 -1
  119. package/build/core/projection/generation/projection-generation-doorbell.js +88 -0
  120. package/build/core/projection/generation/projection-generation-execution.js +24 -0
  121. package/build/core/projection/generation/projection-generation-identity.js +4 -0
  122. package/build/core/projection/generation/projection-generation-launcher.js +72 -138
  123. package/build/core/projection/generation/projection-generation-process.js +16 -15
  124. package/build/core/projection/generation/projection-generation-runner.js +125 -79
  125. package/build/core/projection/generation/projection-generation-runtime.js +10 -61
  126. package/build/core/projection/generation/protocol.js +68 -0
  127. package/build/core/projection/generation/store.js +17 -7
  128. package/build/core/projection/generation/transitions.js +14 -14
  129. package/build/core/projection/index.js +5 -5
  130. package/build/core/projection/projection-core.js +6 -2
  131. package/build/core/projection/projection-execution-observer.js +1 -1
  132. package/build/core/projection/projection-history.js +7 -7
  133. package/build/core/projection/projection-kill.js +15 -6
  134. package/build/core/projection/projection-life-observer.js +8 -8
  135. package/build/core/projection/projection-mint.js +6 -8
  136. package/build/core/projection/projection-status-observation.js +77 -8
  137. package/build/core/projection/projection-status.js +151 -4
  138. package/build/core/projection/projection-wait.js +46 -27
  139. package/build/core/projection/projection-wake.js +27 -89
  140. package/build/core/projection/tell/launch-store.js +1 -1
  141. package/build/core/projection/tell/store.js +1 -1
  142. package/build/core/renew-build.js +204 -74
  143. package/build/core/renew-plan.js +34 -9
  144. package/build/core/renew-rewrite.js +56 -15
  145. package/build/core/renew.js +39 -35
  146. package/build/core/repository-ledger/accepted-fold-read.js +6 -3
  147. package/build/core/repository-ledger/codec.js +11 -5
  148. package/build/core/repository-ledger/current-state-store.js +13 -16
  149. package/build/core/repository-ledger/fold-repository.js +5 -6
  150. package/build/core/repository-ledger/identity.js +60 -0
  151. package/build/core/repository-ledger/inventory.js +3 -3
  152. package/build/core/repository-ledger/read-model.js +54 -6
  153. package/build/core/repository-ledger/write-transaction.js +9 -4
  154. package/build/core/run-control/connection-bound-close.js +41 -0
  155. package/build/core/run-control/detached-lease-bootstrap.js +208 -0
  156. package/build/core/run-control/detached-process.js +14 -0
  157. package/build/core/run-control/index.js +6 -0
  158. package/build/core/{process-group.js → run-control/process-tree.js} +1 -1
  159. package/build/core/run-control/runner-lease.js +172 -0
  160. package/build/core/{sqlite-process-lifetime-lock.js → run-control/sqlite-process-lifetime-lock.js} +4 -24
  161. package/build/core/seal.js +44 -32
  162. package/build/core/settlement/claim-delivery.js +22 -9
  163. package/build/core/settlement/claim.js +8 -6
  164. package/build/core/settlement/petition-claim-gates.js +9 -8
  165. package/build/core/settlement/petition-head-guard.js +5 -6
  166. package/build/core/settlement/petition-preview.js +21 -5
  167. package/build/core/settlement/petition.js +51 -17
  168. package/build/core/settlement/settlement.js +20 -15
  169. package/build/core/settlement/verdict.js +2 -2
  170. package/build/core/settlement/verification.js +492 -364
  171. package/build/core/status/board.js +184 -75
  172. package/build/core/status/drift.js +8 -10
  173. package/build/core/task/board.js +1 -0
  174. package/build/core/task/commands.js +25 -0
  175. package/build/core/task/compose.js +3 -2
  176. package/build/core/task/document.js +102 -39
  177. package/build/core/task/index.js +3 -3
  178. package/build/core/task/settlement-git.js +1 -4
  179. package/build/core/task/settlement-policy.js +27 -14
  180. package/build/core/task/source-board.js +1 -0
  181. package/build/core/task/task-bind-preparation.js +59 -9
  182. package/build/core/task/task-contract.js +2 -2
  183. package/build/core/task/task-store-repository.js +1 -0
  184. package/build/core/task/task.js +2 -2
  185. package/build/core/transcripts.js +4 -4
  186. package/build/core/verification-declaration.js +95 -0
  187. package/build/core/worktree-bootstrap.js +1 -1
  188. package/build/core/worktree-path.js +7 -11
  189. package/build/flow-error.js +9 -1
  190. package/build/generated/version.js +2 -2
  191. package/build/git/branches.js +41 -70
  192. package/build/git/commits.js +92 -21
  193. package/build/git/core.js +9 -161
  194. package/build/git/diff/preview.js +4 -4
  195. package/build/git/diff/read.js +4 -4
  196. package/build/git/diff/structured.js +5 -5
  197. package/build/git/process.js +229 -0
  198. package/build/git/refs.js +30 -5
  199. package/build/git/staging.js +39 -115
  200. package/build/git/streaming-batch.js +9 -16
  201. package/build/git/worktree.js +104 -91
  202. package/build/index.js +7 -0
  203. package/package.json +1 -1
  204. package/skills/keiyaku-akuma/SKILL.md +21 -20
  205. package/skills/keiyaku-task/SKILL.md +38 -4
  206. package/skills/keiyaku-workflow/SKILL.md +51 -11
  207. package/build/cli/commands/projection/revive/meta.js +0 -12
  208. package/build/core/projection/projection-life-protocol.js +0 -115
  209. package/build/core/projection/projection-runner-lock.js +0 -211
  210. package/build/core/projection/tell/database.js +0 -127
  211. package/build/core/settlement/verification-coordination.js +0 -305
  212. package/build/core/settlement/verification-supervisor.js +0 -275
@@ -1,426 +1,554 @@
1
- import { spawn } from "node:child_process";
2
- import { getConfig } from "../../config/env.js";
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ import { fileURLToPath } from "node:url";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { DatabaseSync } from "node:sqlite";
7
+ import { z } from "zod";
3
8
  import { assertSettingsKnobUsable } from "../../config/settings/disease.js";
4
9
  import { loadKeiyakuSettings } from "../../config/settings/loader.js";
5
- import { PROCESS_GROUP_KILL_GRACE_MS, ProcessTreeTerminationError, ownedProcessIdentity, ownedProcessIsLive, terminateOwnedProcess, terminateProcessGroup, } from "../process-group.js";
6
- import { VerificationCoordination } from "./verification-coordination.js";
7
- import { VERIFICATION_SUPERVISOR_PROTOCOL_VERSION, supervisorMessageSchema, verificationSupervisorArguments, } from "./verification-supervisor.js";
10
+ import { createUlid } from "../ids.js";
11
+ import { effectiveVerification } from "../lifecycle-history.js";
12
+ import { beginConnectionBoundRunnerClose, acquireRunnerLease, acquireRunnerLostProof, initializeRunnerLeaseDatabase, launchDetachedProcess, openDetachedLeaseBootstrap, observeRunnerLease, receiveDetachedLease, RUN_CONTROL_BOOTSTRAP_ENV, RunnerLeaseUnavailableError, terminateProcessGroup, } from "../run-control/index.js";
8
13
  const OUTPUT_TAIL_BYTES = 8_192;
9
- const COORDINATION_POLL_MS = 50;
10
- const COORDINATION_RECOVERY_MARGIN_MS = 60_000;
14
+ const RUN_WAIT_POLL_MS = 25;
15
+ const RUN_START_TIMEOUT_MS = 30_000;
16
+ const RUNTIME_DIRECTORY = [".keiyaku", "runtime"];
17
+ const VERIFICATION_RUN_SCHEMA_VERSION = 4;
18
+ const RUNNER_FAILURE_CODES = ["SPAWN_FAILED", "PROCESS_TERMINATED", "TIMED_OUT", "CANCELLED", "TREE_TERMINATION_FAILED", "RUNNER_LOST"];
19
+ export class VerificationRunFormatError extends Error {
20
+ code = "VERIFICATION_RUN_FORMAT_INVALID";
21
+ constructor(message, options) {
22
+ super(message, options);
23
+ this.name = "VerificationRunFormatError";
24
+ }
25
+ }
26
+ export class VerificationRunWaitTimeoutError extends Error {
27
+ runId;
28
+ code = "VERIFICATION_RUN_WAIT_TIMEOUT";
29
+ constructor(runId) {
30
+ super(`verification run '${runId}' did not reach a terminal result before the observation deadline`);
31
+ this.runId = runId;
32
+ this.name = "VerificationRunWaitTimeoutError";
33
+ }
34
+ }
35
+ export class VerificationRunUnknownError extends Error {
36
+ runId;
37
+ code = "VERIFICATION_RUN_UNKNOWN";
38
+ constructor(runId) {
39
+ super(`verification run '${runId}' does not exist`);
40
+ this.runId = runId;
41
+ this.name = "VerificationRunUnknownError";
42
+ }
43
+ }
11
44
  class OutputTailCollector {
12
- #chunks = [];
13
- #retainedBytes = 0;
45
+ #tail = Buffer.alloc(0);
14
46
  #totalBytes = 0;
15
47
  push(chunk) {
16
48
  const value = Buffer.from(chunk);
17
49
  this.#totalBytes += value.byteLength;
18
- this.#chunks.push(value);
19
- this.#retainedBytes += value.byteLength;
20
- while (this.#retainedBytes > OUTPUT_TAIL_BYTES && this.#chunks.length > 0) {
21
- const first = this.#chunks[0];
22
- const excess = this.#retainedBytes - OUTPUT_TAIL_BYTES;
23
- if (first.byteLength <= excess) {
24
- this.#chunks.shift();
25
- this.#retainedBytes -= first.byteLength;
26
- }
27
- else {
28
- this.#chunks[0] = first.subarray(excess);
29
- this.#retainedBytes -= excess;
30
- }
31
- }
50
+ this.#tail = Buffer.concat([this.#tail, value]).subarray(-OUTPUT_TAIL_BYTES);
32
51
  }
33
52
  result() {
34
- return {
35
- tail: Buffer.concat(this.#chunks).toString("utf8"),
36
- truncated: this.#totalBytes > this.#retainedBytes,
37
- omittedBytes: this.#totalBytes - this.#retainedBytes,
53
+ return { tail: this.#tail.toString("utf8"), truncated: this.#totalBytes > this.#tail.byteLength, omittedBytes: this.#totalBytes - this.#tail.byteLength };
54
+ }
55
+ }
56
+ function runtimeDirectory(root) { return path.join(root, ...RUNTIME_DIRECTORY); }
57
+ export function verificationRunDatabasePath(root) { return path.join(runtimeDirectory(root), "verification-runs.sqlite"); }
58
+ export function verificationRunLeasePath(root, runId) {
59
+ return path.join(runtimeDirectory(root), `verification-run-${runId}.lease`);
60
+ }
61
+ function currentSchemaVersion(database) {
62
+ const row = database.prepare("PRAGMA user_version").get();
63
+ if (!row || typeof row.user_version !== "number" || !Number.isInteger(row.user_version)) {
64
+ throw new VerificationRunFormatError("VerificationRun database has an invalid schema version");
65
+ }
66
+ return row.user_version;
67
+ }
68
+ function createCurrentSchema(database) {
69
+ database.exec("BEGIN IMMEDIATE");
70
+ try {
71
+ database.exec(`
72
+ CREATE TABLE verification_runs (
73
+ run_id TEXT PRIMARY KEY, execution_cwd TEXT NOT NULL, candidate_head TEXT NOT NULL, candidate_tree TEXT NOT NULL,
74
+ plan_json TEXT NOT NULL, started_at_ms INTEGER NOT NULL,
75
+ cancel_requested INTEGER NOT NULL DEFAULT 0, terminal_json TEXT, finished_at_ms INTEGER
76
+ ) STRICT;
77
+ CREATE TABLE verification_run_receipts (
78
+ run_id TEXT NOT NULL REFERENCES verification_runs(run_id), item_index INTEGER NOT NULL, receipt_json TEXT NOT NULL,
79
+ PRIMARY KEY (run_id, item_index)
80
+ ) STRICT;
81
+ PRAGMA user_version = ${VERIFICATION_RUN_SCHEMA_VERSION};
82
+ `);
83
+ database.exec("COMMIT");
84
+ }
85
+ catch (error) {
86
+ database.exec("ROLLBACK");
87
+ throw error;
88
+ }
89
+ }
90
+ function assertCurrentSchema(database, created) {
91
+ const version = currentSchemaVersion(database);
92
+ if (version === 0 && created)
93
+ createCurrentSchema(database);
94
+ else if (version !== VERIFICATION_RUN_SCHEMA_VERSION) {
95
+ throw new VerificationRunFormatError(`unsupported VerificationRun database schema version ${version}`);
96
+ }
97
+ }
98
+ function openValidatedDatabase(databasePath, readOnly, created) {
99
+ const database = readOnly ? new DatabaseSync(databasePath, { readOnly: true }) : new DatabaseSync(databasePath);
100
+ // Wait under concurrent runner writes for both mutable and read-only observers.
101
+ database.exec("PRAGMA busy_timeout = 5000;");
102
+ try {
103
+ assertCurrentSchema(database, created);
104
+ }
105
+ catch (error) {
106
+ database.close();
107
+ throw error;
108
+ }
109
+ return database;
110
+ }
111
+ /** Mutable store used only by launch/runner paths that may create the runtime DB. */
112
+ function openRunDatabase(root) {
113
+ fs.mkdirSync(runtimeDirectory(root), { recursive: true });
114
+ const databasePath = verificationRunDatabasePath(root);
115
+ return openValidatedDatabase(databasePath, false, !fs.existsSync(databasePath));
116
+ }
117
+ /** Existing store only; never creates a runtime database under an arbitrary cwd. */
118
+ function openExistingRunDatabase(root, readOnly) {
119
+ const databasePath = verificationRunDatabasePath(root);
120
+ if (!fs.existsSync(databasePath))
121
+ return null;
122
+ return openValidatedDatabase(databasePath, readOnly, false);
123
+ }
124
+ function emptyTail() { return { tail: "", truncated: false, omittedBytes: 0 }; }
125
+ function executorFor(entry) {
126
+ return entry.executor;
127
+ }
128
+ function stringField(value, location) {
129
+ if (typeof value !== "string")
130
+ throw new VerificationRunFormatError(`${location} must be a string`);
131
+ return value;
132
+ }
133
+ function integerField(value, location) {
134
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
135
+ throw new VerificationRunFormatError(`${location} must be an integer`);
136
+ return value;
137
+ }
138
+ function jsonValue(raw, location) {
139
+ try {
140
+ return JSON.parse(raw);
141
+ }
142
+ catch (error) {
143
+ throw new VerificationRunFormatError(`${location} is not valid JSON`, { cause: error });
144
+ }
145
+ }
146
+ const outputTailSchema = z.strictObject({ tail: z.string(), truncated: z.boolean(), omittedBytes: z.number().int().nonnegative() });
147
+ const planEntrySchema = z.strictObject({
148
+ source: z.enum(["contract", "repository-gate"]), label: z.string(), declaration: z.string(),
149
+ executor: z.string(), command: z.string(), args: z.array(z.string()), shell: z.boolean(), timeoutMs: z.number().int().positive(),
150
+ });
151
+ const executionCommon = { durationMs: z.number().int().nonnegative(), stdout: outputTailSchema, stderr: outputTailSchema };
152
+ const executionSchema = z.discriminatedUnion("status", [
153
+ z.strictObject({ status: z.literal("executed"), code: z.number().int(), ...executionCommon }),
154
+ z.strictObject({ status: z.literal("runner_failed"), ...executionCommon, cause: z.strictObject({ code: z.enum(RUNNER_FAILURE_CODES), message: z.string() }) }),
155
+ ]);
156
+ const resultSchema = planEntrySchema.extend({
157
+ candidate: z.strictObject({ head: z.string(), tree: z.string() }), executor: z.string(), execution: executionSchema,
158
+ });
159
+ const terminalSchema = z.discriminatedUnion("status", [
160
+ z.strictObject({ status: z.literal("completed"), results: z.array(resultSchema) }),
161
+ z.strictObject({ status: z.literal("runner_lost"), results: z.array(resultSchema), detail: z.string() }),
162
+ ]);
163
+ function parseCurrent(schema, value, location) {
164
+ const parsed = schema.safeParse(value);
165
+ if (!parsed.success)
166
+ throw new VerificationRunFormatError(`${location} is not current: ${z.prettifyError(parsed.error)}`);
167
+ return parsed.data;
168
+ }
169
+ function parseResult(value, location) { return parseCurrent(resultSchema, value, location); }
170
+ function parsePlan(raw) {
171
+ const value = jsonValue(raw, "VerificationRun plan");
172
+ if (!Array.isArray(value))
173
+ throw new VerificationRunFormatError("VerificationRun plan must be an array");
174
+ return parseCurrent(z.array(planEntrySchema), value, "VerificationRun plan");
175
+ }
176
+ function parseTerminal(raw) {
177
+ if (raw === null)
178
+ return null;
179
+ return parseCurrent(terminalSchema, jsonValue(raw, "VerificationRun terminal"), "VerificationRun terminal");
180
+ }
181
+ function readReceipts(database, runId, plan) {
182
+ const rows = database.prepare(`
183
+ SELECT item_index, receipt_json FROM verification_run_receipts WHERE run_id = ? ORDER BY item_index
184
+ `).all(runId);
185
+ if (rows.length > plan.length)
186
+ throw new VerificationRunFormatError("VerificationRun has more receipts than plan items");
187
+ return rows.map((row, index) => {
188
+ if (integerField(row.item_index, `VerificationRun receipt[${index}] index`) !== index) {
189
+ throw new VerificationRunFormatError("VerificationRun receipts are not a contiguous ordered prefix");
190
+ }
191
+ return parseResult(jsonValue(stringField(row.receipt_json, `VerificationRun receipt[${index}]`), `VerificationRun receipt[${index}]`), `VerificationRun receipt[${index}]`);
192
+ });
193
+ }
194
+ function rowToRun(row, plan, candidate, receipts) {
195
+ if (typeof row.terminal_json !== "string" && row.terminal_json !== null)
196
+ throw new VerificationRunFormatError("VerificationRun terminal is invalid");
197
+ return {
198
+ id: stringField(row.run_id, "VerificationRun id"),
199
+ cwd: stringField(row.execution_cwd, "VerificationRun execution cwd"),
200
+ candidate, plan,
201
+ startedAtMs: integerField(row.started_at_ms, "VerificationRun start time"),
202
+ receipts,
203
+ terminal: parseTerminal(row.terminal_json === null ? null : stringField(row.terminal_json, "VerificationRun terminal")),
204
+ finishedAtMs: row.finished_at_ms === null ? null : integerField(row.finished_at_ms, "VerificationRun finish time"),
205
+ };
206
+ }
207
+ export function readVerificationRun(root, runId) {
208
+ const database = openExistingRunDatabase(root, true);
209
+ if (!database)
210
+ return null;
211
+ try {
212
+ const row = database.prepare(`
213
+ SELECT run_id, execution_cwd, candidate_head, candidate_tree, plan_json, started_at_ms,
214
+ terminal_json, finished_at_ms FROM verification_runs WHERE run_id = ?
215
+ `).get(runId);
216
+ if (!row)
217
+ return null;
218
+ const plan = parsePlan(stringField(row.plan_json, "VerificationRun plan"));
219
+ const candidate = {
220
+ head: stringField(row.candidate_head, "VerificationRun candidate head"),
221
+ tree: stringField(row.candidate_tree, "VerificationRun candidate tree"),
38
222
  };
223
+ return rowToRun(row, plan, candidate, readReceipts(database, runId, plan));
224
+ }
225
+ finally {
226
+ database.close();
227
+ }
228
+ }
229
+ export function createVerificationRun(input, id = createUlid(input.nowMs ?? Date.now(), [...randomBytes(10)])) {
230
+ const startedAtMs = input.nowMs ?? Date.now();
231
+ const database = openRunDatabase(input.root);
232
+ try {
233
+ database.prepare(`
234
+ INSERT INTO verification_runs (run_id, execution_cwd, candidate_head, candidate_tree, plan_json, started_at_ms)
235
+ VALUES (?, ?, ?, ?, ?, ?)
236
+ `).run(id, input.cwd, input.candidate.head, input.candidate.tree, JSON.stringify(input.plan), startedAtMs);
237
+ }
238
+ finally {
239
+ database.close();
240
+ }
241
+ return { id, cwd: input.cwd, candidate: input.candidate, plan: [...input.plan], startedAtMs, receipts: [], terminal: null, finishedAtMs: null };
242
+ }
243
+ export function requestVerificationRunCancellation(root, runId) {
244
+ const database = openExistingRunDatabase(root, false);
245
+ if (!database)
246
+ return false;
247
+ try {
248
+ return database.prepare(`UPDATE verification_runs SET cancel_requested = 1 WHERE run_id = ? AND terminal_json IS NULL`).run(runId).changes > 0;
249
+ }
250
+ finally {
251
+ database.close();
252
+ }
253
+ }
254
+ function isCancellationRequested(database, runId) {
255
+ const row = database.prepare("SELECT cancel_requested FROM verification_runs WHERE run_id = ?").get(runId);
256
+ return row?.cancel_requested === 1;
257
+ }
258
+ function writeReceipt(database, runId, itemIndex, result) {
259
+ database.prepare(`INSERT INTO verification_run_receipts (run_id, item_index, receipt_json) VALUES (?, ?, ?)`).run(runId, itemIndex, JSON.stringify(result));
260
+ }
261
+ function writeRunTerminal(database, runId, terminal) {
262
+ const updated = database.prepare(`
263
+ UPDATE verification_runs SET terminal_json = ?, finished_at_ms = ? WHERE run_id = ? AND terminal_json IS NULL
264
+ `).run(JSON.stringify(terminal), Date.now(), runId);
265
+ if (updated.changes !== 1)
266
+ throw new Error(`verification run '${runId}' is already terminal`);
267
+ }
268
+ function commitRunTerminal(database, runId, terminal) {
269
+ database.exec("BEGIN IMMEDIATE");
270
+ try {
271
+ writeRunTerminal(database, runId, terminal);
272
+ database.exec("COMMIT");
273
+ }
274
+ catch (error) {
275
+ database.exec("ROLLBACK");
276
+ throw error;
277
+ }
278
+ }
279
+ function lostResults(run, detail) {
280
+ const entry = run.plan[run.receipts.length];
281
+ if (!entry)
282
+ return [...run.receipts];
283
+ return [...run.receipts, {
284
+ ...entry, candidate: run.candidate, executor: executorFor(entry),
285
+ execution: { status: "runner_failed", durationMs: 0, stdout: emptyTail(), stderr: emptyTail(), cause: { code: "RUNNER_LOST", message: detail } },
286
+ }];
287
+ }
288
+ function settleRunnerLost(root, run, detail) {
289
+ const proof = acquireRunnerLostProof(verificationRunLeasePath(root, run.id));
290
+ const database = openRunDatabase(root);
291
+ try {
292
+ const current = readVerificationRun(root, run.id);
293
+ if (!current)
294
+ throw new Error(`verification run '${run.id}' disappeared`);
295
+ if (current.terminal)
296
+ return current.terminal;
297
+ const terminal = { status: "runner_lost", results: lostResults(current, detail), detail };
298
+ commitRunTerminal(database, run.id, terminal);
299
+ return terminal;
300
+ }
301
+ catch (error) {
302
+ const reread = readVerificationRun(root, run.id);
303
+ if (reread?.terminal)
304
+ return reread.terminal;
305
+ throw error;
306
+ }
307
+ finally {
308
+ database.close();
309
+ proof.close();
310
+ }
311
+ }
312
+ export async function waitForVerificationRun(input) {
313
+ const deadline = input.deadlineMs ?? (input.timeoutMs === undefined ? undefined : Date.now() + input.timeoutMs);
314
+ for (;;) {
315
+ input.signal?.throwIfAborted();
316
+ const run = readVerificationRun(input.root, input.runId);
317
+ if (!run)
318
+ throw new VerificationRunUnknownError(input.runId);
319
+ if (run.terminal)
320
+ return run.terminal;
321
+ if (observeRunnerLease(verificationRunLeasePath(input.root, input.runId)).state === "released") {
322
+ return settleRunnerLost(input.root, run, "verification runner lease was released before terminal evidence");
323
+ }
324
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
325
+ if (remaining !== undefined && remaining <= 0)
326
+ throw new VerificationRunWaitTimeoutError(input.runId);
327
+ await delay(remaining === undefined ? RUN_WAIT_POLL_MS : Math.min(RUN_WAIT_POLL_MS, remaining));
328
+ }
329
+ }
330
+ const MODULE_FILE = fileURLToPath(import.meta.url);
331
+ const PACKAGE_ROOT = path.resolve(path.dirname(MODULE_FILE), "..", "..", "..");
332
+ const RUNNER_ENTRY = MODULE_FILE.endsWith(".ts")
333
+ ? [process.execPath, "--import", "tsx", path.join(PACKAGE_ROOT, "src", "index.ts"), "__keiyaku-verify"]
334
+ : [process.execPath, path.join(PACKAGE_ROOT, "build", "index.js"), "__keiyaku-verify"];
335
+ function verificationRunnerLaunch(root, runId) {
336
+ const [command, ...args] = RUNNER_ENTRY;
337
+ if (!command)
338
+ throw new Error("verification runner command is empty");
339
+ return {
340
+ command, args: [...args, path.resolve(root), runId], unref: true,
341
+ options: { stdio: ["ignore", "ignore", "ignore", "ipc"], env: { ...process.env, [RUN_CONTROL_BOOTSTRAP_ENV]: "1" } },
342
+ };
343
+ }
344
+ function settleFailedVerificationLaunch(root, run, detail) {
345
+ const current = readVerificationRun(root, run.id) ?? run;
346
+ if (current.terminal)
347
+ return current;
348
+ return { ...current, terminal: settleRunnerLost(root, current, detail), finishedAtMs: Date.now() };
349
+ }
350
+ export async function startVerificationRun(input) {
351
+ const runId = createUlid(Date.now(), [...randomBytes(10)]);
352
+ const leasePath = verificationRunLeasePath(input.root, runId);
353
+ fs.mkdirSync(runtimeDirectory(input.root), { recursive: true });
354
+ initializeRunnerLeaseDatabase(leasePath);
355
+ let launchOwnership;
356
+ try {
357
+ launchOwnership = acquireRunnerLease(leasePath);
39
358
  }
359
+ catch (error) {
360
+ throw new Error(`verification runner launch ownership could not be acquired: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
361
+ }
362
+ let run;
363
+ try {
364
+ run = createVerificationRun(input, runId);
365
+ }
366
+ catch (error) {
367
+ launchOwnership.close();
368
+ throw error;
369
+ }
370
+ const opened = await openDetachedLeaseBootstrap({
371
+ coordinate: run.id, leasePath, parentLease: launchOwnership,
372
+ launch: verificationRunnerLaunch(input.root, run.id), deadline: Date.now() + RUN_START_TIMEOUT_MS,
373
+ });
374
+ if (opened.status === "failed")
375
+ return settleFailedVerificationLaunch(input.root, run, `verification runner launch failed: ${opened.detail}`);
376
+ if (input.signal?.aborted)
377
+ requestVerificationRunCancellation(input.root, run.id);
378
+ const authorized = await opened.bootstrap.authorize();
379
+ if (authorized.status === "failed")
380
+ return settleFailedVerificationLaunch(input.root, run, `verification runner launch failed: ${authorized.detail}`);
381
+ return readVerificationRun(input.root, run.id) ?? run;
382
+ }
383
+ export async function runVerificationPlan(input) {
384
+ const root = input.root ?? input.cwd;
385
+ const run = await startVerificationRun({ root, cwd: input.cwd, candidate: input.candidate, plan: input.plan, signal: input.signal });
386
+ const runId = run.id;
387
+ return {
388
+ runId,
389
+ async awaitTerminal() {
390
+ // Owner abort requests stop and must observe terminal cleanup.
391
+ // CLI wait/status never call this path; they observe only.
392
+ const requestCancellation = () => { requestVerificationRunCancellation(root, runId); };
393
+ input.signal?.addEventListener("abort", requestCancellation, { once: true });
394
+ if (input.signal?.aborted)
395
+ requestCancellation();
396
+ try {
397
+ const terminal = await waitForVerificationRun({ root, runId });
398
+ return { runId, terminal, results: [...terminal.results] };
399
+ }
400
+ finally {
401
+ input.signal?.removeEventListener("abort", requestCancellation);
402
+ }
403
+ },
404
+ };
40
405
  }
41
406
  export function verificationExecutor(command) {
42
407
  const basename = command.command.split(/[\\/]/).pop() ?? "";
43
408
  const executor = basename.toLowerCase().replace(/\.exe$/, "");
44
- if (executor !== "bash" && executor !== "zsh" && executor !== "pwsh") {
409
+ if (executor !== "bash" && executor !== "zsh" && executor !== "pwsh")
45
410
  return { cause: "unsupported_executor" };
46
- }
47
411
  const bodyIndex = command.args.findIndex((arg) => arg === "-c" || arg === "-lc" || arg === "-Command");
48
412
  const body = bodyIndex < 0 ? undefined : command.args[bodyIndex + 1];
49
- if (body === undefined)
50
- return { cause: "missing_command_body" };
51
- return { executor, body };
413
+ return body === undefined ? { cause: "missing_command_body" } : { executor, body };
52
414
  }
53
- /** The document schema owns parsing and persistence; this only consumes its resolved declarations. */
54
415
  export function contractVerificationDeclarations(lifecycle) {
55
- const bind = lifecycle.history.find(({ entry }) => entry.kind === "bind")?.entry;
56
- return bind?.kind === "bind" ? bind.data.verification : [];
416
+ return effectiveVerification(lifecycle.history.map(({ entry }) => entry));
57
417
  }
58
418
  export function composeVerificationPlan(input) {
59
- const contract = input.contract ?? [];
60
419
  const timeoutMs = input.timeoutMs ?? 300_000;
61
420
  return [
62
- ...contract.map((declaration, index) => ({
63
- source: "contract",
64
- label: `Verification ${index + 1}`,
65
- declaration,
66
- command: declaration,
67
- args: [],
68
- shell: true,
69
- timeoutMs,
421
+ ...(input.contract ?? []).map((declaration, index) => ({
422
+ source: "contract", label: `Verification ${index + 1}`, declaration: declaration.script,
423
+ executor: declaration.executor, command: declaration.executor,
424
+ args: declaration.executor === "pwsh" ? ["-Command", declaration.script] : ["-c", declaration.script],
425
+ shell: false, timeoutMs,
70
426
  })),
71
427
  ...input.repositoryGates.map((gate) => ({
72
- source: "repository-gate",
73
- label: gate.label,
74
- declaration: gate.label,
75
- command: gate.command,
76
- args: [...gate.args],
77
- shell: false,
78
- timeoutMs,
428
+ source: "repository-gate", label: gate.label, declaration: gate.label, executor: gate.command,
429
+ command: gate.command, args: [...gate.args], shell: false, timeoutMs,
79
430
  })),
80
431
  ];
81
432
  }
82
433
  export async function resolveVerificationPolicy(cwd) {
83
434
  const loaded = await loadKeiyakuSettings(cwd);
84
435
  assertSettingsKnobUsable(loaded, "gate");
85
- return {
86
- commands: loaded.knobs?.gate?.commands ?? [],
87
- timeoutMs: loaded.knobs?.gate?.timeoutMs ?? 300_000,
88
- };
89
- }
90
- function executorFor(entry) {
91
- if (!entry.shell)
92
- return entry.command;
93
- return process.platform === "win32" ? (process.env.ComSpec ?? "cmd.exe") : "/bin/sh";
436
+ return { commands: loaded.knobs?.gate?.commands ?? [], timeoutMs: loaded.knobs?.gate?.timeoutMs ?? 300_000 };
94
437
  }
95
- export async function runVerificationPlanEntry(cwd, entry, signal, onSupervisorSpawned) {
438
+ export async function executeVerificationRunEntry(input) {
96
439
  const started = process.hrtime.bigint();
97
- return new Promise((resolve, reject) => {
440
+ return await new Promise((resolve) => {
98
441
  const stdout = new OutputTailCollector();
99
442
  const stderr = new OutputTailCollector();
100
443
  let settled = false;
101
- let timer;
102
- let cancel;
444
+ let stopping;
445
+ const streams = () => ({ durationMs: Number((process.hrtime.bigint() - started) / 1000000n), stdout: stdout.result(), stderr: stderr.result() });
446
+ let child;
103
447
  const finish = (execution) => {
104
448
  if (settled)
105
449
  return;
106
450
  settled = true;
107
- if (timer)
108
- clearTimeout(timer);
109
- if (cancel)
110
- signal?.removeEventListener("abort", cancel);
451
+ clearTimeout(timer);
452
+ input.signal?.removeEventListener("abort", cancel);
111
453
  resolve(execution);
112
454
  };
113
- const streams = () => ({
114
- durationMs: Number((process.hrtime.bigint() - started) / 1000000n),
115
- stdout: stdout.result(),
116
- stderr: stderr.result(),
117
- });
118
- let terminating;
119
- let terminal;
120
- const child = spawn(process.execPath, verificationSupervisorArguments(), {
121
- cwd: process.cwd(),
122
- shell: false,
123
- stdio: ["ignore", "pipe", "pipe", "ipc"],
124
- env: getConfig().runtimeEnv,
125
- detached: process.platform !== "win32",
126
- });
127
- child.stdout?.on("data", (chunk) => stdout.push(chunk));
128
- child.stderr?.on("data", (chunk) => stderr.push(chunk));
129
- child.once("error", (error) => {
130
- finish({
131
- status: "runner_failed",
132
- ...streams(),
133
- cause: { code: "SPAWN_FAILED", message: error.message },
134
- });
135
- });
136
- const detachUncleanSupervisor = () => {
137
- child.stdout?.destroy();
138
- child.stderr?.destroy();
139
- if (child.connected)
140
- child.disconnect();
141
- child.unref();
142
- };
143
- const identity = ownedProcessIdentity(child);
144
- if (identity && onSupervisorSpawned) {
145
- try {
146
- onSupervisorSpawned(identity);
147
- }
148
- catch (error) {
149
- void terminateProcessGroup(child).then(() => reject(error), (terminationError) => reject(new ProcessTreeTerminationError(`runner registration failed and cleanup failed: ${terminationError instanceof Error ? terminationError.message : String(terminationError)}`, { cause: error })));
455
+ const stop = (cause) => {
456
+ if (settled || stopping)
150
457
  return;
151
- }
458
+ stopping = cause;
459
+ void terminateProcessGroup(child).then(() => finish({ status: "runner_failed", ...streams(), cause: { code: cause, message: cause === "TIMED_OUT" ? `verification exceeded ${input.entry.timeoutMs}ms` : "verification cancelled" } }), (error) => finish({ status: "runner_failed", ...streams(), cause: { code: "TREE_TERMINATION_FAILED", message: error instanceof Error ? error.message : String(error) } }));
460
+ };
461
+ const cancel = () => stop("CANCELLED");
462
+ const timer = setTimeout(() => stop("TIMED_OUT"), input.entry.timeoutMs);
463
+ timer.unref?.();
464
+ try {
465
+ child = launchDetachedProcess({
466
+ command: input.entry.command, args: input.entry.args,
467
+ options: { cwd: input.cwd, shell: input.entry.shell, stdio: ["ignore", "pipe", "pipe"] },
468
+ });
152
469
  }
153
- child.on("message", (raw) => {
154
- const parsed = supervisorMessageSchema.safeParse(raw);
155
- if (!parsed.success)
470
+ catch (error) {
471
+ finish({ status: "runner_failed", ...streams(), cause: { code: "SPAWN_FAILED", message: error instanceof Error ? error.message : String(error) } });
472
+ return;
473
+ }
474
+ child.stdout?.on("data", (chunk) => stdout.push(chunk));
475
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
476
+ child.once("error", (error) => finish({ status: "runner_failed", ...streams(), cause: { code: "SPAWN_FAILED", message: error.message } }));
477
+ child.once("close", (code, closeSignal) => {
478
+ if (stopping)
156
479
  return;
157
- const message = parsed.data;
158
- if (message.type === "ready") {
159
- if (terminating)
160
- return;
161
- const configureMessage = {
162
- version: VERIFICATION_SUPERVISOR_PROTOCOL_VERSION,
163
- type: "configure",
164
- cwd,
165
- command: entry.command,
166
- args: entry.args,
167
- shell: entry.shell,
168
- timeoutMs: entry.timeoutMs,
169
- };
170
- child.send?.(configureMessage);
480
+ if (closeSignal || code === null) {
481
+ finish({ status: "runner_failed", ...streams(), cause: { code: "PROCESS_TERMINATED", message: `executor terminated${closeSignal ? ` by ${closeSignal}` : " without an exit status"}` } });
171
482
  }
172
- else if (message.type === "configured") {
173
- if (terminating)
174
- return;
175
- const startMessage = {
176
- version: VERIFICATION_SUPERVISOR_PROTOCOL_VERSION,
177
- type: "start",
178
- };
179
- child.send?.(startMessage);
180
- }
181
- else if (message.type === "terminal") {
182
- terminal = message;
183
- if (message.outcome.kind === "tree-termination-failed" && !terminating) {
184
- const supervisorFailure = message.outcome.message;
185
- terminating = "TIMED_OUT";
186
- void terminateProcessGroup(child).then(() => {
187
- finish({
188
- status: "runner_failed",
189
- ...streams(),
190
- cause: { code: "TIMED_OUT", message: `verification exceeded ${entry.timeoutMs}ms` },
191
- });
192
- }, (error) => {
193
- detachUncleanSupervisor();
194
- finish({
195
- status: "runner_failed",
196
- ...streams(),
197
- cause: {
198
- code: "TREE_TERMINATION_FAILED",
199
- message: `${supervisorFailure}; parent cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
200
- },
201
- });
202
- });
203
- }
483
+ else {
484
+ finish({ status: "executed", ...streams(), code });
204
485
  }
205
486
  });
206
- const terminate = (cause) => {
207
- if (settled || terminating)
208
- return;
209
- terminating = cause;
210
- void terminateProcessGroup(child).then(() => {
211
- finish({
212
- status: "runner_failed",
213
- ...streams(),
214
- cause: {
215
- code: cause,
216
- message: cause === "TIMED_OUT" ? `verification exceeded ${entry.timeoutMs}ms` : "verification cancelled",
217
- },
218
- });
219
- }, (error) => {
220
- detachUncleanSupervisor();
221
- finish({
222
- status: "runner_failed",
223
- ...streams(),
224
- cause: {
225
- code: error instanceof ProcessTreeTerminationError ? error.code : "TREE_TERMINATION_FAILED",
226
- message: error instanceof Error ? error.message : String(error),
227
- },
228
- });
229
- });
230
- };
231
- timer = setTimeout(() => terminate("TIMED_OUT"), entry.timeoutMs);
232
- timer.unref?.();
233
- cancel = () => terminate("CANCELLED");
234
- signal?.addEventListener("abort", cancel, { once: true });
235
- if (signal?.aborted)
487
+ input.signal?.addEventListener("abort", cancel, { once: true });
488
+ if (input.signal?.aborted)
236
489
  cancel();
237
- child.once("close", (code, closeSignal) => {
238
- void (async () => {
239
- if (timer)
240
- clearTimeout(timer);
241
- if (cancel)
242
- signal?.removeEventListener("abort", cancel);
243
- if (terminating)
244
- return;
245
- if (identity && ownedProcessIsLive(identity)) {
246
- try {
247
- await terminateOwnedProcess(identity);
248
- }
249
- catch (error) {
250
- finish({
251
- status: "runner_failed",
252
- ...streams(),
253
- cause: {
254
- code: "TREE_TERMINATION_FAILED",
255
- message: error instanceof Error ? error.message : String(error),
256
- },
257
- });
258
- return;
259
- }
260
- }
261
- if (!terminal) {
262
- finish({
263
- status: "runner_failed",
264
- ...streams(),
265
- cause: {
266
- code: "PROCESS_TERMINATED",
267
- message: `verification supervisor terminated${closeSignal ? ` by ${closeSignal}` : code === null ? " without an exit status" : ` with exit ${code}`}`,
268
- },
269
- });
270
- return;
271
- }
272
- const observed = { durationMs: terminal.durationMs, stdout: stdout.result(), stderr: stderr.result() };
273
- if (terminal.outcome.kind === "exit") {
274
- finish({ status: "executed", ...observed, code: terminal.outcome.code });
275
- }
276
- else if (terminal.outcome.kind === "spawn-failed") {
277
- finish({ status: "runner_failed", ...observed, cause: { code: "SPAWN_FAILED", message: terminal.outcome.message } });
278
- }
279
- else if (terminal.outcome.kind === "timeout") {
280
- finish({ status: "runner_failed", ...observed, cause: { code: "TIMED_OUT", message: `verification exceeded ${entry.timeoutMs}ms` } });
281
- }
282
- else if (terminal.outcome.kind === "signal") {
283
- finish({
284
- status: "runner_failed",
285
- ...observed,
286
- cause: {
287
- code: "PROCESS_TERMINATED",
288
- message: `executor terminated${terminal.outcome.signal ? ` by ${terminal.outcome.signal}` : " without an exit status"}`,
289
- },
290
- });
291
- }
292
- else {
293
- finish({
294
- status: "runner_failed",
295
- ...observed,
296
- cause: { code: "TREE_TERMINATION_FAILED", message: terminal.outcome.message },
297
- });
298
- }
299
- })();
300
- });
301
490
  });
302
491
  }
303
- export async function runVerificationPlan(input) {
304
- const execute = async (supervisorLifecycle) => {
305
- const results = [];
306
- for (const entry of input.plan) {
307
- if (input.signal?.aborted) {
308
- const empty = { tail: "", truncated: false, omittedBytes: 0 };
309
- results.push({
310
- ...entry,
311
- candidate: input.candidate,
312
- executor: executorFor(entry),
313
- execution: {
314
- status: "runner_failed",
315
- durationMs: 0,
316
- stdout: empty,
317
- stderr: empty,
318
- cause: { code: "CANCELLED", message: "verification cancelled before runner spawn" },
319
- },
320
- });
492
+ export async function executePersistedVerificationRun(root, runId, inheritedLease) {
493
+ const initial = readVerificationRun(root, runId);
494
+ if (!initial || initial.terminal)
495
+ return;
496
+ const database = openRunDatabase(root);
497
+ let lease = inheritedLease;
498
+ let cancellationPoll;
499
+ try {
500
+ initializeRunnerLeaseDatabase(verificationRunLeasePath(root, runId));
501
+ lease ??= acquireRunnerLease(verificationRunLeasePath(root, runId));
502
+ const adopted = readVerificationRun(root, runId);
503
+ if (!adopted || adopted.terminal)
504
+ return;
505
+ const controller = new AbortController();
506
+ cancellationPoll = setInterval(() => { if (isCancellationRequested(database, runId))
507
+ controller.abort(); }, RUN_WAIT_POLL_MS);
508
+ cancellationPoll.unref?.();
509
+ const results = [...adopted.receipts];
510
+ for (let index = adopted.receipts.length; index < adopted.plan.length; index += 1) {
511
+ const entry = adopted.plan[index];
512
+ if (isCancellationRequested(database, runId))
513
+ controller.abort();
514
+ const execution = controller.signal.aborted
515
+ ? { status: "runner_failed", durationMs: 0, stdout: emptyTail(), stderr: emptyTail(), cause: { code: "CANCELLED", message: "verification cancelled before executor spawn" } }
516
+ : await executeVerificationRunEntry({ cwd: initial.cwd, entry, signal: controller.signal });
517
+ const result = { ...entry, candidate: adopted.candidate, executor: executorFor(entry), execution };
518
+ writeReceipt(database, runId, index, result);
519
+ results.push(result);
520
+ if (execution.status === "runner_failed" && (execution.cause.code === "CANCELLED" || execution.cause.code === "TREE_TERMINATION_FAILED"))
321
521
  break;
322
- }
323
- let supervisorRecorded = false;
324
- const execution = await runVerificationPlanEntry(input.cwd, entry, input.signal, supervisorLifecycle
325
- ? (identity) => {
326
- supervisorLifecycle.spawned(identity);
327
- supervisorRecorded = true;
328
- }
329
- : undefined);
330
- const cleanupFailed = execution.status === "runner_failed"
331
- && execution.cause.code === "TREE_TERMINATION_FAILED";
332
- if (supervisorRecorded && !cleanupFailed)
333
- supervisorLifecycle?.cleaned();
334
- results.push({
335
- ...entry,
336
- candidate: input.candidate,
337
- executor: executorFor(entry),
338
- execution,
339
- });
340
- if (execution.status === "runner_failed"
341
- && (execution.cause.code === "CANCELLED" || execution.cause.code === "TREE_TERMINATION_FAILED"))
342
- break;
343
- }
344
- return results;
345
- };
346
- const key = input.coordinationKey ?? JSON.stringify({
347
- cwd: input.cwd,
348
- candidate: input.candidate,
349
- plan: input.plan,
350
- });
351
- const memoryKey = JSON.stringify({ root: input.coordinationRoot ?? null, key });
352
- const existing = verificationRuns.get(memoryKey);
353
- if (existing)
354
- return await existing;
355
- const run = input.coordinationRoot
356
- ? runCoordinatedVerification({
357
- root: input.coordinationRoot,
358
- key,
359
- execute,
360
- signal: input.signal,
361
- candidate: input.candidate,
362
- plan: input.plan,
363
- })
364
- : execute();
365
- const tracked = run.finally(() => verificationRuns.delete(memoryKey));
366
- verificationRuns.set(memoryKey, tracked);
367
- return await tracked;
368
- }
369
- const verificationRuns = new Map();
370
- async function wait(ms) {
371
- await new Promise((resolve) => setTimeout(resolve, ms));
372
- }
373
- function cancelledResults(candidate, plan) {
374
- const entry = plan[0];
375
- if (!entry)
376
- return [];
377
- const empty = { tail: "", truncated: false, omittedBytes: 0 };
378
- return [{
379
- ...entry,
380
- candidate,
381
- executor: executorFor(entry),
382
- execution: {
383
- status: "runner_failed",
384
- durationMs: 0,
385
- stdout: empty,
386
- stderr: empty,
387
- cause: { code: "CANCELLED", message: "verification cancelled while waiting for an identical active execution" },
388
- },
389
- }];
390
- }
391
- async function runCoordinatedVerification(input) {
392
- const coordination = new VerificationCoordination(input.root);
393
- const fingerprint = coordination.fingerprint(input.key);
394
- const staleAfterMs = input.plan.reduce((total, entry) => total + entry.timeoutMs + PROCESS_GROUP_KILL_GRACE_MS, COORDINATION_RECOVERY_MARGIN_MS);
395
- for (;;) {
396
- if (input.signal?.aborted)
397
- return cancelledResults(input.candidate, input.plan);
398
- const claim = coordination.claim(fingerprint, staleAfterMs);
399
- if (claim.status === "receipt")
400
- return claim.results;
401
- if (claim.status === "wait") {
402
- await wait(COORDINATION_POLL_MS);
403
- continue;
404
522
  }
523
+ const close = beginConnectionBoundRunnerClose(database, lease);
405
524
  try {
406
- if (claim.priorSupervisor) {
407
- await terminateOwnedProcess(claim.priorSupervisor);
408
- coordination.clearSupervisor(fingerprint, claim.token);
409
- }
410
- const lifecycle = {
411
- spawned: (identity) => coordination.recordSupervisor(fingerprint, claim.token, identity),
412
- cleaned: () => coordination.clearSupervisor(fingerprint, claim.token),
413
- };
414
- const results = await input.execute(lifecycle);
415
- const completion = coordination.complete(fingerprint, claim.token, results);
416
- if (completion.status === "ownership-lost") {
417
- throw new Error("verification coordination ownership changed before receipt publication");
418
- }
419
- return results;
525
+ writeRunTerminal(database, runId, { status: "completed", results });
526
+ close.commit();
527
+ lease = undefined;
420
528
  }
421
529
  catch (error) {
422
- coordination.releaseForTakeover(fingerprint, claim.token);
530
+ if (close.leaseOwnership === "retained")
531
+ close.rollback();
532
+ else
533
+ lease = undefined;
423
534
  throw error;
424
535
  }
425
536
  }
537
+ catch (error) {
538
+ if (!lease && error instanceof RunnerLeaseUnavailableError && observeRunnerLease(verificationRunLeasePath(root, runId)).state === "held")
539
+ return;
540
+ throw error;
541
+ }
542
+ finally {
543
+ if (cancellationPoll)
544
+ clearInterval(cancellationPoll);
545
+ if (lease)
546
+ lease.close();
547
+ database.close();
548
+ }
549
+ }
550
+ export async function runVerificationRuntime(root, runId) {
551
+ const transfer = await receiveDetachedLease({ coordinate: runId, leasePath: verificationRunLeasePath(root, runId) });
552
+ if (transfer.status === "authorized")
553
+ await executePersistedVerificationRun(root, runId, transfer.lease);
426
554
  }