opencode-agent-orchestration-kit 1.0.31 → 1.0.33

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 (78) hide show
  1. package/README.md +41 -3
  2. package/SECURITY.md +7 -0
  3. package/docker/open-design/data/app.sqlite +0 -0
  4. package/docker/open-design/data/app.sqlite-shm +0 -0
  5. package/docker/open-design/data/app.sqlite-wal +0 -0
  6. package/docker/open-design/opencode-auth/log/2026-05-02T105802.log +17 -0
  7. package/docker/open-design/opencode-auth/log/2026-05-04T102127.log +16 -0
  8. package/docker/open-design/opencode-auth/opencode.db +0 -0
  9. package/docker/open-design/opencode-auth/opencode.db-shm +0 -0
  10. package/docker/open-design/opencode-auth/opencode.db-wal +0 -0
  11. package/docs/cli.md +72 -0
  12. package/docs/installation.md +25 -5
  13. package/docs/quickstart.md +1 -1
  14. package/docs/releases/v1.0.32.md +68 -0
  15. package/docs/releases/v1.0.33.md +72 -0
  16. package/docs/security.md +4 -0
  17. package/docs/supply-chain.md +9 -5
  18. package/docs/threat-model.md +244 -0
  19. package/docs/use-cases/README.md +31 -0
  20. package/docs/use-cases/direct-label-change/README.md +76 -0
  21. package/docs/use-cases/direct-label-change/before/package.json +8 -0
  22. package/docs/use-cases/direct-label-change/before/src/settings-label.mjs +1 -0
  23. package/docs/use-cases/direct-label-change/before/test/settings-label.test.mjs +8 -0
  24. package/docs/use-cases/direct-label-change/case.json +118 -0
  25. package/docs/use-cases/direct-label-change/expected/package.json +8 -0
  26. package/docs/use-cases/direct-label-change/expected/src/settings-label.mjs +1 -0
  27. package/docs/use-cases/direct-label-change/expected/test/settings-label.test.mjs +8 -0
  28. package/docs/use-cases/feature-tag-normalizer/README.md +78 -0
  29. package/docs/use-cases/feature-tag-normalizer/before/package.json +8 -0
  30. package/docs/use-cases/feature-tag-normalizer/before/src/normalize-tags.mjs +3 -0
  31. package/docs/use-cases/feature-tag-normalizer/before/test/normalize-tags.test.mjs +13 -0
  32. package/docs/use-cases/feature-tag-normalizer/case.json +119 -0
  33. package/docs/use-cases/feature-tag-normalizer/expected/package.json +8 -0
  34. package/docs/use-cases/feature-tag-normalizer/expected/src/normalize-tags.mjs +14 -0
  35. package/docs/use-cases/feature-tag-normalizer/expected/test/normalize-tags.test.mjs +18 -0
  36. package/docs/workflows.md +6 -0
  37. package/opencode/AGENTS.md +6 -0
  38. package/opencode/agents/review_api.md +3 -1
  39. package/opencode/agents/review_coordinator.md +3 -1
  40. package/opencode/agents/review_quality.md +3 -1
  41. package/opencode/agents/review_security.md +3 -1
  42. package/opencode/agents/review_tests.md +3 -1
  43. package/opencode/agents/reviewer.md +2 -2
  44. package/opencode/commands/loop.md +53 -14
  45. package/opencode/docs/ai/evolution/README.md +28 -0
  46. package/opencode/docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl +11 -0
  47. package/opencode/docs/ai/harness/README.md +2 -0
  48. package/opencode/docs/ai/harness/agents.md +30 -4
  49. package/opencode/docs/ai/harness/checks.md +27 -0
  50. package/opencode/docs/ai/harness/commands.md +21 -4
  51. package/opencode/docs/ai/harness/orchestrated-review.md +4 -0
  52. package/opencode/docs/ai/harness/orchestration-contracts.json +891 -0
  53. package/opencode/package-lock.json +14 -8
  54. package/opencode/package.json +1 -0
  55. package/opencode/scripts/adversarial-harness.test.mjs +296 -0
  56. package/opencode/scripts/check-harness.mjs +826 -11
  57. package/opencode/scripts/check-harness.test.mjs +572 -1
  58. package/opencode/scripts/loop-state.mjs +1149 -0
  59. package/opencode/scripts/loop-state.test.mjs +577 -0
  60. package/opencode/scripts/review-orchestrated-prepare.mjs +33 -9
  61. package/package.json +4 -1
  62. package/scripts/check-supply-chain.mjs +11 -1
  63. package/scripts/check-supply-chain.test.mjs +47 -0
  64. package/scripts/check-threat-model.mjs +421 -0
  65. package/scripts/check-threat-model.test.mjs +304 -0
  66. package/scripts/check-use-cases.mjs +501 -0
  67. package/scripts/check-use-cases.test.mjs +225 -0
  68. package/scripts/check.sh +51 -1
  69. package/scripts/install-smoke.sh +24 -1
  70. package/scripts/manage-installation.mjs +567 -25
  71. package/scripts/manage-installation.test.mjs +418 -0
  72. package/scripts/oak.mjs +200 -0
  73. package/scripts/oak.test.mjs +277 -0
  74. package/scripts/package-smoke.mjs +57 -0
  75. package/scripts/package-smoke.test.mjs +75 -2
  76. package/scripts/version.mjs +1 -0
  77. package/scripts/version.test.mjs +3 -2
  78. package/supply-chain.json +1 -0
