harness-everything 1.2.1 → 1.3.0

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 (55) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/benchmarks/results/live-host/agy-2026-11-26-516-read-only/README.md +12 -0
  5. package/benchmarks/results/live-host/agy-2026-11-26-516-read-only/capture.sanitized.jsonl +5 -0
  6. package/benchmarks/results/live-host/codex-2026-11-26-488-post-tool-use/README.md +25 -0
  7. package/benchmarks/results/live-host/codex-2026-11-26-488-post-tool-use/capture.sanitized.jsonl +10 -0
  8. package/ci/fixtures/468-dispatch/agy-quota-PROVENANCE.md +19 -0
  9. package/ci/fixtures/468-dispatch/agy-quota-direct-individual.stderr +2 -0
  10. package/ci/fixtures/468-dispatch/agy-quota-direct-third-party.stderr +2 -0
  11. package/ci/fixtures/468-dispatch/agy-quota-exec-individual.log +3 -0
  12. package/ci/mechanism-2am-observations-session-import.test.js +1 -0
  13. package/ci/mechanism-2w-platform-compatibility.test.js +1 -2
  14. package/ci/mechanism-34-observations.test.js +37 -1
  15. package/ci/mechanism-397-opencode-observations.test.js +4 -3
  16. package/ci/mechanism-468-dispatch-cli.test.js +1496 -4
  17. package/ci/mechanism-516-windows-verify-and-shell.test.js +74 -19
  18. package/ci/mechanism-548-bigint-identity.test.js +531 -0
  19. package/ci/mechanism-error-ledger-oracle.test.js +786 -3
  20. package/ci/mechanism-error-ledger-scan.test.js +981 -0
  21. package/ci/mechanism-report-writer.test.js +47 -1
  22. package/ci/mechanism-system-one-cycle.test.js +47 -2
  23. package/ci/openai-plugin-submission.test.js +26 -8
  24. package/docs/error-handling/details/c8-dispatch-cli.md +109 -13
  25. package/docs/openai-plugin.md +6 -10
  26. package/docs/platform-capabilities.md +15 -0
  27. package/docs/routing.md +2 -0
  28. package/error-ledger-bootstrap/SKILL.md +1 -1
  29. package/error-ledger-bootstrap/references/workflow.md +42 -7
  30. package/error-ledger-bootstrap/scripts/promote.js +8 -6
  31. package/error-ledger-bootstrap/scripts/scan.js +525 -12
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +3 -2
  34. package/hooks/scripts/state-persist.js +6 -1
  35. package/opencode-plugin/plugin.json +1 -1
  36. package/package.json +1 -1
  37. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  38. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  39. package/plugins/harness-everything/hooks/scripts/state-persist.js +6 -1
  40. package/plugins/harness-everything/plugin.json +1 -1
  41. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  42. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +42 -7
  43. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +8 -6
  44. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +525 -12
  45. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  46. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +3 -2
  47. package/sbom.cdx.json +7 -7
  48. package/scripts/build-openai-submission.js +8 -4
  49. package/scripts/dispatch.js +499 -87
  50. package/scripts/error-ledger-oracle.js +521 -27
  51. package/scripts/errors-sync.js +4 -3
  52. package/scripts/report-writer.js +4 -3
  53. package/submission/openai/README.md +9 -14
  54. package/submission/openai/listing.json +1 -1
  55. package/submission/openai/test-cases.json +1 -1
@@ -1,14 +1,105 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- const { spawnSync } = require('node:child_process');
4
+ const { spawn } = require('node:child_process');
5
5
  const fs = require('node:fs');
6
6
  const path = require('node:path');
7
7
 
8
8
  const REPORT_WRITER = path.join(__dirname, 'report-writer.js');
9
- const USAGE = 'Usage: dispatch --runner <codex|opencode> --model <id> --packet <path> --worktree <path> --scratch <absolute-path> --report <path> [--effort <low|medium|high|xhigh>] [--dry-run] [--json] [--help]';
10
- const VALUE_OPTIONS = new Set(['--runner', '--model', '--packet', '--worktree', '--scratch', '--report', '--effort']);
9
+ const USAGE = 'Usage: dispatch --runner <codex|opencode|agy> --model <id> --packet <path> --worktree <path> --scratch <absolute-path> --report <path> [--effort <low|medium|high|xhigh>] [--assignment <path>] [--admission-policy <path>] [--dry-run] [--json] [--help]';
10
+ const VALUE_OPTIONS = new Set(['--runner', '--model', '--packet', '--worktree', '--scratch', '--report', '--effort', '--assignment', '--admission-policy']);
11
+ const POOL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
12
+ const SUPPORTED_RUNNERS = new Set(['codex', 'opencode', 'agy']);
11
13
  const CODEX_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh']);
