opencode-agent-orchestration-kit 1.0.30 → 1.0.32

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 (31) hide show
  1. package/README.md +21 -2
  2. package/docs/installation.md +1 -1
  3. package/docs/quickstart.md +1 -1
  4. package/docs/releases/v1.0.31.md +68 -0
  5. package/docs/releases/v1.0.32.md +68 -0
  6. package/opencode/AGENTS.md +6 -0
  7. package/opencode/agents/review_api.md +3 -1
  8. package/opencode/agents/review_coordinator.md +3 -1
  9. package/opencode/agents/review_quality.md +3 -1
  10. package/opencode/agents/review_security.md +3 -1
  11. package/opencode/agents/review_tests.md +3 -1
  12. package/opencode/agents/reviewer.md +2 -2
  13. package/opencode/commands/loop.md +53 -14
  14. package/opencode/docs/ai/evolution/README.md +41 -3
  15. package/opencode/docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl +11 -0
  16. package/opencode/docs/ai/harness/agents.md +23 -4
  17. package/opencode/docs/ai/harness/checks.md +34 -3
  18. package/opencode/docs/ai/harness/commands.md +13 -4
  19. package/opencode/docs/ai/harness/orchestrated-review.md +4 -0
  20. package/opencode/scripts/adversarial-harness.test.mjs +296 -0
  21. package/opencode/scripts/check-harness.mjs +198 -2
  22. package/opencode/scripts/check-harness.test.mjs +207 -1
  23. package/opencode/scripts/loop-state.mjs +1149 -0
  24. package/opencode/scripts/loop-state.test.mjs +577 -0
  25. package/opencode/scripts/replay-routing.mjs +9 -5
  26. package/opencode/scripts/review-orchestrated-prepare.mjs +33 -9
  27. package/opencode/scripts/summarize-routing-metrics.mjs +471 -0
  28. package/opencode/scripts/summarize-routing-metrics.test.mjs +230 -0
  29. package/package.json +1 -1
  30. package/scripts/package-smoke.test.mjs +2 -2
  31. package/scripts/version.test.mjs +2 -2