@@ -0,0 +1,1149 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const SCHEMA_VERSION = 1;
9
+ const slugPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
10
+ const idPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
11
+ const approvalStatuses = new Set(["approved"]);
12
+ const loopStatuses = new Set(["approved", "running", "completed", "paused", "blocked"]);
13
+
14
+ export class LoopStateError extends Error {
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.name = "LoopStateError";
18
+ this.code = code;
19
+ }
20
+ }
21
+
22
+ function fail(code, message) {
23
+ throw new LoopStateError(code, message);
24
+ }
25
+
26
+ function isObject(value) {
27
+ return value !== null && typeof value === "object" && !Array.isArray(value);
28
+ }
29
+
30
+ function requireString(value, label, pattern = idPattern) {
31
+ if (typeof value !== "string" || !pattern.test(value)) {
32
+ fail("invalid_argument", `${label} is invalid`);
33
+ }
34
+ }
35
+
36
+ function requireNullableString(value, label) {
37
+ if (value !== null && (typeof value !== "string" || value.length === 0)) {
38
+ fail("state_corrupt", `${label} must be null or a non-empty string`);
39
+ }
40
+ }
41
+
42
+ function requireExactKeys(value, keys, label, corruptCode = "state_corrupt") {
43
+ if (!isObject(value)) fail(corruptCode, `${label} must be an object`);
44
+ const actual = Object.keys(value).sort();
45
+ const expected = [...keys].sort();
46
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
47
+ fail(corruptCode, `${label} has an invalid field set`);
48
+ }
49
+ }
50
+
51
+ function validateState(state) {
52
+ requireExactKeys(
53
+ state,
54
+ [
55
+ "schema_version",
56
+ "slug",
57
+ "contract_hash",
58
+ "git_baseline",
59
+ "session_id",
60
+ "approval",
61
+ "lease",
62
+ "status",
63
+ "current_iteration",
64
+ "last_completed_step",
65
+ "blocking_cause",
66
+ "last_action_id",
67
+ ],
68
+ "state",
69
+ );
70
+ if (state.schema_version !== SCHEMA_VERSION) {
71
+ fail("schema_unsupported", `unsupported schema_version ${state.schema_version}`);
72
+ }
73
+ requireString(state.slug, "state.slug", slugPattern);
74
+ if (!/^sha256:[a-f0-9]{64}$/.test(state.contract_hash)) {
75
+ fail("state_corrupt", "state.contract_hash is invalid");
76
+ }
77
+ requireString(state.git_baseline, "state.git_baseline");
78
+ requireString(state.session_id, "state.session_id");
79
+ requireExactKeys(state.approval, ["status", "contract_hash"], "state.approval");
80
+ if (!approvalStatuses.has(state.approval.status)) {
81
+ fail("state_corrupt", "state.approval.status is invalid");
82
+ }
83
+ if (state.approval.contract_hash !== state.contract_hash) {
84
+ fail("state_corrupt", "approval contract hash does not match state");
85
+ }
86
+ if (state.lease !== null) {
87
+ requireExactKeys(state.lease, ["session_id", "acquired_at"], "state.lease");
88
+ requireString(state.lease.session_id, "state.lease.session_id");
89
+ if (
90
+ typeof state.lease.acquired_at !== "string"
91
+ || Number.isNaN(Date.parse(state.lease.acquired_at))
92
+ ) {
93
+ fail("state_corrupt", "state.lease.acquired_at is invalid");
94
+ }
95
+ }
96
+ if (!loopStatuses.has(state.status)) {
97
+ fail("state_corrupt", "state.status is invalid");
98
+ }
99
+ if (!Number.isInteger(state.current_iteration) || state.current_iteration < 0) {
100
+ fail("state_corrupt", "state.current_iteration must be a non-negative integer");
101
+ }
102
+ requireNullableString(state.last_completed_step, "state.last_completed_step");
103
+ requireNullableString(state.blocking_cause, "state.blocking_cause");
104
+ requireString(state.last_action_id, "state.last_action_id");
105
+ return state;
106
+ }
107
+
108
+ function validateEvent(event, expectedSequence) {
109
+ requireExactKeys(
110
+ event,
111
+ [
112
+ "schema_version",
113
+ "sequence",
114
+ "action_id",
115
+ "type",
116
+ "session_id",
117
+ "payload",
118
+ "recorded_at",
119
+ "state_after",
120
+ ],
121
+ `history event ${expectedSequence}`,
122
+ "history_corrupt",
123
+ );
124
+ if (event.schema_version !== SCHEMA_VERSION || event.sequence !== expectedSequence) {
125
+ fail("history_corrupt", `history event ${expectedSequence} has invalid sequence or schema`);
126
+ }
127
+ if (
128
+ typeof event.action_id !== "string"
129
+ || !idPattern.test(event.action_id)
130
+ || typeof event.type !== "string"
131
+ || !idPattern.test(event.type)
132
+ || typeof event.session_id !== "string"
133
+ || !idPattern.test(event.session_id)
134
+ || !isObject(event.payload)
135
+ || typeof event.recorded_at !== "string"
136
+ || Number.isNaN(Date.parse(event.recorded_at))
137
+ ) {
138
+ fail("history_corrupt", `history event ${expectedSequence} is invalid`);
139
+ }
140
+ try {
141
+ validateState(event.state_after);
142
+ } catch (error) {
143
+ if (error instanceof LoopStateError) {
144
+ fail("history_corrupt", `history event ${expectedSequence}: ${error.message}`);
145
+ }
146
+ throw error;
147
+ }
148
+ if (event.state_after.last_action_id !== event.action_id) {
149
+ fail("history_corrupt", `history event ${expectedSequence} action mismatch`);
150
+ }
151
+ return event;
152
+ }
153
+
154
+ function validateHistoryContinuity(events, expectedSlug) {
155
+ const first = events[0];
156
+ if (!["initialized", "migrated"].includes(first.type)) {
157
+ fail("history_corrupt", "history must start with initialized or migrated");
158
+ }
159
+ if (first.state_after.slug !== expectedSlug) {
160
+ fail("history_corrupt", "history slug does not match its filename");
161
+ }
162
+ if (first.state_after.last_action_id !== first.action_id) {
163
+ fail("history_corrupt", "initial action does not match state");
164
+ }
165
+ if (
166
+ first.state_after.session_id !== first.session_id
167
+ || first.state_after.lease !== null
168
+ ) {
169
+ fail("history_corrupt", "initial state has invalid session or lease");
170
+ }
171
+ if (first.type === "initialized") {
172
+ requireExactKeys(
173
+ first.payload,
174
+ ["git_baseline"],
175
+ "history event 1 payload",
176
+ "history_corrupt",
177
+ );
178
+ if (first.payload.git_baseline !== first.state_after.git_baseline) {
179
+ fail("history_corrupt", "initial git baseline mismatch");
180
+ }
181
+ } else {
182
+ requireExactKeys(
183
+ first.payload,
184
+ ["from_schema_version"],
185
+ "history event 1 payload",
186
+ "history_corrupt",
187
+ );
188
+ }
189
+ const immutable = {
190
+ slug: first.state_after.slug,
191
+ contract_hash: first.state_after.contract_hash,
192
+ git_baseline: first.state_after.git_baseline,
193
+ approval: first.state_after.approval,
194
+ };
195
+ const actionIds = new Set();
196
+ for (const [index, event] of events.entries()) {
197
+ if (actionIds.has(event.action_id)) {
198
+ fail("history_corrupt", `history repeats action_id at event ${index + 1}`);
199
+ }
200
+ actionIds.add(event.action_id);
201
+ for (const [field, value] of Object.entries(immutable)) {
202
+ if (JSON.stringify(event.state_after[field]) !== JSON.stringify(value)) {
203
+ fail("history_corrupt", `history changes immutable ${field} at event ${index + 1}`);
204
+ }
205
+ }
206
+ if (index === 0) continue;
207
+ const previous = events[index - 1].state_after;
208
+ let expected;
209
+ if (event.type === "resumed") {
210
+ requireExactKeys(
211
+ event.payload,
212
+ ["contract_hash"],
213
+ `history event ${index + 1} payload`,
214
+ "history_corrupt",
215
+ );
216
+ if (
217
+ previous.lease !== null
218
+ || event.payload.contract_hash !== immutable.contract_hash
219
+ || event.state_after.lease?.session_id !== event.session_id
220
+ ) {
221
+ fail("history_corrupt", `invalid resume transition at event ${index + 1}`);
222
+ }
223
+ expected = {
224
+ ...previous,
225
+ session_id: event.session_id,
226
+ lease: event.state_after.lease,
227
+ status: "running",
228
+ last_action_id: event.action_id,
229
+ };
230
+ } else if (event.type === "action_recorded") {
231
+ requireExactKeys(
232
+ event.payload,
233
+ ["iteration", "completed_step", "blocking_cause", "status"],
234
+ `history event ${index + 1} payload`,
235
+ "history_corrupt",
236
+ );
237
+ if (
238
+ previous.lease?.session_id !== event.session_id
239
+ || event.payload.iteration < previous.current_iteration
240
+ ) {
241
+ fail("history_corrupt", `invalid action transition at event ${index + 1}`);
242
+ }
243
+ expected = {
244
+ ...previous,
245
+ current_iteration: event.payload.iteration,
246
+ last_completed_step: event.payload.completed_step,
247
+ blocking_cause: event.payload.blocking_cause,
248
+ status: event.payload.status ?? previous.status,
249
+ last_action_id: event.action_id,
250
+ };
251
+ } else if (event.type === "released") {
252
+ requireExactKeys(
253
+ event.payload,
254
+ [],
255
+ `history event ${index + 1} payload`,
256
+ "history_corrupt",
257
+ );
258
+ if (previous.lease?.session_id !== event.session_id) {
259
+ fail("history_corrupt", `invalid release transition at event ${index + 1}`);
260
+ }
261
+ expected = {
262
+ ...previous,
263
+ lease: null,
264
+ last_action_id: event.action_id,
265
+ };
266
+ } else if (event.type === "repaired") {
267
+ requireExactKeys(
268
+ event.payload,
269
+ ["release_lock"],
270
+ `history event ${index + 1} payload`,
271
+ "history_corrupt",
272
+ );
273
+ if (event.payload.release_lock !== true) {
274
+ fail("history_corrupt", `invalid repair transition at event ${index + 1}`);
275
+ }
276
+ expected = {
277
+ ...previous,
278
+ lease: null,
279
+ last_action_id: event.action_id,
280
+ };
281
+ } else {
282
+ fail("history_corrupt", `unexpected event type at event ${index + 1}`);
283
+ }
284
+ if (JSON.stringify(event.state_after) !== JSON.stringify(expected)) {
285
+ fail("history_corrupt", `state transition mismatch at event ${index + 1}`);
286
+ }
287
+ }
288
+ }
289
+
290
+ function stable(value) {
291
+ if (Array.isArray(value)) return value.map(stable);
292
+ if (!isObject(value)) return value;
293
+ return Object.fromEntries(
294
+ Object.keys(value).sort().map((key) => [key, stable(value[key])]),
295
+ );
296
+ }
297
+
298
+ function sameAction(event, type, sessionId, payload) {
299
+ return JSON.stringify(stable({
300
+ type: event.type,
301
+ session_id: event.session_id,
302
+ payload: event.payload,
303
+ })) === JSON.stringify(stable({
304
+ type,
305
+ session_id: sessionId,
306
+ payload,
307
+ }));
308
+ }
309
+
310
+ function pathsFor(root, slug) {
311
+ requireString(slug, "slug", slugPattern);
312
+ if (typeof root !== "string" || root.length === 0) {
313
+ fail("invalid_argument", "root is required");
314
+ }
315
+ let resolvedRoot;
316
+ try {
317
+ resolvedRoot = fs.realpathSync(path.resolve(root));
318
+ } catch (error) {
319
+ if (error.code === "ENOENT") fail("unsafe_path", "root must exist");
320
+ throw error;
321
+ }
322
+ const rootStat = fs.lstatSync(resolvedRoot);
323
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
324
+ fail("unsafe_path", "root must resolve to a real directory");
325
+ }
326
+ const loopsDir = path.join(resolvedRoot, ".opencode", "loops");
327
+ for (const directory of [
328
+ path.join(resolvedRoot, ".opencode"),
329
+ loopsDir,
330
+ ]) {
331
+ if (!fs.existsSync(directory)) continue;
332
+ const stat = fs.lstatSync(directory);
333
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
334
+ fail("unsafe_path", `${directory} must be a real directory`);
335
+ }
336
+ }
337
+ return {
338
+ root: resolvedRoot,
339
+ loopsDir,
340
+ state: path.join(loopsDir, `${slug}.json`),
341
+ history: path.join(loopsDir, `${slug}.history.jsonl`),
342
+ lock: path.join(loopsDir, `${slug}.lock`),
343
+ lockOwner: path.join(loopsDir, `${slug}.lock`, "owner.json"),
344
+ transitionLock: path.join(loopsDir, `${slug}.lock`, "transition.lock"),
345
+ markdown: path.join(loopsDir, `${slug}.md`),
346
+ };
347
+ }
348
+
349
+ function lstatIfPresent(file) {
350
+ try {
351
+ return fs.lstatSync(file);
352
+ } catch (error) {
353
+ if (error.code === "ENOENT") return null;
354
+ throw error;
355
+ }
356
+ }
357
+
358
+ function ensureLoopsDir(paths) {
359
+ for (const directory of [
360
+ path.join(paths.root, ".opencode"),
361
+ paths.loopsDir,
362
+ ]) {
363
+ try {
364
+ fs.mkdirSync(directory, { mode: 0o700 });
365
+ } catch (error) {
366
+ if (error.code !== "EEXIST") throw error;
367
+ }
368
+ const stat = fs.lstatSync(directory);
369
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
370
+ fail("unsafe_path", `${directory} must be a real directory`);
371
+ }
372
+ }
373
+ }
374
+
375
+ function readJsonFile(file, code) {
376
+ let raw;
377
+ try {
378
+ const stat = fs.lstatSync(file);
379
+ if (!stat.isFile() || stat.isSymbolicLink()) {
380
+ fail("unsafe_path", `${file} must be a regular file`);
381
+ }
382
+ raw = fs.readFileSync(file, "utf8");
383
+ } catch (error) {
384
+ if (error instanceof LoopStateError) throw error;
385
+ if (error.code === "ENOENT") fail("state_missing", `${file} does not exist`);
386
+ throw error;
387
+ }
388
+ try {
389
+ return JSON.parse(raw);
390
+ } catch (error) {
391
+ fail(code, `${file} contains invalid JSON: ${error.message}`);
392
+ }
393
+ }
394
+
395
+ function readContract(contractPath, root) {
396
+ if (typeof contractPath !== "string" || contractPath.length === 0) {
397
+ fail("invalid_argument", "contractPath is required");
398
+ }
399
+ const resolved = path.resolve(contractPath);
400
+ let realContract;
401
+ try {
402
+ realContract = fs.realpathSync(resolved);
403
+ } catch (error) {
404
+ if (error.code === "ENOENT") fail("contract_missing", `${resolved} does not exist`);
405
+ throw error;
406
+ }
407
+ const relative = path.relative(path.resolve(root), realContract);
408
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
409
+ fail("unsafe_path", "contractPath must stay inside root");
410
+ }
411
+ let stat;
412
+ try {
413
+ stat = fs.lstatSync(resolved);
414
+ } catch (error) {
415
+ if (error.code === "ENOENT") fail("contract_missing", `${resolved} does not exist`);
416
+ throw error;
417
+ }
418
+ if (!stat.isFile() || stat.isSymbolicLink()) {
419
+ fail("unsafe_path", "contractPath must be a regular file");
420
+ }
421
+ return fs.readFileSync(realContract);
422
+ }
423
+
424
+ function contractHash(contractPath, root) {
425
+ return `sha256:${createHash("sha256").update(readContract(contractPath, root)).digest("hex")}`;
426
+ }
427
+
428
+ function atomicWriteJson(file, value) {
429
+ const directory = path.dirname(file);
430
+ const temporary = path.join(
431
+ directory,
432
+ `.${path.basename(file)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`,
433
+ );
434
+ let descriptor;
435
+ try {
436
+ descriptor = fs.openSync(temporary, "wx", 0o600);
437
+ fs.writeFileSync(descriptor, `${JSON.stringify(value, null, 2)}\n`);
438
+ fs.fsyncSync(descriptor);
439
+ fs.closeSync(descriptor);
440
+ descriptor = undefined;
441
+ fs.renameSync(temporary, file);
442
+ const directoryDescriptor = fs.openSync(directory, "r");
443
+ try {
444
+ fs.fsyncSync(directoryDescriptor);
445
+ } finally {
446
+ fs.closeSync(directoryDescriptor);
447
+ }
448
+ } finally {
449
+ if (descriptor !== undefined) fs.closeSync(descriptor);
450
+ fs.rmSync(temporary, { force: true });
451
+ }
452
+ }
453
+
454
+ function readHistory(paths, { allowIncompleteTail = false } = {}) {
455
+ let raw;
456
+ try {
457
+ const stat = fs.lstatSync(paths.history);
458
+ if (!stat.isFile() || stat.isSymbolicLink()) {
459
+ fail("unsafe_path", `${paths.history} must be a regular file`);
460
+ }
461
+ raw = fs.readFileSync(paths.history, "utf8");
462
+ } catch (error) {
463
+ if (error instanceof LoopStateError) throw error;
464
+ if (error.code === "ENOENT") fail("history_missing", `${paths.history} does not exist`);
465
+ throw error;
466
+ }
467
+ const hasIncompleteTail = raw.length > 0 && !raw.endsWith("\n");
468
+ const lines = raw.split("\n");
469
+ if (lines.at(-1) === "") lines.pop();
470
+ const events = [];
471
+ for (const [index, line] of lines.entries()) {
472
+ try {
473
+ events.push(validateEvent(JSON.parse(line), index + 1));
474
+ } catch (error) {
475
+ const isLast = index === lines.length - 1;
476
+ if (
477
+ allowIncompleteTail
478
+ && hasIncompleteTail
479
+ && isLast
480
+ && error instanceof SyntaxError
481
+ ) {
482
+ if (events.length > 0) {
483
+ validateHistoryContinuity(
484
+ events,
485
+ path.basename(paths.state, ".json"),
486
+ );
487
+ }
488
+ return {
489
+ events,
490
+ validBytes: Buffer.byteLength(`${lines.slice(0, index).join("\n")}${index > 0 ? "\n" : ""}`),
491
+ incompleteTail: true,
492
+ };
493
+ }
494
+ if (error instanceof LoopStateError) throw error;
495
+ fail("history_corrupt", `${paths.history}: line ${index + 1} is invalid`);
496
+ }
497
+ }
498
+ if (events.length === 0) fail("history_corrupt", `${paths.history} is empty`);
499
+ validateHistoryContinuity(
500
+ events,
501
+ path.basename(paths.state, ".json"),
502
+ );
503
+ return { events, validBytes: Buffer.byteLength(raw), incompleteTail: false };
504
+ }
505
+
506
+ function appendEvent(paths, event) {
507
+ let descriptor;
508
+ try {
509
+ const before = event.sequence === 1 ? null : lstatIfPresent(paths.history);
510
+ if (
511
+ event.sequence !== 1
512
+ && (before === null || !before.isFile() || before.isSymbolicLink())
513
+ ) {
514
+ fail("unsafe_path", `${paths.history} must remain a regular file`);
515
+ }
516
+ const noFollow = fs.constants.O_NOFOLLOW ?? 0;
517
+ const flags = event.sequence === 1
518
+ ? fs.constants.O_APPEND
519
+ | fs.constants.O_CREAT
520
+ | fs.constants.O_EXCL
521
+ | fs.constants.O_WRONLY
522
+ | noFollow
523
+ : fs.constants.O_APPEND
524
+ | fs.constants.O_WRONLY
525
+ | noFollow;
526
+ descriptor = fs.openSync(paths.history, flags, 0o600);
527
+ if (event.sequence !== 1) {
528
+ const opened = fs.fstatSync(descriptor);
529
+ const after = fs.lstatSync(paths.history);
530
+ if (
531
+ !opened.isFile()
532
+ || !after.isFile()
533
+ || after.isSymbolicLink()
534
+ || opened.dev !== after.dev
535
+ || opened.ino !== after.ino
536
+ || opened.dev !== before.dev
537
+ || opened.ino !== before.ino
538
+ ) {
539
+ fail("unsafe_path", `${paths.history} changed during append`);
540
+ }
541
+ }
542
+ fs.writeFileSync(descriptor, `${JSON.stringify(event)}\n`);
543
+ fs.fsyncSync(descriptor);
544
+ } catch (error) {
545
+ if (["ELOOP", "EMLINK"].includes(error.code)) {
546
+ fail("unsafe_path", `${paths.history} cannot be a symlink`);
547
+ }
548
+ if (error.code === "EEXIST") {
549
+ fail("history_exists", `${paths.history} already exists`);
550
+ }
551
+ if (error.code === "ENOENT") {
552
+ fail("history_missing", `${paths.history} does not exist`);
553
+ }
554
+ throw error;
555
+ } finally {
556
+ if (descriptor !== undefined) fs.closeSync(descriptor);
557
+ }
558
+ }
559
+
560
+ function loadStateAndHistory(paths) {
561
+ const state = validateState(readJsonFile(paths.state, "state_corrupt"));
562
+ const { events } = readHistory(paths);
563
+ const latest = events.at(-1).state_after;
564
+ return { state, events, latest };
565
+ }
566
+
567
+ function actionResult(events, actionId, type, sessionId, payload) {
568
+ const existing = events.find((event) => event.action_id === actionId);
569
+ if (!existing) return null;
570
+ if (!sameAction(existing, type, sessionId, payload)) {
571
+ fail("action_conflict", `action_id ${actionId} was already used with different content`);
572
+ }
573
+ return structuredClone(events.at(-1).state_after);
574
+ }
575
+
576
+ function committedActionResult(
577
+ paths,
578
+ state,
579
+ events,
580
+ actionId,
581
+ type,
582
+ sessionId,
583
+ payload,
584
+ ) {
585
+ const result = actionResult(events, actionId, type, sessionId, payload);
586
+ if (!result) return null;
587
+ const latest = events.at(-1).state_after;
588
+ const durableLockPresent = lstatIfPresent(paths.lock) !== null;
589
+ if (
590
+ JSON.stringify(state) !== JSON.stringify(latest)
591
+ || lstatIfPresent(paths.transitionLock) !== null
592
+ || durableLockPresent !== (latest.lease !== null)
593
+ ) {
594
+ fail("recovery_required", "action exists in history but its commit is incomplete; run repair");
595
+ }
596
+ return result;
597
+ }
598
+
599
+ function commitTransition({
600
+ paths,
601
+ events,
602
+ actionId,
603
+ type,
604
+ sessionId,
605
+ payload,
606
+ nextState,
607
+ failpoint,
608
+ }) {
609
+ requireString(actionId, "actionId");
610
+ const duplicate = actionResult(events, actionId, type, sessionId, payload);
611
+ if (duplicate) return duplicate;
612
+ const stateAfter = validateState({
613
+ ...nextState,
614
+ last_action_id: actionId,
615
+ });
616
+ const event = {
617
+ schema_version: SCHEMA_VERSION,
618
+ sequence: events.length + 1,
619
+ action_id: actionId,
620
+ type,
621
+ session_id: sessionId,
622
+ payload,
623
+ recorded_at: new Date().toISOString(),
624
+ state_after: stateAfter,
625
+ };
626
+ appendEvent(paths, event);
627
+ if (failpoint === "after_journal") {
628
+ fail("simulated_crash", "simulated crash after journal append");
629
+ }
630
+ atomicWriteJson(paths.state, stateAfter);
631
+ if (failpoint === "after_snapshot") {
632
+ fail("simulated_crash", "simulated crash after snapshot write");
633
+ }
634
+ return structuredClone(stateAfter);
635
+ }
636
+
637
+ function acquireLock(paths, sessionId) {
638
+ try {
639
+ fs.mkdirSync(paths.lock, { mode: 0o700 });
640
+ } catch (error) {
641
+ if (error.code === "EEXIST") fail("loop_locked", `loop ${path.basename(paths.state, ".json")} is locked`);
642
+ throw error;
643
+ }
644
+ try {
645
+ atomicWriteJson(paths.lockOwner, {
646
+ session_id: sessionId,
647
+ acquired_at: new Date().toISOString(),
648
+ });
649
+ } catch (error) {
650
+ fs.rmSync(paths.lock, { recursive: true, force: true });
651
+ throw error;
652
+ }
653
+ }
654
+
655
+ function requireLockOwner(paths, sessionId) {
656
+ const owner = readJsonFile(paths.lockOwner, "lock_corrupt");
657
+ requireExactKeys(owner, ["session_id", "acquired_at"], "lock owner", "lock_corrupt");
658
+ if (owner.session_id !== sessionId) {
659
+ fail("lease_mismatch", `loop lease belongs to ${owner.session_id}`);
660
+ }
661
+ }
662
+
663
+ function acquireTransitionLock(paths, sessionId) {
664
+ let descriptor;
665
+ try {
666
+ descriptor = fs.openSync(paths.transitionLock, "wx", 0o600);
667
+ fs.writeFileSync(descriptor, `${JSON.stringify({
668
+ session_id: sessionId,
669
+ acquired_at: new Date().toISOString(),
670
+ })}\n`);
671
+ fs.fsyncSync(descriptor);
672
+ } catch (error) {
673
+ if (error.code === "EEXIST") {
674
+ fail("transition_locked", "another transition is already in progress");
675
+ }
676
+ if (error.code === "ENOENT") {
677
+ fail("lease_mismatch", "durable loop lock disappeared");
678
+ }
679
+ throw error;
680
+ } finally {
681
+ if (descriptor !== undefined) fs.closeSync(descriptor);
682
+ }
683
+ }
684
+
685
+ function releaseTransitionLock(paths) {
686
+ fs.rmSync(paths.transitionLock, { force: true });
687
+ }
688
+
689
+ export function initLoopState({
690
+ root,
691
+ slug,
692
+ contractPath,
693
+ gitBaseline,
694
+ sessionId,
695
+ actionId,
696
+ }) {
697
+ requireString(gitBaseline, "gitBaseline");
698
+ requireString(sessionId, "sessionId");
699
+ requireString(actionId, "actionId");
700
+ const paths = pathsFor(root, slug);
701
+ ensureLoopsDir(paths);
702
+ const hash = contractHash(contractPath, paths.root);
703
+ if (
704
+ lstatIfPresent(paths.state) !== null
705
+ || lstatIfPresent(paths.history) !== null
706
+ || lstatIfPresent(paths.lock) !== null
707
+ ) {
708
+ fail("state_exists", `loop ${slug} already has durable state`);
709
+ }
710
+ const state = validateState({
711
+ schema_version: SCHEMA_VERSION,
712
+ slug,
713
+ contract_hash: hash,
714
+ git_baseline: gitBaseline,
715
+ session_id: sessionId,
716
+ approval: { status: "approved", contract_hash: hash },
717
+ lease: null,
718
+ status: "approved",
719
+ current_iteration: 0,
720
+ last_completed_step: null,
721
+ blocking_cause: null,
722
+ last_action_id: actionId,
723
+ });
724
+ const event = {
725
+ schema_version: SCHEMA_VERSION,
726
+ sequence: 1,
727
+ action_id: actionId,
728
+ type: "initialized",
729
+ session_id: sessionId,
730
+ payload: { git_baseline: gitBaseline },
731
+ recorded_at: new Date().toISOString(),
732
+ state_after: state,
733
+ };
734
+ appendEvent(paths, event);
735
+ atomicWriteJson(paths.state, state);
736
+ return structuredClone(state);
737
+ }
738
+
739
+ export function inspectLoopState({ root, slug }) {
740
+ const paths = pathsFor(root, slug);
741
+ const { state, latest } = loadStateAndHistory(paths);
742
+ if (JSON.stringify(state) !== JSON.stringify(latest)) {
743
+ fail("snapshot_stale", "snapshot is behind append-only history; run repair");
744
+ }
745
+ return structuredClone(state);
746
+ }
747
+
748
+ export function acquireLoop({
749
+ root,
750
+ slug,
751
+ contractPath,
752
+ sessionId,
753
+ actionId,
754
+ }) {
755
+ requireString(sessionId, "sessionId");
756
+ requireString(actionId, "actionId");
757
+ const paths = pathsFor(root, slug);
758
+ const { state, events, latest } = loadStateAndHistory(paths);
759
+ const payload = { contract_hash: contractHash(contractPath, paths.root) };
760
+ if (payload.contract_hash !== state.contract_hash) {
761
+ fail("contract_mismatch", "approved contract hash does not match the current contract");
762
+ }
763
+ const duplicate = committedActionResult(
764
+ paths,
765
+ state,
766
+ events,
767
+ actionId,
768
+ "resumed",
769
+ sessionId,
770
+ payload,
771
+ );
772
+ if (duplicate) return duplicate;
773
+ if (JSON.stringify(state) !== JSON.stringify(latest)) {
774
+ fail("snapshot_stale", "snapshot is behind append-only history; run repair");
775
+ }
776
+ if (state.lease !== null) {
777
+ if (lstatIfPresent(paths.lock) !== null) {
778
+ fail("loop_locked", `loop ${slug} is locked`);
779
+ }
780
+ fail("lease_inconsistent", "canonical state already has a lease; run repair");
781
+ }
782
+ acquireLock(paths, sessionId);
783
+ try {
784
+ return commitTransition({
785
+ paths,
786
+ events,
787
+ actionId,
788
+ type: "resumed",
789
+ sessionId,
790
+ payload,
791
+ nextState: {
792
+ ...state,
793
+ session_id: sessionId,
794
+ lease: {
795
+ session_id: sessionId,
796
+ acquired_at: new Date().toISOString(),
797
+ },
798
+ status: "running",
799
+ },
800
+ });
801
+ } catch (error) {
802
+ fs.rmSync(paths.lock, { recursive: true, force: true });
803
+ throw error;
804
+ }
805
+ }
806
+
807
+ export function recordLoopAction({
808
+ root,
809
+ slug,
810
+ sessionId,
811
+ actionId,
812
+ iteration,
813
+ completedStep,
814
+ blockingCause,
815
+ status,
816
+ failpoint,
817
+ }) {
818
+ requireString(sessionId, "sessionId");
819
+ requireString(actionId, "actionId");
820
+ if (!Number.isInteger(iteration) || iteration < 0) {
821
+ fail("invalid_argument", "iteration must be a non-negative integer");
822
+ }
823
+ if (completedStep !== null && (typeof completedStep !== "string" || completedStep.length === 0)) {
824
+ fail("invalid_argument", "completedStep must be null or a non-empty string");
825
+ }
826
+ if (blockingCause !== null && (typeof blockingCause !== "string" || blockingCause.length === 0)) {
827
+ fail("invalid_argument", "blockingCause must be null or a non-empty string");
828
+ }
829
+ if (status !== undefined && !loopStatuses.has(status)) {
830
+ fail("invalid_argument", "status is invalid");
831
+ }
832
+ const paths = pathsFor(root, slug);
833
+ const payload = {
834
+ iteration,
835
+ completed_step: completedStep,
836
+ blocking_cause: blockingCause,
837
+ status: status ?? null,
838
+ };
839
+ const initial = loadStateAndHistory(paths);
840
+ const duplicate = committedActionResult(
841
+ paths,
842
+ initial.state,
843
+ initial.events,
844
+ actionId,
845
+ "action_recorded",
846
+ sessionId,
847
+ payload,
848
+ );
849
+ if (duplicate) return duplicate;
850
+ requireLockOwner(paths, sessionId);
851
+ acquireTransitionLock(paths, sessionId);
852
+ let preserveTransitionLock = false;
853
+ try {
854
+ const { state, events, latest } = loadStateAndHistory(paths);
855
+ const concurrentDuplicate = actionResult(
856
+ events,
857
+ actionId,
858
+ "action_recorded",
859
+ sessionId,
860
+ payload,
861
+ );
862
+ if (concurrentDuplicate) return concurrentDuplicate;
863
+ if (JSON.stringify(state) !== JSON.stringify(latest)) {
864
+ fail("snapshot_stale", "snapshot is behind append-only history; run repair");
865
+ }
866
+ requireLockOwner(paths, sessionId);
867
+ if (state.lease?.session_id !== sessionId) {
868
+ fail("lease_mismatch", "canonical lease does not belong to this session");
869
+ }
870
+ if (iteration < state.current_iteration) {
871
+ fail("iteration_regression", "iteration cannot move backwards");
872
+ }
873
+ try {
874
+ return commitTransition({
875
+ paths,
876
+ events,
877
+ actionId,
878
+ type: "action_recorded",
879
+ sessionId,
880
+ payload,
881
+ failpoint,
882
+ nextState: {
883
+ ...state,
884
+ current_iteration: iteration,
885
+ last_completed_step: completedStep,
886
+ blocking_cause: blockingCause,
887
+ status: status ?? state.status,
888
+ },
889
+ });
890
+ } catch (error) {
891
+ preserveTransitionLock =
892
+ error instanceof LoopStateError && error.code === "simulated_crash";
893
+ throw error;
894
+ }
895
+ } finally {
896
+ if (!preserveTransitionLock) releaseTransitionLock(paths);
897
+ }
898
+ }
899
+
900
+ export function releaseLoop({ root, slug, sessionId, actionId, failpoint }) {
901
+ requireString(sessionId, "sessionId");
902
+ requireString(actionId, "actionId");
903
+ const paths = pathsFor(root, slug);
904
+ const initial = loadStateAndHistory(paths);
905
+ const duplicate = committedActionResult(
906
+ paths,
907
+ initial.state,
908
+ initial.events,
909
+ actionId,
910
+ "released",
911
+ sessionId,
912
+ {},
913
+ );
914
+ if (duplicate) return duplicate;
915
+ requireLockOwner(paths, sessionId);
916
+ acquireTransitionLock(paths, sessionId);
917
+ let preserveTransitionLock = false;
918
+ try {
919
+ const { state, events, latest } = loadStateAndHistory(paths);
920
+ const payload = {};
921
+ const concurrentDuplicate = actionResult(
922
+ events,
923
+ actionId,
924
+ "released",
925
+ sessionId,
926
+ payload,
927
+ );
928
+ if (concurrentDuplicate) return concurrentDuplicate;
929
+ if (JSON.stringify(state) !== JSON.stringify(latest)) {
930
+ fail("snapshot_stale", "snapshot is behind append-only history; run repair");
931
+ }
932
+ requireLockOwner(paths, sessionId);
933
+ if (state.lease?.session_id !== sessionId) {
934
+ fail("lease_mismatch", "canonical lease does not belong to this session");
935
+ }
936
+ let released;
937
+ try {
938
+ released = commitTransition({
939
+ paths,
940
+ events,
941
+ actionId,
942
+ type: "released",
943
+ sessionId,
944
+ payload,
945
+ failpoint,
946
+ nextState: { ...state, lease: null },
947
+ });
948
+ } catch (error) {
949
+ preserveTransitionLock =
950
+ error instanceof LoopStateError && error.code === "simulated_crash";
951
+ throw error;
952
+ }
953
+ fs.rmSync(paths.lock, { recursive: true, force: true });
954
+ return released;
955
+ } finally {
956
+ if (!preserveTransitionLock) releaseTransitionLock(paths);
957
+ }
958
+ }
959
+
960
+ export function repairLoopState({
961
+ root,
962
+ slug,
963
+ releaseLock = false,
964
+ truncateTail = false,
965
+ }) {
966
+ const paths = pathsFor(root, slug);
967
+ if (lstatIfPresent(paths.lock) !== null && !releaseLock) {
968
+ fail("loop_locked", "repair refuses an active or abandoned lock without --release-lock");
969
+ }
970
+ const history = readHistory(paths, { allowIncompleteTail: truncateTail });
971
+ if (history.incompleteTail) {
972
+ fs.truncateSync(paths.history, history.validBytes);
973
+ const descriptor = fs.openSync(paths.history, "r");
974
+ try {
975
+ fs.fsyncSync(descriptor);
976
+ } finally {
977
+ fs.closeSync(descriptor);
978
+ }
979
+ }
980
+ if (history.events.length === 0) {
981
+ fail("history_corrupt", "history has no complete events");
982
+ }
983
+ let recovered = structuredClone(history.events.at(-1).state_after);
984
+ if (releaseLock) {
985
+ const actionId = `repair:${randomBytes(8).toString("hex")}`;
986
+ recovered = {
987
+ ...recovered,
988
+ lease: null,
989
+ last_action_id: actionId,
990
+ };
991
+ appendEvent(paths, {
992
+ schema_version: SCHEMA_VERSION,
993
+ sequence: history.events.length + 1,
994
+ action_id: actionId,
995
+ type: "repaired",
996
+ session_id: "repair",
997
+ payload: { release_lock: true },
998
+ recorded_at: new Date().toISOString(),
999
+ state_after: recovered,
1000
+ });
1001
+ fs.rmSync(paths.lock, { recursive: true, force: true });
1002
+ }
1003
+ atomicWriteJson(paths.state, recovered);
1004
+ return recovered;
1005
+ }
1006
+
1007
+ export function migrateLoopState({
1008
+ root,
1009
+ slug,
1010
+ contractPath,
1011
+ gitBaseline,
1012
+ sessionId,
1013
+ actionId,
1014
+ approvalStatus,
1015
+ }) {
1016
+ if (approvalStatus !== "approved") {
1017
+ fail("approval_required", "migration requires renewed explicit approval");
1018
+ }
1019
+ requireString(sessionId, "sessionId");
1020
+ requireString(actionId, "actionId");
1021
+ const paths = pathsFor(root, slug);
1022
+ ensureLoopsDir(paths);
1023
+ let legacy = null;
1024
+ if (lstatIfPresent(paths.state) !== null) {
1025
+ legacy = readJsonFile(paths.state, "state_corrupt");
1026
+ if (!isObject(legacy) || legacy.schema_version !== 0) {
1027
+ fail("schema_unsupported", "migrate accepts only schema_version 0 or markdown-only state");
1028
+ }
1029
+ }
1030
+ const baseline = legacy?.git_baseline ?? gitBaseline;
1031
+ requireString(baseline, "gitBaseline");
1032
+ if (lstatIfPresent(paths.history) !== null) {
1033
+ fail("history_exists", "migration refuses to replace existing append-only history");
1034
+ }
1035
+ const hash = contractHash(contractPath, paths.root);
1036
+ const state = validateState({
1037
+ schema_version: SCHEMA_VERSION,
1038
+ slug,
1039
+ contract_hash: hash,
1040
+ git_baseline: baseline,
1041
+ session_id: sessionId,
1042
+ approval: { status: "approved", contract_hash: hash },
1043
+ lease: null,
1044
+ status: legacy?.status ?? "approved",
1045
+ current_iteration: legacy?.current_iteration ?? 0,
1046
+ last_completed_step: legacy?.last_completed_step ?? null,
1047
+ blocking_cause: legacy?.blocking_cause ?? null,
1048
+ last_action_id: actionId,
1049
+ });
1050
+ const event = {
1051
+ schema_version: SCHEMA_VERSION,
1052
+ sequence: 1,
1053
+ action_id: actionId,
1054
+ type: "migrated",
1055
+ session_id: sessionId,
1056
+ payload: { from_schema_version: legacy?.schema_version ?? "markdown" },
1057
+ recorded_at: new Date().toISOString(),
1058
+ state_after: state,
1059
+ };
1060
+ appendEvent(paths, event);
1061
+ atomicWriteJson(paths.state, state);
1062
+ return structuredClone(state);
1063
+ }
1064
+
1065
+ function parseArguments(argv) {
1066
+ const [command, ...tokens] = argv;
1067
+ const options = {};
1068
+ for (let index = 0; index < tokens.length; index += 1) {
1069
+ const token = tokens[index];
1070
+ if (!token.startsWith("--")) fail("invalid_argument", `unexpected argument ${token}`);
1071
+ const key = token.slice(2).replaceAll("-", "_");
1072
+ if (["release_lock", "truncate_tail"].includes(key)) {
1073
+ options[key] = true;
1074
+ continue;
1075
+ }
1076
+ const value = tokens[index + 1];
1077
+ if (value === undefined || value.startsWith("--")) {
1078
+ fail("invalid_argument", `${token} requires a value`);
1079
+ }
1080
+ options[key] = value;
1081
+ index += 1;
1082
+ }
1083
+ return { command, options };
1084
+ }
1085
+
1086
+ function cliOptions(options) {
1087
+ return {
1088
+ root: options.root ?? process.cwd(),
1089
+ slug: options.slug,
1090
+ contractPath: options.contract,
1091
+ gitBaseline: options.git_baseline,
1092
+ sessionId: options.session_id,
1093
+ actionId: options.action_id,
1094
+ approvalStatus: options.approval_status,
1095
+ };
1096
+ }
1097
+
1098
+ export function main(argv = process.argv.slice(2)) {
1099
+ const { command, options } = parseArguments(argv);
1100
+ const common = cliOptions(options);
1101
+ let result;
1102
+ if (command === "init") {
1103
+ result = initLoopState(common);
1104
+ } else if (command === "resume") {
1105
+ result = acquireLoop(common);
1106
+ } else if (command === "record") {
1107
+ result = recordLoopAction({
1108
+ ...common,
1109
+ iteration: Number(options.iteration),
1110
+ completedStep: options.completed_step === "null" ? null : options.completed_step,
1111
+ blockingCause: options.blocking_cause === "null" ? null : options.blocking_cause,
1112
+ status: options.status,
1113
+ });
1114
+ } else if (command === "release") {
1115
+ result = releaseLoop(common);
1116
+ } else if (command === "inspect") {
1117
+ result = inspectLoopState(common);
1118
+ } else if (command === "repair") {
1119
+ result = repairLoopState({
1120
+ ...common,
1121
+ releaseLock: options.release_lock === true,
1122
+ truncateTail: options.truncate_tail === true,
1123
+ });
1124
+ } else if (command === "migrate") {
1125
+ result = migrateLoopState(common);
1126
+ } else {
1127
+ fail(
1128
+ "invalid_argument",
1129
+ "command must be init, resume, record, release, inspect, repair, or migrate",
1130
+ );
1131
+ }
1132
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1133
+ }
1134
+
1135
+ const isDirect = process.argv[1]
1136
+ && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
1137
+
1138
+ if (isDirect) {
1139
+ try {
1140
+ main();
1141
+ } catch (error) {
1142
+ if (error instanceof LoopStateError) {
1143
+ process.stderr.write(`${error.code}: ${error.message}\n`);
1144
+ process.exitCode = 1;
1145
+ } else {
1146
+ throw error;
1147
+ }
1148
+ }
1149
+ }