14
+ const AGY_SETTINGS = '{"permissions":{"allow":["command(*)","read_file(*)"]}}';
15
+ const READINESS_TIMEOUT_MS = 120000;
16
+ const EXECUTION_TIMEOUT_MS = 2700000;
17
+ // I544: one diagnostic-pair recognizer shared by readiness and execution. The captured `error:` line
18
+ // and its `AGY_ERROR` JSON companion must both be present, valid and describe the same supported pool.
19
+ // Advice text, reset value and redacted identifier are deliberately not pinned.
20
+ const AGY_QUOTA_ERROR_LINE = /^error: (Third-party|Individual) quota reached\.\s+.+\s+Resets in .+\.$/;
21
+ const AGY_ERROR_LINE = /^AGY_ERROR: (\{.*\})$/;
22
+
23
+ // #466 D-gate. Managed mode is entered only by --assignment <sidecar JSON>. C8 owns admission
24
+ // (one runner-profile decision + this registry); the assignment owns which actor runs each gate.
25
+ // `unsandboxed` gates need a loopback-capable profile; `any` gates are worker-compatible everywhere.
26
+ const GATE_REGISTRY = new Map([
27
+ ['verify:all', 'unsandboxed'],
28
+ ['verify:all --fast', 'unsandboxed'],
29
+ ['npm run test:consistency', 'any'],
30
+ ['npm run test:references', 'any'],
31
+ ['npm run test:portability', 'any'],
32
+ ]);
33
+ const FOCUSED_NODE_TEST_PREFIX = 'node --test ';
34
+ const FOCUSED_NODE_TEST_SEGMENT = /^[A-Za-z0-9_.-]+$/;
35
+ const GATE_ACTORS = new Set(['worker', 'coordinator']);
36
+
37
+ function isFocusedNodeTest(id) {
38
+ if (!id.startsWith(FOCUSED_NODE_TEST_PREFIX)) return false;
39
+ const operand = id.slice(FOCUSED_NODE_TEST_PREFIX.length);
40
+ if (!operand.endsWith('.js') || operand.startsWith('/')) return false;
41
+ const segments = operand.split('/');
42
+ if (segments.some(seg => !seg || seg === '.' || seg === '..' || !FOCUSED_NODE_TEST_SEGMENT.test(seg))) return false;
43
+ return segments.at(-1).length > 3;
44
+ }
45
+
46
+ // The single runner-profile decision: codex runs `-s workspace-write` and agy requests `--sandbox`
47
+ // (not treated as an unsandboxed loopback-capable profile). Only opencode is unsandboxed.
48
+ function runnerProfile(runner) {
49
+ return { sandboxed: runner === 'codex' || runner === 'agy' };
50
+ }
51
+
52
+ function gateRequirement(id) {
53
+ if (GATE_REGISTRY.has(id)) return GATE_REGISTRY.get(id);
54
+ return isFocusedNodeTest(id) ? 'any' : null;
55
+ }
56
+
57
+ function isPlainObject(value) {
58
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
59
+ }
60
+
61
+ function assignmentInvalid(message) {
62
+ fail(19, 'GATE_ASSIGNMENT_INVALID', 'gate', message);
63
+ }
64
+
65
+ function loadGateAssignment(file, worktree, runner) {
66
+ const resolved = pathFrom(worktree, file);
67
+ let parsed;
68
+ try {
69
+ if (!fs.statSync(resolved).isFile()) assignmentInvalid('--assignment must name an existing file');
70
+ parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
71
+ } catch (cause) {
72
+ if (cause instanceof DispatchFailure) throw cause;
73
+ assignmentInvalid(`--assignment is unreadable or not JSON: ${cause.code || 'parse error'}`);
74
+ }
75
+ if (!isPlainObject(parsed) || Object.keys(parsed).sort().join() !== 'gates,schemaVersion') {
76
+ assignmentInvalid('assignment must be an object with exactly schemaVersion and gates');
77
+ }
78
+ if (parsed.schemaVersion !== 1) assignmentInvalid('assignment schemaVersion must be 1');
79
+ if (!Array.isArray(parsed.gates)) assignmentInvalid('assignment gates must be an array');
80
+ const seen = new Set();
81
+ const gates = { worker: [], coordinator: [] };
82
+ const entries = [];
83
+ for (const gate of parsed.gates) {
84
+ if (!isPlainObject(gate) || Object.keys(gate).sort().join() !== 'actor,id') assignmentInvalid('each gate must be an object with exactly id and actor');
85
+ if (typeof gate.id !== 'string' || !GATE_ACTORS.has(gate.actor)) assignmentInvalid('gate id must be a string and actor must be worker or coordinator');
86
+ if (seen.has(gate.id)) assignmentInvalid(`duplicate gate id: ${gate.id}`);
87
+ seen.add(gate.id);
88
+ if (!gateRequirement(gate.id)) assignmentInvalid(`unknown gate id: ${gate.id}`);
89
+ entries.push(gate);
90
+ }
91
+ // Admission is decided only after the whole assignment validates, so a bad entry is never masked by a refusal.
92
+ for (const gate of entries) {
93
+ if (gate.actor === 'worker' && gateRequirement(gate.id) === 'unsandboxed' && runnerProfile(runner).sandboxed) {
94
+ const reason = runner === 'agy'
95
+ ? 'agy requests --sandbox and is not treated as an unsandboxed loopback-capable profile'
96
+ : `${runner} runs sandboxed`;
97
+ fail(18, 'GATE_REFUSED', 'gate', `worker gate "${gate.id}" needs an unsandboxed profile; ${reason}. Assign it to the coordinator.`);
98
+ }
99
+ gates[gate.actor].push(gate.id);
100
+ }
101
+ return gates;
102
+ }
12
103
  let evidencePaths = {};
13
104
 