@@ -0,0 +1,577 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import {
10
+ LoopStateError,
11
+ acquireLoop,
12
+ initLoopState,
13
+ inspectLoopState,
14
+ migrateLoopState,
15
+ recordLoopAction,
16
+ releaseLoop,
17
+ repairLoopState,
18
+ } from "./loop-state.mjs";
19
+
20
+ const scriptPath = fileURLToPath(new URL("./loop-state.mjs", import.meta.url));
21
+
22
+ function withRepo(callback) {
23
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-state-"));
24
+ try {
25
+ fs.mkdirSync(path.join(root, ".opencode/loops"), { recursive: true });
26
+ const contractPath = path.join(root, ".opencode/loops/example.md");
27
+ fs.writeFileSync(contractPath, "# Approved loop\n\nObjective: ship safely.\n");
28
+ return callback({ root, contractPath });
29
+ } finally {
30
+ fs.rmSync(root, { recursive: true, force: true });
31
+ }
32
+ }
33
+
34
+ function initExample(root, contractPath) {
35
+ return initLoopState({
36
+ root,
37
+ slug: "example",
38
+ contractPath,
39
+ gitBaseline: "abc123",
40
+ sessionId: "session-1",
41
+ actionId: "approve-1",
42
+ });
43
+ }
44
+
45
+ test("initializes canonical state and append-only history without replacing markdown", () => {
46
+ withRepo(({ root, contractPath }) => {
47
+ const markdown = fs.readFileSync(contractPath, "utf8");
48
+ const state = initExample(root, contractPath);
49
+
50
+ assert.equal(state.schema_version, 1);
51
+ assert.equal(state.slug, "example");
52
+ assert.match(state.contract_hash, /^sha256:[a-f0-9]{64}$/);
53
+ assert.equal(state.approval.status, "approved");
54
+ assert.equal(state.approval.contract_hash, state.contract_hash);
55
+ assert.equal(state.git_baseline, "abc123");
56
+ assert.equal(state.session_id, "session-1");
57
+ assert.equal(state.lease, null);
58
+ assert.equal(state.status, "approved");
59
+ assert.equal(state.current_iteration, 0);
60
+ assert.equal(state.last_completed_step, null);
61
+ assert.equal(state.blocking_cause, null);
62
+ assert.equal(state.last_action_id, "approve-1");
63
+ assert.equal(fs.readFileSync(contractPath, "utf8"), markdown);
64
+
65
+ const history = fs
66
+ .readFileSync(path.join(root, ".opencode/loops/example.history.jsonl"), "utf8")
67
+ .trim()
68
+ .split("\n")
69
+ .map(JSON.parse);
70
+ assert.equal(history.length, 1);
71
+ assert.equal(history[0].type, "initialized");
72
+ assert.equal(history[0].action_id, "approve-1");
73
+ });
74
+ });
75
+
76
+ test("acquires one durable lease and rejects a simultaneous resume", () => {
77
+ withRepo(({ root, contractPath }) => {
78
+ initExample(root, contractPath);
79
+ acquireLoop({
80
+ root,
81
+ slug: "example",
82
+ contractPath,
83
+ sessionId: "session-1",
84
+ actionId: "resume-1",
85
+ });
86
+ assert.equal(inspectLoopState({ root, slug: "example" }).status, "running");
87
+
88
+ assert.throws(
89
+ () => acquireLoop({
90
+ root,
91
+ slug: "example",
92
+ contractPath,
93
+ sessionId: "session-2",
94
+ actionId: "resume-2",
95
+ }),
96
+ (error) => error instanceof LoopStateError && error.code === "loop_locked",
97
+ );
98
+ });
99
+ });
100
+
101
+ test("serializes transitions even when processes share the same session id", () => {
102
+ withRepo(({ root, contractPath }) => {
103
+ initExample(root, contractPath);
104
+ acquireLoop({
105
+ root,
106
+ slug: "example",
107
+ contractPath,
108
+ sessionId: "session-1",
109
+ actionId: "resume-1",
110
+ });
111
+ assert.throws(
112
+ () => repairLoopState({ root, slug: "example" }),
113
+ (error) => error instanceof LoopStateError && error.code === "loop_locked",
114
+ );
115
+ fs.writeFileSync(
116
+ path.join(root, ".opencode/loops/example.lock/transition.lock"),
117
+ '{"session_id":"session-1"}\n',
118
+ );
119
+
120
+ assert.throws(
121
+ () => recordLoopAction({
122
+ root,
123
+ slug: "example",
124
+ sessionId: "session-1",
125
+ actionId: "iteration-1",
126
+ iteration: 1,
127
+ completedStep: "developer_change",
128
+ blockingCause: null,
129
+ }),
130
+ (error) => error instanceof LoopStateError && error.code === "transition_locked",
131
+ );
132
+
133
+ const historyLines = fs
134
+ .readFileSync(path.join(root, ".opencode/loops/example.history.jsonl"), "utf8")
135
+ .trim()
136
+ .split("\n");
137
+ assert.equal(historyLines.length, 2);
138
+ });
139
+ });
140
+
141
+ test("rejects approval bound to a changed contract", () => {
142
+ withRepo(({ root, contractPath }) => {
143
+ initExample(root, contractPath);
144
+ acquireLoop({
145
+ root,
146
+ slug: "example",
147
+ contractPath,
148
+ sessionId: "session-1",
149
+ actionId: "resume-1",
150
+ });
151
+ fs.appendFileSync(contractPath, "\nChanged after approval.\n");
152
+
153
+ assert.throws(
154
+ () => acquireLoop({
155
+ root,
156
+ slug: "example",
157
+ contractPath,
158
+ sessionId: "session-1",
159
+ actionId: "resume-1",
160
+ }),
161
+ (error) => error instanceof LoopStateError && error.code === "contract_mismatch",
162
+ );
163
+ });
164
+ });
165
+
166
+ test("records actions idempotently and rejects action-id reuse with different content", () => {
167
+ withRepo(({ root, contractPath }) => {
168
+ initExample(root, contractPath);
169
+ acquireLoop({
170
+ root,
171
+ slug: "example",
172
+ contractPath,
173
+ sessionId: "session-1",
174
+ actionId: "resume-1",
175
+ });
176
+ const action = {
177
+ root,
178
+ slug: "example",
179
+ sessionId: "session-1",
180
+ actionId: "iteration-1",
181
+ iteration: 1,
182
+ completedStep: "developer_change",
183
+ blockingCause: null,
184
+ };
185
+
186
+ const first = recordLoopAction(action);
187
+ const duplicate = recordLoopAction(action);
188
+ assert.deepEqual(duplicate, first);
189
+
190
+ const later = recordLoopAction({
191
+ ...action,
192
+ actionId: "iteration-2",
193
+ iteration: 2,
194
+ completedStep: "reviewer_approved",
195
+ status: "completed",
196
+ });
197
+ const delayedRetry = recordLoopAction(action);
198
+ assert.deepEqual(delayedRetry, later);
199
+ assert.equal(later.status, "completed");
200
+
201
+ assert.throws(
202
+ () => recordLoopAction({ ...action, completedStep: "reviewer_approved" }),
203
+ (error) => error instanceof LoopStateError && error.code === "action_conflict",
204
+ );
205
+
206
+ const released = releaseLoop({
207
+ root,
208
+ slug: "example",
209
+ sessionId: "session-1",
210
+ actionId: "release-1",
211
+ });
212
+ assert.deepEqual(recordLoopAction(action), released);
213
+
214
+ const historyLines = fs
215
+ .readFileSync(path.join(root, ".opencode/loops/example.history.jsonl"), "utf8")
216
+ .trim()
217
+ .split("\n");
218
+ assert.equal(historyLines.length, 5);
219
+ });
220
+ });
221
+
222
+ test("recovers a snapshot left behind by a crash after the journal append", () => {
223
+ withRepo(({ root, contractPath }) => {
224
+ initExample(root, contractPath);
225
+ acquireLoop({
226
+ root,
227
+ slug: "example",
228
+ contractPath,
229
+ sessionId: "session-1",
230
+ actionId: "resume-1",
231
+ });
232
+
233
+ assert.throws(
234
+ () => recordLoopAction({
235
+ root,
236
+ slug: "example",
237
+ sessionId: "session-1",
238
+ actionId: "iteration-1",
239
+ iteration: 1,
240
+ completedStep: "developer_change",
241
+ blockingCause: null,
242
+ failpoint: "after_journal",
243
+ }),
244
+ (error) => error instanceof LoopStateError && error.code === "simulated_crash",
245
+ );
246
+
247
+ const staleSnapshot = JSON.parse(
248
+ fs.readFileSync(path.join(root, ".opencode/loops/example.json"), "utf8"),
249
+ );
250
+ assert.equal(staleSnapshot.current_iteration, 0);
251
+
252
+ assert.throws(
253
+ () => recordLoopAction({
254
+ root,
255
+ slug: "example",
256
+ sessionId: "session-1",
257
+ actionId: "iteration-1",
258
+ iteration: 1,
259
+ completedStep: "developer_change",
260
+ blockingCause: null,
261
+ }),
262
+ (error) => error instanceof LoopStateError && error.code === "recovery_required",
263
+ );
264
+
265
+ const repaired = repairLoopState({
266
+ root,
267
+ slug: "example",
268
+ releaseLock: true,
269
+ });
270
+ assert.equal(repaired.current_iteration, 1);
271
+ assert.equal(repaired.last_completed_step, "developer_change");
272
+
273
+ const resumed = acquireLoop({
274
+ root,
275
+ slug: "example",
276
+ contractPath,
277
+ sessionId: "session-2",
278
+ actionId: "resume-2",
279
+ });
280
+ assert.equal(resumed.session_id, "session-2");
281
+ });
282
+ });
283
+
284
+ test("does not report a release retry as committed while crash locks remain", () => {
285
+ withRepo(({ root, contractPath }) => {
286
+ initExample(root, contractPath);
287
+ acquireLoop({
288
+ root,
289
+ slug: "example",
290
+ contractPath,
291
+ sessionId: "session-1",
292
+ actionId: "resume-1",
293
+ });
294
+
295
+ assert.throws(
296
+ () => releaseLoop({
297
+ root,
298
+ slug: "example",
299
+ sessionId: "session-1",
300
+ actionId: "release-1",
301
+ failpoint: "after_snapshot",
302
+ }),
303
+ (error) => error instanceof LoopStateError && error.code === "simulated_crash",
304
+ );
305
+ assert.throws(
306
+ () => releaseLoop({
307
+ root,
308
+ slug: "example",
309
+ sessionId: "session-1",
310
+ actionId: "release-1",
311
+ }),
312
+ (error) => error instanceof LoopStateError && error.code === "recovery_required",
313
+ );
314
+ fs.rmSync(
315
+ path.join(root, ".opencode/loops/example.lock/transition.lock"),
316
+ );
317
+ assert.throws(
318
+ () => releaseLoop({
319
+ root,
320
+ slug: "example",
321
+ sessionId: "session-1",
322
+ actionId: "release-1",
323
+ }),
324
+ (error) => error instanceof LoopStateError && error.code === "recovery_required",
325
+ );
326
+ assert.equal(
327
+ fs.existsSync(path.join(root, ".opencode/loops/example.lock")),
328
+ true,
329
+ );
330
+
331
+ const repaired = repairLoopState({
332
+ root,
333
+ slug: "example",
334
+ releaseLock: true,
335
+ });
336
+ assert.equal(repaired.lease, null);
337
+ });
338
+ });
339
+
340
+ test("detects corrupt snapshots and repairs them from intact history", () => {
341
+ withRepo(({ root, contractPath }) => {
342
+ initExample(root, contractPath);
343
+ const statePath = path.join(root, ".opencode/loops/example.json");
344
+ fs.writeFileSync(statePath, "{broken");
345
+
346
+ assert.throws(
347
+ () => inspectLoopState({ root, slug: "example" }),
348
+ (error) => error instanceof LoopStateError && error.code === "state_corrupt",
349
+ );
350
+
351
+ const repaired = repairLoopState({ root, slug: "example" });
352
+ assert.equal(repaired.slug, "example");
353
+ assert.equal(repaired.last_action_id, "approve-1");
354
+ });
355
+ });
356
+
357
+ test("rejects structurally valid history that changes immutable state", () => {
358
+ withRepo(({ root, contractPath }) => {
359
+ initExample(root, contractPath);
360
+ acquireLoop({
361
+ root,
362
+ slug: "example",
363
+ contractPath,
364
+ sessionId: "session-1",
365
+ actionId: "resume-1",
366
+ });
367
+ const historyPath = path.join(root, ".opencode/loops/example.history.jsonl");
368
+ const events = fs
369
+ .readFileSync(historyPath, "utf8")
370
+ .trim()
371
+ .split("\n")
372
+ .map(JSON.parse);
373
+ events[1].state_after.git_baseline = "tampered";
374
+ fs.writeFileSync(
375
+ historyPath,
376
+ `${events.map((event) => JSON.stringify(event)).join("\n")}\n`,
377
+ );
378
+
379
+ assert.throws(
380
+ () => repairLoopState({ root, slug: "example", releaseLock: true }),
381
+ (error) => error instanceof LoopStateError && error.code === "history_corrupt",
382
+ );
383
+ });
384
+ });
385
+
386
+ test("repairs only an incomplete trailing journal record and rejects middle corruption", () => {
387
+ withRepo(({ root, contractPath }) => {
388
+ initExample(root, contractPath);
389
+ const historyPath = path.join(root, ".opencode/loops/example.history.jsonl");
390
+ fs.appendFileSync(historyPath, '{"sequence":2');
391
+
392
+ const repaired = repairLoopState({ root, slug: "example", truncateTail: true });
393
+ assert.equal(repaired.last_action_id, "approve-1");
394
+ assert.ok(fs.readFileSync(historyPath, "utf8").endsWith("\n"));
395
+
396
+ fs.writeFileSync(
397
+ historyPath,
398
+ '{"sequence":1,"broken":true}\n{"sequence":2}\n',
399
+ );
400
+ assert.throws(
401
+ () => repairLoopState({ root, slug: "example", truncateTail: true }),
402
+ (error) => error instanceof LoopStateError && error.code === "history_corrupt",
403
+ );
404
+ });
405
+ });
406
+
407
+ test("migrates a schema v0 snapshot only with explicit renewed approval", () => {
408
+ withRepo(({ root, contractPath }) => {
409
+ const statePath = path.join(root, ".opencode/loops/example.json");
410
+ fs.writeFileSync(
411
+ statePath,
412
+ `${JSON.stringify({
413
+ schema_version: 0,
414
+ slug: "example",
415
+ git_baseline: "old123",
416
+ current_iteration: 2,
417
+ last_completed_step: "reviewer_rejected",
418
+ blocking_cause: "needs_changes",
419
+ })}\n`,
420
+ );
421
+
422
+ assert.throws(
423
+ () => migrateLoopState({
424
+ root,
425
+ slug: "example",
426
+ contractPath,
427
+ sessionId: "session-2",
428
+ actionId: "migrate-1",
429
+ approvalStatus: "pending",
430
+ }),
431
+ (error) => error instanceof LoopStateError && error.code === "approval_required",
432
+ );
433
+
434
+ const migrated = migrateLoopState({
435
+ root,
436
+ slug: "example",
437
+ contractPath,
438
+ sessionId: "session-2",
439
+ actionId: "migrate-1",
440
+ approvalStatus: "approved",
441
+ });
442
+ assert.equal(migrated.schema_version, 1);
443
+ assert.equal(migrated.current_iteration, 2);
444
+ assert.equal(migrated.last_completed_step, "reviewer_rejected");
445
+ assert.equal(migrated.approval.status, "approved");
446
+ assert.equal(migrated.status, "approved");
447
+ });
448
+ });
449
+
450
+ test("releases only the owning session lease", () => {
451
+ withRepo(({ root, contractPath }) => {
452
+ initExample(root, contractPath);
453
+ acquireLoop({
454
+ root,
455
+ slug: "example",
456
+ contractPath,
457
+ sessionId: "session-1",
458
+ actionId: "resume-1",
459
+ });
460
+
461
+ assert.throws(
462
+ () => releaseLoop({
463
+ root,
464
+ slug: "example",
465
+ sessionId: "session-2",
466
+ actionId: "release-2",
467
+ }),
468
+ (error) => error instanceof LoopStateError && error.code === "lease_mismatch",
469
+ );
470
+
471
+ const released = releaseLoop({
472
+ root,
473
+ slug: "example",
474
+ sessionId: "session-1",
475
+ actionId: "release-1",
476
+ });
477
+ assert.equal(released.lease, null);
478
+ });
479
+ });
480
+
481
+ test("exposes the durable operations through the portable CLI", () => {
482
+ withRepo(({ root, contractPath }) => {
483
+ const init = spawnSync(
484
+ process.execPath,
485
+ [
486
+ scriptPath,
487
+ "init",
488
+ "--root",
489
+ root,
490
+ "--slug",
491
+ "example",
492
+ "--contract",
493
+ contractPath,
494
+ "--git-baseline",
495
+ "abc123",
496
+ "--session-id",
497
+ "session-1",
498
+ "--action-id",
499
+ "approve-1",
500
+ ],
501
+ { encoding: "utf8" },
502
+ );
503
+ assert.equal(init.status, 0, init.stderr);
504
+ assert.equal(JSON.parse(init.stdout).schema_version, 1);
505
+
506
+ const inspect = spawnSync(
507
+ process.execPath,
508
+ [scriptPath, "inspect", "--root", root, "--slug", "example"],
509
+ { encoding: "utf8" },
510
+ );
511
+ assert.equal(inspect.status, 0, inspect.stderr);
512
+ assert.equal(JSON.parse(inspect.stdout).last_action_id, "approve-1");
513
+ });
514
+ });
515
+
516
+ test("rejects a symlinked state ancestor that escapes the root", () => {
517
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-root-"));
518
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-outside-"));
519
+ try {
520
+ fs.mkdirSync(path.join(outside, "loops"));
521
+ fs.writeFileSync(
522
+ path.join(outside, "loops/example.md"),
523
+ "# Approved loop\n",
524
+ );
525
+ fs.symlinkSync(outside, path.join(root, ".opencode"));
526
+
527
+ assert.throws(
528
+ () => initLoopState({
529
+ root,
530
+ slug: "example",
531
+ contractPath: path.join(root, ".opencode/loops/example.md"),
532
+ gitBaseline: "abc123",
533
+ sessionId: "session-1",
534
+ actionId: "approve-1",
535
+ }),
536
+ (error) => error instanceof LoopStateError && error.code === "unsafe_path",
537
+ );
538
+ assert.equal(
539
+ fs.existsSync(path.join(outside, "loops/example.json")),
540
+ false,
541
+ );
542
+ } finally {
543
+ fs.rmSync(root, { recursive: true, force: true });
544
+ fs.rmSync(outside, { recursive: true, force: true });
545
+ }
546
+ });
547
+
548
+ test("does not follow a broken history symlink during initialization", () => {
549
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-root-"));
550
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-outside-"));
551
+ try {
552
+ fs.mkdirSync(path.join(root, ".opencode/loops"), { recursive: true });
553
+ const contractPath = path.join(root, ".opencode/loops/example.md");
554
+ const outsideTarget = path.join(outside, "created.jsonl");
555
+ fs.writeFileSync(contractPath, "# Approved loop\n");
556
+ fs.symlinkSync(
557
+ outsideTarget,
558
+ path.join(root, ".opencode/loops/example.history.jsonl"),
559
+ );
560
+
561
+ assert.throws(
562
+ () => initLoopState({
563
+ root,
564
+ slug: "example",
565
+ contractPath,
566
+ gitBaseline: "abc123",
567
+ sessionId: "session-1",
568
+ actionId: "approve-1",
569
+ }),
570
+ (error) => error instanceof LoopStateError && error.code === "state_exists",
571
+ );
572
+ assert.equal(fs.existsSync(outsideTarget), false);
573
+ } finally {
574
+ fs.rmSync(root, { recursive: true, force: true });
575
+ fs.rmSync(outside, { recursive: true, force: true });
576
+ }
577
+ });
@@ -798,12 +798,19 @@ function evaluateScenario(scenario, fixture, redact) {
798
798
  };