14
105
  class DispatchFailure extends Error {
@@ -77,14 +168,25 @@ function isGitRoot(directory) {
77
168
  function canonicalFuturePath(file) {
78
169
  let ancestor = path.resolve(file);
79
170
  const suffix = [];
80
- while (!fs.existsSync(ancestor)) {
81
- const parent = path.dirname(ancestor);
82
- if (parent === ancestor) break;
83
- suffix.unshift(path.basename(ancestor));
84
- ancestor = parent;
171
+ while (true) {
172
+ try {
173
+ fs.lstatSync(ancestor);
174
+ } catch (cause) {
175
+ if (cause?.code === 'ENOENT') {
176
+ const parent = path.dirname(ancestor);
177
+ if (parent === ancestor) break;
178
+ suffix.unshift(path.basename(ancestor));
179
+ ancestor = parent;
180
+ continue;
181
+ }
182
+ return null;
183
+ }
184
+ const canonicalAncestor = realPath(ancestor);
185
+ if (!canonicalAncestor) return null;
186
+ return path.resolve(canonicalAncestor, ...suffix);
85
187
  }
86
- const canonicalAncestor = realPath(ancestor);
87
- return canonicalAncestor ? path.resolve(canonicalAncestor, ...suffix) : path.resolve(file);
188
+ const canonicalRoot = realPath(ancestor);
189
+ return canonicalRoot ? path.resolve(canonicalRoot, ...suffix) : path.resolve(file);
88
190
  }
89
191
 
90
192
  function gitAncestor(directory) {
@@ -97,25 +199,175 @@ function gitAncestor(directory) {
97
199
  }
98
200
  }
99
201
 
100
- function validateScratch(value) {
101
- if (!path.isAbsolute(value)) fail(11, 'UNSAFE_SCRATCH', 'validation', 'scratch must be an absolute path outside every Git repository or worktree');
102
- const scratch = canonicalFuturePath(value);
202
+ function isPathInsideOrEqual(parent, child) {
203
+ const rel = path.relative(parent, child);
204
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
205
+ }
206
+
207
+ function validateExternalDir(value, onFail, label) {
208
+ if (typeof value !== 'string' || !value.trim() || !path.isAbsolute(value)) {
209
+ onFail(`${label} must be an absolute path outside every Git repository or worktree`);
210
+ }
211
+ const canonical = canonicalFuturePath(value);
212
+ if (!canonical) {
213
+ onFail(`${label} cannot be resolved (dangling symlink or unresolved symlink chain)`);
214
+ }
103
215
  if (fs.existsSync(value) && !fs.statSync(value).isDirectory()) {
104
- fail(11, 'UNSAFE_SCRATCH', 'validation', 'scratch must be a directory outside every Git repository or worktree');
216
+ onFail(`${label} must be a directory outside every Git repository or worktree`);
217
+ }
218
+ const repository = gitAncestor(canonical);
219
+ if (repository) onFail(`${label} is inside a Git repository or worktree: ${repository}`);
220
+ return { resolved: path.resolve(value), canonical };
221
+ }
222
+
223
+ function validateScratch(value) {
224
+ return validateExternalDir(value, message => fail(11, 'UNSAFE_SCRATCH', 'validation', message), 'scratch').resolved;
225
+ }
226
+
227
+ // #466 D-admission. Managed mode requires --admission-policy <path>, mapping opaque pool ids to
228
+ // positive integer caps and (runner, model) routes to a pool id, plus one shared external dir.
229
+ function admissionInvalid(message) {
230
+ fail(21, 'ADMISSION_POLICY_INVALID', 'admission', message);
231
+ }
232
+
233
+ function loadAdmissionPolicy(file, worktree, scratch, runner, model) {
234
+ if (file === undefined) admissionInvalid('managed mode requires --admission-policy <path>');
235
+ const resolved = pathFrom(worktree, file);
236
+ let parsed;
237
+ try {
238
+ if (!fs.statSync(resolved).isFile()) admissionInvalid('--admission-policy must name an existing file');
239
+ parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
240
+ } catch (cause) {
241
+ if (cause instanceof DispatchFailure) throw cause;
242
+ admissionInvalid(`--admission-policy is unreadable or not JSON: ${cause.code || 'parse error'}`);
243
+ }
244
+ if (!isPlainObject(parsed) || Object.keys(parsed).sort().join() !== 'dir,pools,routes,schemaVersion') {
245
+ admissionInvalid('admission policy must be an object with exactly schemaVersion, dir, pools, and routes');
246
+ }
247
+ if (parsed.schemaVersion !== 1) admissionInvalid('admission policy schemaVersion must be 1');
248
+ const dirInfo = validateExternalDir(parsed.dir, admissionInvalid, 'admission dir');
249
+ const scratchCanonical = canonicalFuturePath(scratch);
250
+ if (isPathInsideOrEqual(scratchCanonical, dirInfo.canonical) || isPathInsideOrEqual(dirInfo.canonical, scratchCanonical)) {
251
+ admissionInvalid('admission dir must be outside --scratch so per-run cleanup cannot touch reservations');
252
+ }
253
+ if (!isPlainObject(parsed.pools) || Object.keys(parsed.pools).length === 0) {
254
+ admissionInvalid('admission policy pools must be a non-empty object');
255
+ }
256
+ const pools = new Map();
257
+ for (const [poolId, spec] of Object.entries(parsed.pools)) {
258
+ if (!POOL_ID_PATTERN.test(poolId)) admissionInvalid(`invalid opaque pool id: ${poolId}`);
259
+ if (!isPlainObject(spec) || Object.keys(spec).join() !== 'cap' || !Number.isSafeInteger(spec.cap) || spec.cap < 1) {
260
+ admissionInvalid(`pool "${poolId}" must be an object with positive integer cap`);
261
+ }
262
+ pools.set(poolId, spec.cap);
263
+ }
264
+ if (!Array.isArray(parsed.routes)) admissionInvalid('admission policy routes must be an array');
265
+ const routeMap = new Map();
266
+ for (const route of parsed.routes) {
267
+ if (!isPlainObject(route) || Object.keys(route).sort().join() !== 'model,pool,runner') {
268
+ admissionInvalid('each admission route must be an object with exactly runner, model, and pool');
269
+ }
270
+ if (!SUPPORTED_RUNNERS.has(route.runner)) admissionInvalid(`unknown runner in admission route: ${route.runner}`);
271
+ if (typeof route.model !== 'string' || !route.model.trim()) admissionInvalid('admission route model must be a non-empty string');
272
+ if (typeof route.pool !== 'string' || !pools.has(route.pool)) admissionInvalid(`admission route references unknown pool: ${route.pool}`);
273
+ const routeKey = `${route.runner}\0${route.model.trim()}`;
274
+ if (routeMap.has(routeKey)) admissionInvalid(`duplicate admission route for ${route.runner} model "${route.model.trim()}"`);
275
+ routeMap.set(routeKey, route.pool);
276
+ }
277
+ const selectedPool = routeMap.get(`${runner}\0${model}`);
278
+ if (!selectedPool) admissionInvalid(`no admission pool configured for ${runner} model "${model}"`);
279
+ return { dir: dirInfo.resolved, pool: selectedPool, cap: pools.get(selectedPool) };
280
+ }
281
+
282
+ function createSlotFile(slotPath, pool, slot) {
283
+ const record = {
284
+ schemaVersion: 1,
285
+ pool,
286
+ slot,
287
+ holderPid: process.pid,
288
+ childPid: null,
289
+ startedAt: new Date().toISOString(),
290
+ };
291
+ fs.writeFileSync(slotPath, `${JSON.stringify(record)}\n`, { flag: 'wx' });
292
+ return { ...record, slotPath, released: false };
293
+ }
294
+
295
+ // #466 F1: automatic stale-slot reclamation is disabled for the pilot. Any existing slot file
296
+ // (live, abandoned, corrupt, or indeterminate) counts as occupied until the normal owner releases
297
+ // it or the coordinator clears it with the pool quiesced and holder/child confirmed absent.
298
+ function acquireAdmissionSlot(admission) {
299
+ const poolDir = path.join(admission.dir, admission.pool);
300
+ fs.mkdirSync(poolDir, { recursive: true });
301
+ const resolvedPoolDir = realPath(poolDir);
302
+ const repository = resolvedPoolDir && gitAncestor(resolvedPoolDir);
303
+ if (!resolvedPoolDir || repository) {
304
+ admissionInvalid(`admission dir resolves inside a Git repository or worktree: ${repository || poolDir}`);
305
+ }
306
+ for (let slot = 0; slot < admission.cap; slot += 1) {
307
+ const slotPath = path.join(poolDir, `slot-${slot}.json`);
308
+ try {
309
+ return createSlotFile(slotPath, admission.pool, slot);
310
+ } catch (cause) {
311
+ if (cause?.code !== 'EEXIST') throw cause;
312
+ }
105
313
  }
106
- const repository = gitAncestor(scratch);
107
- if (repository) fail(11, 'UNSAFE_SCRATCH', 'validation', `scratch is inside a Git repository or worktree: ${repository}`);
108
- return path.resolve(value);
314
+ fail(22, 'ADMISSION_CAP_REACHED', 'admission', `admission pool "${admission.pool}" is at cap ${admission.cap}; refusing before spawn`);
315
+ }
316
+
317
+ function updateReservationChild(reservation, childPid) {
318
+ if (!reservation || reservation.released) return;
319
+ reservation.childPid = childPid;
320
+ const payload = `${JSON.stringify({
321
+ schemaVersion: 1,
322
+ pool: reservation.pool,
323
+ slot: reservation.slot,
324
+ holderPid: reservation.holderPid,
325
+ childPid: reservation.childPid,
326
+ startedAt: reservation.startedAt,
327
+ })}\n`;
328
+ const tmpPath = `${reservation.slotPath}.tmp-${process.pid}-${Date.now()}`;
329
+ try {
330
+ fs.writeFileSync(tmpPath, payload);
331
+ fs.renameSync(tmpPath, reservation.slotPath);
332
+ } catch {
333
+ try { fs.unlinkSync(tmpPath); } catch {}
334
+ try { fs.writeFileSync(reservation.slotPath, payload); } catch {}
335
+ }
336
+ }
337
+
338
+ function releaseAdmissionSlot(reservation) {
339
+ if (!reservation || reservation.released) return;
340
+ reservation.released = true;
341
+ try {
342
+ const parsed = JSON.parse(fs.readFileSync(reservation.slotPath, 'utf8'));
343
+ if (parsed.holderPid === reservation.holderPid && parsed.startedAt === reservation.startedAt) {
344
+ fs.unlinkSync(reservation.slotPath);
345
+ }
346
+ } catch {}
109
347
  }
110
348
 
111
349
  function pathFrom(base, value) {
112
350
  return path.resolve(base, value);
113
351
  }
114
352
 
353
+ function existsOrSymlink(file) {
354
+ try { fs.lstatSync(file); return true; } catch { return false; }
355
+ }
356
+
357
+ function worktreeRelativePath(worktree, target, label) {
358
+ const canonical = canonicalFuturePath(target);
359
+ if (!canonical) fail(10, 'INVALID_INPUT', 'input', `${label} cannot be resolved inside --worktree for agy`);
360
+ const rel = path.relative(worktree, canonical);
361
+ if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
362
+ fail(10, 'INVALID_INPUT', 'input', `${label} must be inside --worktree for agy`);
363
+ }
364
+ return rel.replace(/\\/g, '/');
365
+ }
366
+
115
367
  function validateInput(options) {
116
368
  const runner = options['--runner'];
117
369
  const model = options['--model'];
118
- if (!['codex', 'opencode'].includes(runner)) fail(10, 'INVALID_INPUT', 'input', '--runner must be codex or opencode');
370
+ if (!['codex', 'opencode', 'agy'].includes(runner)) fail(10, 'INVALID_INPUT', 'input', '--runner must be codex, opencode, or agy');
119
371
  if (!model || !model.trim()) fail(10, 'INVALID_INPUT', 'input', '--model must be a nonempty id');
120
372
  const effort = options['--effort'];
121
373
  if (effort !== undefined && runner !== 'codex') fail(10, 'INVALID_INPUT', 'input', '--effort is only supported for codex');
@@ -135,9 +387,18 @@ function validateInput(options) {
135
387
  if (!fs.existsSync(path.dirname(report)) || !fs.statSync(path.dirname(report)).isDirectory()) {
136
388
  fail(10, 'INVALID_INPUT', 'input', '--report parent directory must already exist');
137
389
  }
138
- if (fs.existsSync(report)) fail(10, 'INVALID_INPUT', 'input', '--report already exists; choose a fresh report path');
390
+ if (existsOrSymlink(report)) fail(10, 'INVALID_INPUT', 'input', '--report already exists; choose a fresh report path');
391
+ const packetRelative = runner === 'agy' ? worktreeRelativePath(worktree, packet, '--packet') : undefined;
392
+ const reportRelative = runner === 'agy' ? worktreeRelativePath(worktree, report, '--report') : undefined;
139
393
  const scratch = validateScratch(options['--scratch']);
140
- return { runner, model: model.trim(), effort, packet, worktree, scratch, report };
394
+ const trimmedModel = model.trim();
395
+ const managed = options['--assignment'] !== undefined;
396
+ if (!managed && options['--admission-policy'] !== undefined) {
397
+ fail(10, 'INVALID_INPUT', 'input', '--admission-policy is only supported in managed mode (--assignment)');
398
+ }
399
+ const gates = managed ? loadGateAssignment(options['--assignment'], worktree, runner) : undefined;
400
+ const admission = managed ? loadAdmissionPolicy(options['--admission-policy'], worktree, scratch, runner, trimmedModel) : undefined;
401
+ return { runner, model: trimmedModel, effort, packet, packetRelative, worktree, scratch, report, reportRelative, gates, admission };
141
402
  }
142
403
 
143
404
  function response(options, outcome, evidence = evidencePaths, input) {
@@ -150,9 +411,16 @@ function response(options, outcome, evidence = evidencePaths, input) {
150
411
  };
151
412
  const runner = input?.runner ?? options['--runner'];
152
413
  const model = input?.model ?? options['--model'];
153
- if (runner === 'codex' || runner === 'opencode') result.runner = runner;
414
+ if (runner === 'codex' || runner === 'opencode' || runner === 'agy') result.runner = runner;
154
415
  if (model) result.model = model;
155
416
  if (input?.effort) result.effort = input.effort;
417
+ if (runner === 'agy') result.sandbox = 'requested';
418
+ if (input?.gates) result.gates = input.gates;
419
+ if (input?.admission) {
420
+ result.admission = input.admission.slot !== undefined
421
+ ? { pool: input.admission.pool, cap: input.admission.cap, slot: input.admission.slot }
422
+ : { pool: input.admission.pool, cap: input.admission.cap };
423
+ }
156
424
  if (outcome.argv) result.argv = outcome.argv;
157
425
  if (outcome.cwd) result.cwd = outcome.cwd;
158
426
  const paths = Object.fromEntries(Object.entries(evidence).filter(([, value]) => value && fs.existsSync(value)));
@@ -171,27 +439,89 @@ function childTimeout(timeout) {
171
439
  : timeout;
172
440
  }
173
441
 
174
- function runChild(command, args, worktree, scratch, logPath, timeout, appendLog = false) {
175
- const result = spawnSync(command, args, {
176
- cwd: worktree,
177
- env: { ...process.env, TMPDIR: scratch },
178
- encoding: 'utf8',
179
- stdio: ['ignore', 'pipe', 'pipe'],
180
- timeout: childTimeout(timeout),
181
- maxBuffer: 16 * 1024 * 1024,
442
+ function runChild(command, args, worktree, scratch, logPath, timeout, appendLog = false, reservation = null) {
443
+ return new Promise((resolve, reject) => {
444
+ let settled = false;
445
+ let timedOut = false;
446
+ let childError;
447
+ const stdoutChunks = [];
448
+ const stderrChunks = [];
449
+ let stdoutBytes = 0;
450
+ let stderrBytes = 0;
451
+ const maxBuffer = 16 * 1024 * 1024;
452
+
453
+ const child = spawn(command, args, {
454
+ cwd: worktree,
455
+ env: { ...process.env, TMPDIR: scratch },
456
+ stdio: ['ignore', 'pipe', 'pipe'],
457
+ });
458
+
459
+ if (reservation && Number.isSafeInteger(child.pid) && child.pid > 0) {
460
+ updateReservationChild(reservation, child.pid);
461
+ }
462
+
463
+ const limit = childTimeout(timeout);
464
+ let killTimer = null;
465
+ const timer = setTimeout(() => {
466
+ timedOut = true;
467
+ try { child.kill('SIGTERM'); } catch {}
468
+ killTimer = setTimeout(() => {
469
+ try { child.kill('SIGKILL'); } catch {}
470
+ }, 100);
471
+ killTimer.unref();
472
+ }, limit);
473
+ timer.unref();
474
+
475
+ function finish(status, signal) {
476
+ if (settled) return;
477
+ settled = true;
478
+ clearTimeout(timer);
479
+ if (killTimer) clearTimeout(killTimer);
480
+ if (reservation) updateReservationChild(reservation, null);
481
+ try {
482
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8');
483
+ const stderr = Buffer.concat(stderrChunks).toString('utf8');
484
+ const log = `${stdout}${stderr ? `${stdout ? '\n' : ''}[stderr]\n${stderr}` : ''}`;
485
+ if (appendLog) fs.appendFileSync(logPath, log);
486
+ else fs.writeFileSync(logPath, log);
487
+ const error = timedOut
488
+ ? Object.assign(new Error(`spawn ${command} ETIMEDOUT`), { code: 'ETIMEDOUT' })
489
+ : childError;
490
+ resolve({ status: timedOut ? null : status, signal, error, stdout, stderr });
491
+ } catch (cause) {
492
+ reject(cause);
493
+ }
494
+ }
495
+
496
+ child.stdout?.on('data', chunk => {
497
+ if (stdoutBytes < maxBuffer) {
498
+ stdoutChunks.push(chunk);
499
+ stdoutBytes += chunk.length;
500
+ }
501
+ });
502
+ child.stderr?.on('data', chunk => {
503
+ if (stderrBytes < maxBuffer) {
504
+ stderrChunks.push(chunk);
505
+ stderrBytes += chunk.length;
506
+ }
507
+ });
508
+ child.on('error', err => {
509
+ childError = err;
510
+ finish(null, null);
511
+ });
512
+ child.on('close', (status, signal) => {
513
+ finish(status, signal);
514
+ });
182
515
  });
183
- const stdout = result.stdout || '';
184
- const stderr = result.stderr || '';
185
- const log = `${stdout}${stderr ? `${stdout ? '\n' : ''}[stderr]\n${stderr}` : ''}`;
186
- if (appendLog) fs.appendFileSync(logPath, log);
187
- else fs.writeFileSync(logPath, log);
188
- return { ...result, stdout, stderr };
189
516
  }
190
517
 
191
- function runnerArgs(input, prompt, outputPath) {
518
+ function runnerArgs(input, prompt, outputPath, timeoutMs = EXECUTION_TIMEOUT_MS) {
192
519
  if (input.runner === 'codex') {
193
520
  return ['exec', '-m', input.model, ...(input.effort ? ['-c', `model_reasoning_effort="${input.effort}"`] : []), '-s', 'workspace-write', '-C', input.worktree, '-o', outputPath, prompt];
194
521
  }
522
+ if (input.runner === 'agy') {
523
+ return ['-p', prompt, '--model', input.model, '--mode', 'accept-edits', '--sandbox', '--settings', AGY_SETTINGS, '--print-timeout', `${Math.ceil(timeoutMs / 1000)}s`];
524
+ }
195
525
  return ['run', '--auto', '-m', input.model, prompt];
196
526
  }
197
527
 
@@ -221,20 +551,43 @@ function withoutHostLabel(text) {
221
551
  return lines.slice(0, -1).join('\n').trim();
222
552
  }
223
553
 
224
- function readinessDiagnostic(runner, stderr) {
225
- const output = stderr.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
554
+ function stripAnsi(text) {
555
+ return text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
556
+ }
557
+
558
+ function agyQuotaDiagnostic(result) {
559
+ if (result.status !== 3 || result.signal || result.error) return null;
560
+ const lines = stripAnsi(result.stderr).split(/\r?\n/);
561
+ const errors = lines.filter(line => AGY_QUOTA_ERROR_LINE.test(line));
562
+ const envelopes = lines.filter(line => line.startsWith('AGY_ERROR:'));
563
+ if (errors.length !== 1 || envelopes.length !== 1) return null;
564
+ const pool = AGY_QUOTA_ERROR_LINE.exec(errors[0])[1];
565
+ let payload;
566
+ try {
567
+ payload = JSON.parse(AGY_ERROR_LINE.exec(envelopes[0])?.[1] ?? '');
568
+ } catch {
569
+ return null;
570
+ }
571
+ if (!isPlainObject(payload) || payload.status !== 'RESOURCE_EXHAUSTED' || payload.error_code !== 429) return null;
572
+ if (typeof payload.short_error !== 'string' || !payload.short_error.includes(`${pool} quota reached.`)) return null;
573
+ return { code: 'RUNNER_QUOTA', message: 'Select an authorized runner or model with available quota.' };
574
+ }
575
+
576
+ function readinessDiagnostic(runner, result) {
577
+ if (runner === 'agy') return agyQuotaDiagnostic(result);
578
+ const output = stripAnsi(result.stderr);
226
579
  const lines = output.split(/\r?\n/);
227
580
  const matches = READINESS_DIAGNOSTICS[runner].filter(diagnostic => lines.includes(diagnostic.line));
228
581
  return matches.length === 1 ? matches[0] : null;
229
582
  }
230
583
 
231
- function readiness(input, paths) {
584
+ async function readiness(input, paths, reservation = null) {
232
585
  const outputPath = input.runner === 'codex' ? paths.readinessOutput : null;
233
586
  const prompt = 'Reply with the single word READY';
234
- const result = runChild(input.runner, runnerArgs(input, prompt, outputPath), input.worktree, input.scratch, paths.readinessLog, 120000);
587
+ const result = await runChild(input.runner, runnerArgs(input, prompt, outputPath, READINESS_TIMEOUT_MS), input.worktree, input.scratch, paths.readinessLog, READINESS_TIMEOUT_MS, false, reservation);
235
588
  if (result.status !== 0) {
236
589
  const diagnostic = Number.isInteger(result.status) && result.status !== 0 && !result.signal && !result.error
237
- ? readinessDiagnostic(input.runner, result.stderr)
590
+ ? readinessDiagnostic(input.runner, result)
238
591
  : null;
239
592
  if (diagnostic) fail(13, diagnostic.code, 'readiness', diagnostic.message);
240
593
  fail(12, 'NOT_READY', 'readiness', 'Readiness failed. Keep the available child evidence.');
@@ -253,68 +606,127 @@ function reportedStatus(raw) {
253
606
  lines.pop();
254
607
  while (lines.length && lines.at(-1).trim() === '') lines.pop(); // live codex -o: blank line before the label
255
608
  }
256
- const line = lines.at(-1) || '';
609
+ const line = (lines.at(-1) || '').replace(/[ \t]+$/, '');
257
610
  if (line === 'STATUS: DONE') return { status: 'DONE' };
258
611
  const blocked = /^STATUS: BLOCKED: (.+)$/.exec(line);
259
- if (blocked && blocked[1].trim()) return { status: 'BLOCKED', reason: blocked[1].trim() };
612
+ if (blocked && blocked[1] === blocked[1].trim() && blocked[1]) return { status: 'BLOCKED', reason: blocked[1] };
260
613
  fail(16, 'REPORT_INVALID', 'report', 'Codex output must end with STATUS: DONE or STATUS: BLOCKED: <reason>');
261
614
  }
262
615
 
263
- function reportWriter(input, paths, command, args) {
264
- const result = runChild(process.execPath, [REPORT_WRITER, ...args], input.worktree, input.scratch, paths.writerLog, 120000, true);
616
+ async function reportWriter(input, paths, command, args) {
617
+ const result = await runChild(process.execPath, [REPORT_WRITER, ...args], input.worktree, input.scratch, paths.writerLog, 120000, true);
265
618
  if (result.status !== 0) fail(16, 'REPORT_INVALID', 'report', result.stderr.trim() || `${command} rejected the report`);
266
619
  return result;
267
620
  }
268
621
 
269
622
  function executionPrompt(input) {
270
- return input.runner === 'codex'
271
- ? `Execute the packet at ${input.packet} and return the complete report body.`
272
- : `Execute the packet at ${input.packet} and write the complete report to ${input.report}.`;
623
+ if (input.runner === 'codex') {
624
+ return `Execute the packet at ${input.packet} and return the complete report body.`;
625
+ }
626
+ if (input.runner === 'agy') {
627
+ return `Execute the packet at ${input.packetRelative} and write the complete report to ${input.reportRelative}. Use only paths relative to the current directory.`;
628
+ }
629
+ return `Execute the packet at ${input.packet} and write the complete report to ${input.report}.`;
273
630
  }
274
631
 
275
- function execute(input, options) {
632
+ // #466 D-scratch. In managed mode --scratch is the canonical external ROOT; every attempt gets its own
633
+ // unique directory below it (the child TMPDIR). The root was validated outside every repository, and the
634
+ // created directory is re-checked after realpath so a swapped symlink cannot redirect it into one.
635
+ function createAttemptDir(input) {
276
636
  fs.mkdirSync(input.scratch, { recursive: true });
277
- const runId = `${process.pid}-${Date.now()}`;
278
- const paths = {
279
- readinessOutput: path.join(input.scratch, `${runId}.readiness.txt`),
280
- readinessLog: path.join(input.scratch, `${runId}.readiness.log`),
281
- rawOutput: path.join(input.scratch, `${runId}.raw.txt`),
282
- runLog: path.join(input.scratch, `${runId}.run.log`),
283
- writerLog: path.join(input.scratch, `${runId}.report-writer.log`),
284
- };
285
- evidencePaths = {
286
- readinessOutput: input.runner === 'codex' ? paths.readinessOutput : null,
287
- readinessLog: paths.readinessLog,
288
- rawOutput: input.runner === 'codex' ? paths.rawOutput : null,
289
- runLog: paths.runLog,
290
- reportWriterLog: paths.writerLog,
291
- report: input.report,
292
- };
637
+ const attempt = fs.mkdtempSync(path.join(input.scratch, 'attempt-'));
638
+ const resolved = realPath(attempt);
639
+ const repository = resolved && gitAncestor(resolved);
640
+ if (!resolved || repository) {
641
+ try { fs.rmSync(attempt, { recursive: true, force: true }); } catch {}
642
+ fail(11, 'UNSAFE_SCRATCH', 'validation', `attempt directory resolves inside a Git repository or worktree: ${repository || attempt}`);
643
+ }
644
+ return attempt;
645
+ }
293
646
 
294
- readiness(input, paths);
295
- if (fs.existsSync(input.report)) fail(16, 'REPORT_INVALID', 'report', 'report path was populated before execution; refusing stale delivery');
296
- const prompt = executionPrompt(input);
297
- const outputPath = input.runner === 'codex' ? paths.rawOutput : null;
298
- const run = runChild(input.runner, runnerArgs(input, prompt, outputPath), input.worktree, input.scratch, paths.runLog, 2700000);
299
- if (run.status !== 0) {
300
- const timedOut = run.error?.code === 'ETIMEDOUT';
301
- fail(15, timedOut ? 'RUN_TIMEOUT' : 'RUN_FAILED', 'execution', timedOut ? 'runner execution timed out' : `runner execution failed${run.error ? `: ${run.error.message}` : ''}`);
647
+ // A checked DONE copies its evidence to <root>/retained/<attempt>/ (outside the disposable run dir), verifies
648
+ // every copy, and only then removes its own attempt dir. Any failure keeps the run dir and its evidence.
649
+ function retainAndClean(input, attempt, paths) {
650
+ const retained = path.join(input.scratchRoot, 'retained', path.basename(attempt));
651
+ try {
652
+ fs.mkdirSync(retained, { recursive: true });
653
+ const moved = {};
654
+ for (const [key, source] of Object.entries(evidencePaths)) {
655
+ if (!source || source === input.report || !fs.existsSync(source)) continue;
656
+ const target = path.join(retained, path.basename(source));
657
+ fs.copyFileSync(source, target);
658
+ if (fs.statSync(target).size !== fs.statSync(source).size) throw new Error(`copy of ${path.basename(source)} is incomplete`);
659
+ moved[key] = target;
660
+ }
661
+ fs.rmSync(attempt, { recursive: true, force: true });
662
+ evidencePaths = { ...evidencePaths, ...moved };
663
+ } catch (cause) {
664
+ fail(20, 'EVIDENCE_RETENTION_FAILED', 'retention', `evidence retention failed; the attempt directory and its evidence were kept: ${cause.message}`);
302
665
  }
666
+ }
303
667
 
304
- if (input.runner === 'codex') {
305
- if (!fs.existsSync(paths.rawOutput) || fs.existsSync(input.report)) fail(16, 'REPORT_INVALID', 'report', 'fresh Codex output or report path is missing');
306
- const status = reportedStatus(fs.readFileSync(paths.rawOutput, 'utf8'));
307
- const writeArgs = ['write', '--from-codex-output', paths.rawOutput, '--output', input.report, '--status', status.status];
308
- if (status.reason) writeArgs.push('--reason', status.reason);
309
- reportWriter(input, paths, 'write', writeArgs);
310
- } else if (!fs.existsSync(input.report)) {
311
- fail(16, 'REPORT_INVALID', 'report', 'runner did not create a fresh report');
668
+ async function execute(input, options) {
669
+ const managed = input.gates !== undefined;
670
+ let reservation = null;
671
+ if (managed) {
672
+ reservation = acquireAdmissionSlot(input.admission);
673
+ input = { ...input, admission: { ...input.admission, slot: reservation.slot } };
312
674
  }
675
+ let attempt = null;
676
+ try {
677
+ if (managed) {
678
+ attempt = createAttemptDir(input);
679
+ input = { ...input, scratchRoot: input.scratch, scratch: attempt };
680
+ } else fs.mkdirSync(input.scratch, { recursive: true });
681
+ const runId = `${process.pid}-${Date.now()}`;
682
+ const paths = {
683
+ readinessOutput: path.join(input.scratch, `${runId}.readiness.txt`),
684
+ readinessLog: path.join(input.scratch, `${runId}.readiness.log`),
685
+ rawOutput: path.join(input.scratch, `${runId}.raw.txt`),
686
+ runLog: path.join(input.scratch, `${runId}.run.log`),
687
+ writerLog: path.join(input.scratch, `${runId}.report-writer.log`),
688
+ };
689
+ evidencePaths = {
690
+ readinessOutput: input.runner === 'codex' ? paths.readinessOutput : null,
691
+ readinessLog: paths.readinessLog,
692
+ rawOutput: input.runner === 'codex' ? paths.rawOutput : null,
693
+ runLog: paths.runLog,
694
+ reportWriterLog: paths.writerLog,
695
+ report: input.report,
696
+ };
697
+
698
+ await readiness(input, paths, reservation);
699
+ if (existsOrSymlink(input.report)) fail(16, 'REPORT_INVALID', 'report', 'report path was populated before execution; refusing stale delivery');
700
+ const prompt = executionPrompt(input);
701
+ const outputPath = input.runner === 'codex' ? paths.rawOutput : null;
702
+ const run = await runChild(input.runner, runnerArgs(input, prompt, outputPath, EXECUTION_TIMEOUT_MS), input.worktree, input.scratch, paths.runLog, EXECUTION_TIMEOUT_MS, false, reservation);
703
+ if (run.status !== 0) {
704
+ if (input.runner === 'agy' && !existsOrSymlink(input.report)) {
705
+ const diagnostic = agyQuotaDiagnostic(run);
706
+ if (diagnostic) fail(13, diagnostic.code, 'execution', diagnostic.message);
707
+ }
708
+ const timedOut = run.error?.code === 'ETIMEDOUT';
709
+ fail(15, timedOut ? 'RUN_TIMEOUT' : 'RUN_FAILED', 'execution', timedOut ? 'runner execution timed out' : `runner execution failed${run.error ? `: ${run.error.message}` : ''}`);
710
+ }
313
711
 
314
- const checked = reportWriter(input, paths, 'check', ['check', '--file', input.report]);
315
- if (/valid \(STATUS: BLOCKED: (.+)\)/.test(checked.stdout)) {
316
- const reason = /valid \(STATUS: BLOCKED: (.+)\)/.exec(checked.stdout)[1];
317
- fail(17, 'WORKER_BLOCKED', 'report', `worker delivered a valid BLOCKED report: ${reason}`);
712
+ if (input.runner === 'codex') {
713
+ if (!fs.existsSync(paths.rawOutput) || existsOrSymlink(input.report)) fail(16, 'REPORT_INVALID', 'report', 'fresh Codex output or report path is missing');
714
+ const status = reportedStatus(fs.readFileSync(paths.rawOutput, 'utf8'));
715
+ const writeArgs = ['write', '--from-codex-output', paths.rawOutput, '--output', input.report, '--status', status.status];
716
+ if (status.reason) writeArgs.push('--reason', status.reason);
717
+ await reportWriter(input, paths, 'write', writeArgs);
718
+ } else if (!existsOrSymlink(input.report) || !fs.lstatSync(input.report).isFile()) {
719
+ fail(16, 'REPORT_INVALID', 'report', 'runner did not create a fresh report');
720
+ }
721
+
722
+ const checked = await reportWriter(input, paths, 'check', ['check', '--file', input.report]);
723
+ if (/valid \(STATUS: BLOCKED: (.+)\)/.test(checked.stdout)) {
724
+ const reason = /valid \(STATUS: BLOCKED: (.+)\)/.exec(checked.stdout)[1];
725
+ fail(17, 'WORKER_BLOCKED', 'report', `worker delivered a valid BLOCKED report: ${reason}`);
726
+ }
727
+ if (managed) retainAndClean(input, attempt, paths);
728
+ } finally {
729
+ releaseAdmissionSlot(reservation);
318
730
  }
319
731
  response(options, {
320
732
  exitCode: 0,
@@ -324,7 +736,7 @@ function execute(input, options) {
324
736
  }, evidencePaths, input);
325
737
  }
326
738
 
327
- function main() {
739
+ async function main() {
328
740
  const argv = process.argv.slice(2);
329
741
  const jsonRequested = argv.includes('--json');
330
742
  let options = { '--json': jsonRequested };
@@ -351,7 +763,7 @@ function main() {
351
763
  }, evidencePaths, input);
352
764
  return;
353
765
  }
354
- execute(input, options);
766
+ await execute(input, options);
355
767
  } catch (cause) {
356
768
  if (cause instanceof DispatchFailure) {
357
769
  response(options, cause, evidencePaths, input);