799
799
  }
800
800
 
801
- function buildReport(scenarios, observations, mode) {
801
+ export function computeCorpusDigest(scenarios) {
802
802
  const canonicalCorpus = `${scenarios
803
803
  .slice()
804
804
  .sort((left, right) => left.id.localeCompare(right.id))
805
805
  .map((scenario) => JSON.stringify(scenario))
806
806
  .join("\n")}\n`;
807
+ return `sha256:${crypto
808
+ .createHash("sha256")
809
+ .update(canonicalCorpus)
810
+ .digest("hex")}`;
811
+ }
812
+
813
+ function buildReport(scenarios, observations, mode) {
807
814
  const scenariosById = new Map(scenarios.map((scenario) => [scenario.id, scenario]));
808
815
  const observationsById = new Map(
809
816
  observations.map((observation) => [observation.scenario_id, observation]),
@@ -820,10 +827,7 @@ function buildReport(scenarios, observations, mode) {
820
827
  const status = aggregate(scenarioResults.map((result) => result.status));
821
828
  return {
822
829
  schema_version: 1,
823
- corpus_digest: `sha256:${crypto
824
- .createHash("sha256")
825
- .update(canonicalCorpus)
826
- .digest("hex")}`,
830
+ corpus_digest: computeCorpusDigest(scenarios),
827
831
  mode,
828
832
  operational_status: "ok",
829
833
  status,
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { execFileSync } from "node:child_process";
6
+ import { createHash } from "node:crypto";
6
7
 
7
8
  const DEFAULT_BUDGETS = {
8
9
  max_reviewers: 3,
@@ -108,16 +109,37 @@ function splitLines(text) {
108
109
  return text.split("\n").map((line) => line.trim()).filter(Boolean);
109
110
  }
110
111
 
112
+ function splitNull(text) {
113
+ return text.split("\0").filter(Boolean);
114
+ }
115
+
116
+ function assertSafeRepoPath(file) {
117
+ if (
118
+ typeof file !== "string"
119
+ || file.length === 0
120
+ || path.isAbsolute(file)
121
+ || /^[A-Za-z]:[\\/]/.test(file)
122
+ || file.split(/[\\/]/).includes("..")
123
+ || /[\u0000-\u001f\u007f]/u.test(file)
124
+ ) {
125
+ throw new Error(`unsafe_review_path: changed file path is not safe for review`);
126
+ }
127
+ return file;
128
+ }
129
+
111
130
  function getChangedFiles(cwd, options) {
112
- const stagedFiles = splitLines(maybeRunGit(cwd, ["diff", "--cached", "--name-only", options.base, "--"]));
113
- const unstagedFiles = options.staged ? [] : splitLines(maybeRunGit(cwd, ["diff", "--name-only", "--"]));
114
- const untrackedFiles = splitLines(maybeRunGit(cwd, ["ls-files", "--others", "--exclude-standard"]));
131
+ const stagedFiles = splitNull(maybeRunGit(cwd, ["diff", "--cached", "--name-only", "-z", options.base, "--"]));
132
+ const unstagedFiles = options.staged ? [] : splitNull(maybeRunGit(cwd, ["diff", "--name-only", "-z", "--"]));
133
+ const untrackedFiles = splitNull(maybeRunGit(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]));
115
134
 
116
135
  return {
117
- staged: stagedFiles,
118
- unstaged: unstagedFiles,
119
- untracked: untrackedFiles,
120
- reviewed: unique([...stagedFiles, ...unstagedFiles, ...(options.includeUntracked ? untrackedFiles : [])]),
136
+ staged: stagedFiles.map(assertSafeRepoPath),
137
+ unstaged: unstagedFiles.map(assertSafeRepoPath),
138
+ untracked: untrackedFiles.map(assertSafeRepoPath),
139
+ reviewed: unique(
140
+ [...stagedFiles, ...unstagedFiles, ...(options.includeUntracked ? untrackedFiles : [])]
141
+ .map(assertSafeRepoPath),
142
+ ),
121
143
  };
122
144
  }
123
145
 
@@ -406,8 +428,9 @@ function prepareReviewWorkspace(options) {
406
428
  droppedPatches.push({ file: item.file, bytes: item.patchBytes, reason: "max_total_patch_bytes" });
407
429
  continue;
408
430
  }
409
- const safeName = item.file.replace(/[^A-Za-z0-9_.-]+/g, "__");
410
- const rel = path.join("patches", `${safeName}.patch`);
431
+ const safeName = path.basename(item.file).replace(/[^A-Za-z0-9_.-]+/g, "__").slice(0, 80);
432
+ const pathDigest = createHash("sha256").update(item.file).digest("hex").slice(0, 16);
433
+ const rel = path.join("patches", `${pathDigest}-${safeName || "file"}.patch`);
411
434
  fs.writeFileSync(path.join(workspace, rel), [
412
435
  "BEGIN_UNTRUSTED_PATCH_DATA",
413
436
  item.patch,
@@ -536,6 +559,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
536
559
 
537
560
  export {
538
561
  DEFAULT_BUDGETS,
562
+ assertSafeRepoPath,
539
563
  buildExecutionPlan,
540
564
  classify,
541
565
  cleanupWorkspace,