harness-everything 0.56.0 → 0.57.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +23 -0
  4. package/benchmarks/results/live-host/claude-2026-11-21-ledger-lesson/README.md +33 -0
  5. package/benchmarks/results/live-host/claude-2026-11-21-ledger-lesson/trace.jsonl +13 -0
  6. package/ci/fixtures/394-claude-ledger-lesson/post-tool-use-failure.json +13 -0
  7. package/ci/fixtures/394-claude-ledger-lesson/pre-tool-use.json +10 -0
  8. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-failure.json +17 -0
  9. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-success.json +17 -0
  10. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-unknown.json +15 -0
  11. package/ci/fixtures/394-codex-ledger-lesson/pre-tool-use.json +12 -0
  12. package/ci/fixtures/394-ledger-match/commitlint-empty-subject.txt +5 -0
  13. package/ci/fixtures/394-ledger-match/commitlint-subject-case.txt +5 -0
  14. package/ci/fixtures/394-ledger-match/provisional-candidates.json +20 -0
  15. package/ci/fixtures/394-ledger-match/quoted-match-record.md +25 -0
  16. package/ci/fixtures/468-dispatch/runner.js +30 -4
  17. package/ci/mechanism-394-claude-ledger-lesson.test.js +176 -0
  18. package/ci/mechanism-394-codex-ledger-lesson.test.js +203 -0
  19. package/ci/mechanism-394-ledger-match.test.js +507 -0
  20. package/ci/mechanism-394-opencode-ledger-lesson.test.js +232 -0
  21. package/ci/mechanism-468-dispatch-cli.test.js +143 -5
  22. package/ci/mechanism-errors-sync-root.test.js +86 -4
  23. package/ci/mechanism-report-writer.test.js +13 -1
  24. package/docs/adr/ROUTE-001-error-lesson-delivery.md +52 -49
  25. package/docs/error-handling/details/c8-dispatch-cli.md +8 -4
  26. package/docs/governed-index.md +1 -1
  27. package/docs/platform-capabilities.md +4 -0
  28. package/hooks/hooks.json +22 -0
  29. package/hooks/scripts/codex-ledger-lesson.js +82 -0
  30. package/hooks/scripts/ledger-lesson.js +94 -0
  31. package/hooks/scripts/lib/ledger-match.js +452 -0
  32. package/opencode-plugin/index.mjs +113 -4
  33. package/opencode-plugin/plugin.json +1 -1
  34. package/package.json +1 -1
  35. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  36. package/plugins/harness-everything/hooks/hooks.json +24 -0
  37. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +82 -0
  38. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -0
  39. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +452 -0
  40. package/plugins/harness-everything/plugin.json +1 -1
  41. package/sbom.cdx.json +7 -7
  42. package/scripts/dispatch.js +31 -7
  43. package/scripts/errors-sync.js +63 -2
  44. package/scripts/report-writer.js +4 -2
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawnSync } = require('node:child_process');
8
+ const { pathToFileURL } = require('node:url');
9
+ const { test } = require('node:test');
10
+
11
+ const ROOT = path.resolve(__dirname, '..');
12
+ const PLUGIN = path.join(ROOT, 'opencode-plugin', 'index.mjs');
13
+ const LEDGER = path.join(ROOT, '.agents', 'harness-everything', 'errors');
14
+ const ERRORS_SYNC = path.join(ROOT, 'scripts', 'errors-sync.js');
15
+ const COMMITLINT = fs.readFileSync(path.join(__dirname, 'fixtures/394-ledger-match/commitlint-subject-case.txt'), 'utf8');
16
+ const OLD_ENV = Object.fromEntries(['HOME', 'USERPROFILE', 'HARNESS_STATE_HOME', 'HARNESS_TELEMETRY', 'HARNESS_SYSTEM_ONE_MODE']
17
+ .map(key => [key, process.env[key]]));
18
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'mechanism-394-opencode-ledger-'));
19
+
20
+ function isOutside(root, target) {
21
+ const relative = path.relative(root, target);
22
+ return relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
23
+ }
24
+
25
+ function addLedger(workspace) {
26
+ const target = path.join(workspace, '.agents', 'harness-everything', 'errors');
27
+ fs.cpSync(LEDGER, target, { recursive: true });
28
+ const generated = spawnSync(process.execPath, [ERRORS_SYNC, '--root', workspace], { cwd: ROOT, encoding: 'utf8' });
29
+ assert.equal(generated.status, 0, generated.stderr);
30
+ }
31
+
32
+ function packagePlugin() {
33
+ const installed = path.join(TMP, 'opencode-install');
34
+ const pluginDir = path.join(installed, 'plugins');
35
+ fs.mkdirSync(pluginDir, { recursive: true });
36
+ fs.copyFileSync(PLUGIN, path.join(pluginDir, 'harness-enforcement.mjs'));
37
+ for (const relative of [
38
+ 'harness-everything/scripts/kernel-router.js',
39
+ 'hooks/scripts/lib/observations.js',
40
+ 'hooks/scripts/lib/ledger-match.js',
41
+ 'hooks/scripts/lib/harness-state.js',
42
+ 'scripts/lib/workspace.js',
43
+ ]) {
44
+ const destination = path.join(installed, relative);
45
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
46
+ fs.copyFileSync(path.join(ROOT, relative), destination);
47
+ }
48
+ fs.cpSync(path.join(ROOT, 'hooks/scripts/lib/platforms'), path.join(installed, 'hooks/scripts/lib/platforms'), { recursive: true });
49
+ return path.join(pluginDir, 'harness-enforcement.mjs');
50
+ }
51
+
52
+ function createV2Context(sessionWorkspaces, pluginFile = PLUGIN) {
53
+ const toolHooks = new Map();
54
+ const sessionHooks = new Map();
55
+ const eventQueue = [];
56
+ let eventWaiter;
57
+ let currentEvent;
58
+ const ctx = {
59
+ location: { directory: ROOT },
60
+ tool: { hook: async (name, callback) => { toolHooks.set(name, callback); return { dispose: async () => {} }; } },
61
+ session: {
62
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: sessionWorkspaces[sessionID] } }),
63
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
64
+ prompt: async () => ({}),
65
+ context: async () => [],
66
+ },
67
+ event: {
68
+ subscribe: ({ signal }) => ({
69
+ [Symbol.asyncIterator]() {
70
+ return {
71
+ next: () => {
72
+ currentEvent?.resolve();
73
+ currentEvent = null;
74
+ if (eventQueue.length) {
75
+ currentEvent = eventQueue.shift();
76
+ return Promise.resolve({ value: currentEvent.event, done: false });
77
+ }
78
+ if (signal.aborted) return Promise.resolve({ done: true });
79
+ return new Promise(resolve => {
80
+ eventWaiter = resolve;
81
+ signal.addEventListener('abort', () => resolve({ done: true }), { once: true });
82
+ });
83
+ },
84
+ };
85
+ },
86
+ }),
87
+ },
88
+ };
89
+ return import(pathToFileURL(pluginFile).href).then(async mod => ({
90
+ toolHooks,
91
+ sessionHooks,
92
+ pushEvent: event => new Promise(resolve => {
93
+ const item = { event, resolve };
94
+ if (eventWaiter) {
95
+ currentEvent = item;
96
+ eventWaiter({ value: event, done: false });
97
+ eventWaiter = null;
98
+ } else eventQueue.push(item);
99
+ }),
100
+ dispose: await mod.default.setup(ctx),
101
+ }));
102
+ }
103
+
104
+ async function toolCall(harness, sessionID, id, status = 'completed', output = 'ok', exit = 0) {
105
+ const command = 'git commit -m "docs(errors): Bad Case"';
106
+ const before = { tool: 'bash', sessionID, agent: 'build', messageID: `message-${id}`, id, input: { command } };
107
+ const beforeSnapshot = structuredClone(before);
108
+ assert.equal(await harness.toolHooks.get('execute.before')(before), undefined);
109
+ assert.deepEqual(before, beforeSnapshot, 'execute.before does not change the tool request');
110
+
111
+ const after = {
112
+ ...before,
113
+ status,
114
+ ...(status === 'error'
115
+ ? { error: { name: 'ToolError', message: output } }
116
+ : { result: { output, metadata: { exit } } }),
117
+ };
118
+ const afterSnapshot = structuredClone(after);
119
+ assert.equal(await harness.toolHooks.get('execute.after')(after), undefined);
120
+ assert.deepEqual(after, afterSnapshot, 'execute.after does not change the host tool result');
121
+ }
122
+
123
+ async function context(harness, sessionID, base = 'base system') {
124
+ const event = { sessionID, kind: 'primary', system: [{ type: 'text', text: base }] };
125
+ await harness.sessionHooks.get('context')(event);
126
+ return event.system.map(part => part.text || '').join('\n');
127
+ }
128
+
129
+ test.after(() => {
130
+ for (const [key, value] of Object.entries(OLD_ENV)) {
131
+ if (value === undefined) delete process.env[key];
132
+ else process.env[key] = value;
133
+ }
134
+ fs.rmSync(TMP, { recursive: true, force: true });
135
+ });
136
+
137
+ test('OpenCode V2 carries real ledger matches through the source and packaged context hooks', async () => {
138
+ assert.ok(isOutside(ROOT, TMP), 'fixture state must stay outside the repository');
139
+ const home = path.join(TMP, 'home');
140
+ const workspace = path.join(TMP, 'workspace');
141
+ const otherWorkspace = path.join(TMP, 'other-workspace');
142
+ const emptyWorkspace = path.join(TMP, 'empty-workspace');
143
+ fs.mkdirSync(home, { recursive: true });
144
+ fs.mkdirSync(workspace, { recursive: true });
145
+ fs.mkdirSync(otherWorkspace, { recursive: true });
146
+ fs.mkdirSync(emptyWorkspace, { recursive: true });
147
+ addLedger(workspace);
148
+ addLedger(otherWorkspace);
149
+ process.env.HOME = home;
150
+ process.env.USERPROFILE = home;
151
+ process.env.HARNESS_STATE_HOME = path.join(TMP, 'harness-state');
152
+ process.env.HARNESS_TELEMETRY = 'off';
153
+ delete process.env.HARNESS_SYSTEM_ONE_MODE;
154
+
155
+ const sessionWorkspaces = {
156
+ same: workspace,
157
+ other: workspace,
158
+ separateWorkspace: otherWorkspace,
159
+ noLedger: emptyWorkspace,
160
+ disposal: workspace,
161
+ sessionCleanup: workspace,
162
+ };
163
+ const harness = await createV2Context(sessionWorkspaces);
164
+ const command = 'git -C x commit -m "docs(errors): Bad Case"';
165
+ try {
166
+ assert.ok(harness.toolHooks.has('execute.before') && harness.toolHooks.has('execute.after'));
167
+ assert.ok(harness.sessionHooks.has('context'));
168
+ assert.equal(harness.toolHooks.size, 2, 'the carrier registers no permission hook or additional tool gate');
169
+
170
+ const before = { tool: 'bash', sessionID: 'same', agent: 'build', messageID: 'message-same', id: 'same-action', input: { command } };
171
+ const beforeSnapshot = structuredClone(before);
172
+ assert.equal(await harness.toolHooks.get('execute.before')(before), undefined);
173
+ assert.deepEqual(before, beforeSnapshot);
174
+
175
+ const failure = {
176
+ ...before,
177
+ status: 'error',
178
+ error: { name: 'ToolError', message: COMMITLINT },
179
+ };
180
+ const failureSnapshot = structuredClone(failure);
181
+ assert.equal(await harness.toolHooks.get('execute.after')(failure), undefined);
182
+ assert.deepEqual(failure, failureSnapshot, 'the failed shell result remains untouched');
183
+
184
+ const wrongSessionSystem = [{ type: 'text', text: 'base system' }];
185
+ await harness.sessionHooks.get('context')({ sessionID: 'other', kind: 'primary', system: wrongSessionSystem });
186
+ assert.deepEqual(wrongSessionSystem, [{ type: 'text', text: 'base system' }], 'a pending lesson stays bound to its session');
187
+
188
+ const delivered = await context(harness, 'same');
189
+ assert.equal((delivered.match(/Cue:\n/g) || []).length, 2,
190
+ 'action selection runs in execute.before and failure selection in execute.after; both arrive at the next model request');
191
+ assert.match(delivered, /subject-case/);
192
+ assert.equal(await context(harness, 'same'), 'base system', 'a delivered phase is not replayed on another context build');
193
+
194
+ await toolCall(harness, 'other', 'other-action', 'completed', COMMITLINT, 0);
195
+ assert.equal((await context(harness, 'other')).match(/Cue:\n/g)?.length, 1,
196
+ 'diagnostic text with a zero exit remains action-only in a second session');
197
+
198
+ await toolCall(harness, 'separateWorkspace', 'workspace-action', 'completed', COMMITLINT, 1);
199
+ assert.equal((await context(harness, 'separateWorkspace')).match(/Cue:\n/g)?.length, 2,
200
+ 'a completed tool result with nonzero metadata.exit and captured diagnostics selects failure too');
201
+
202
+ await toolCall(harness, 'noLedger', 'no-ledger-action');
203
+ assert.equal(await context(harness, 'noLedger'), 'base system', 'an unrelated workspace without a ledger is silent');
204
+
205
+ await toolCall(harness, 'sessionCleanup', 'session-cleanup-action');
206
+ const state = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js'));
207
+ const sessionState = state.getSessionDir(workspace, 'sessionCleanup', { workspace_root: workspace, session_id: 'sessionCleanup', host_id: 'opencode' });
208
+ const claims = fs.readdirSync(sessionState).filter(file => file.endsWith('.claim'));
209
+ assert.equal(claims.length, 1);
210
+ await harness.pushEvent({ type: 'session.deleted', sessionID: 'sessionCleanup' });
211
+ assert.ok(claims.every(file => !fs.existsSync(path.join(sessionState, file))),
212
+ 'session invalidation releases an undelivered matcher reservation');
213
+
214
+ await harness.toolHooks.get('execute.before')({
215
+ tool: 'bash', sessionID: 'disposal', agent: 'build', messageID: 'message-disposal', id: 'pending-action', input: { command },
216
+ });
217
+ } finally {
218
+ await harness.dispose();
219
+ }
220
+
221
+ const packaged = await createV2Context(sessionWorkspaces, packagePlugin());
222
+ try {
223
+ await packaged.toolHooks.get('execute.before')({
224
+ tool: 'bash', sessionID: 'disposal', agent: 'build', messageID: 'message-disposal-2', id: 'pending-action-2', input: { command },
225
+ });
226
+ const packagedDelivery = await context(packaged, 'disposal');
227
+ assert.match(packagedDelivery, /subject-case/,
228
+ 'disposing the prior carrier releases an undelivered claim, and the packaged loader resolves the shared matcher');
229
+ } finally {
230
+ await packaged.dispose();
231
+ }
232
+ });
@@ -162,7 +162,7 @@ function assertEvent(event, testCase, runner, phase, model = runner === 'codex'
162
162
  assert.equal(event.stdinIsCharacterDevice, true);
163
163
  assert.equal(event.args[event.args.indexOf('-m') + 1], model);
164
164
  assert.equal(event.args.at(-1), phase === 'readiness'
165
- ? 'Reply exactly with READY.'
165
+ ? 'Reply with the single word READY'
166
166
  : `Execute the packet at ${packet} and ${runner === 'codex' ? 'return the complete report body.' : `write the complete report to ${testCase.report}.`}`);
167
167
  }
168
168
 
@@ -184,7 +184,9 @@ function assertNoExecutionAfterReadinessFailure(testCase, runner, response, mode
184
184
  assert.equal(response.phase, 'readiness');
185
185
  assert.equal(response.runner, runner);
186
186
  assert.equal(response.model, model);
187
- assert.deepEqual(Object.keys(response).sort(), ['code', 'evidence', 'message', 'model', 'ok', 'phase', 'runner'].sort());
187
+ const expectedKeys = ['code', 'evidence', 'message', 'model', 'ok', 'phase', 'runner'];
188
+ if (response.effort) expectedKeys.push('effort');
189
+ assert.deepEqual(Object.keys(response).sort(), expectedKeys.sort());
188
190
  const actualEvents = events(testCase);
189
191
  assert.equal(actualEvents.length, 1, 'refusal must make one readiness call and no execution or fallback call');
190
192
  assertEvent(actualEvents[0], testCase, runner, 'readiness', model);
@@ -202,7 +204,24 @@ function assertReadinessRefusal(testCase, runner, response, model = runner === '
202
204
  assertNoExecutionAfterReadinessFailure(testCase, runner, response, model);
203
205
  }
204
206
 
205
- function runSuccessAndArgvMatch(runner, requestedModel = runner === 'codex' ? 'fixture/codex-model' : 'fixture/opencode-model') {
207
+ function assertReadinessAnswer(runner, response, answer) {
208
+ const output = runner === 'codex' ? response.evidence.readinessOutput : response.evidence.readinessLog;
209
+ const raw = fs.readFileSync(output, 'utf8');
210
+ assert.equal(runner === 'codex' ? raw : raw.split('\n[stderr]\n')[0], answer);
211
+ }
212
+
213
+ function assertEffortArgs(args, effort) {
214
+ const setting = args.indexOf('-c');
215
+ if (effort) {
216
+ assert.ok(setting >= 0);
217
+ assert.equal(args[setting + 1], `model_reasoning_effort="${effort}"`);
218
+ } else {
219
+ assert.equal(setting, -1);
220
+ assert.equal(args.some(arg => arg.startsWith('model_reasoning_effort=')), false);
221
+ }
222
+ }
223
+
224
+ function runSuccessAndArgvMatch(runner, requestedModel = runner === 'codex' ? 'fixture/codex-model' : 'fixture/opencode-model', config = {}) {
206
225
  const testCase = makeCase(`${runner} success`);
207
226
  const model = requestedModel.trim();
208
227
  const args = argsFor(testCase, runner, requestedModel);
@@ -214,7 +233,7 @@ function runSuccessAndArgvMatch(runner, requestedModel = runner === 'codex' ? 'f
214
233
  assertNoRunner(testCase);
215
234
  assertNoScratchOrReport(testCase);
216
235
 
217
- const result = jsonResponse(cli([...args, '--json'], testCase), 0, 'DONE');
236
+ const result = jsonResponse(cli([...args, '--json'], testCase, config), 0, 'DONE');
218
237
  assert.equal(result.runner, runner);
219
238
  assert.equal(result.model, model);
220
239
  assert.equal(fs.existsSync(testCase.scratch), true);
@@ -388,6 +407,60 @@ try {
388
407
  runSuccessAndArgvMatch(runner, ` ${runner === 'codex' ? 'fixture/codex-model' : 'fixture/opencode-model'} `);
389
408
  });
390
409
 
410
+ for (const { scenario, answer } of [
411
+ { scenario: 'ready-period', answer: 'READY.\n' },
412
+ { scenario: 'ready-padded-period', answer: ' \tREADY. \n' },
413
+ // Advisor answer 3: the label object is an opaque wrapper; its fields are not validated here.
414
+ { scenario: 'ready-bad-schema-label', answer: 'READY\n<!-- harness-label {"bad":true} -->\n' },
415
+ { scenario: 'ready-host-label', answer: 'READY\n<!-- harness-label {"v":1,"validity":"actionable","tier":"tier1","intents":[],"workflow":"deferred","skills":[]} -->\n' },
416
+ ]) {
417
+ check(`${runner} accepts trimmed ${scenario} through the real entry and validates a fresh report`, () => {
418
+ const testCase = makeCase(`${runner} ${scenario}`);
419
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, { readiness: scenario }), 0, 'DONE');
420
+ assertReadinessAnswer(runner, response, answer);
421
+ assert.equal(fs.readFileSync(response.evidence.report, 'utf8'), 'Fixture completed the packet.\nSTATUS: DONE\n');
422
+ const actualEvents = events(testCase);
423
+ assert.equal(actualEvents.length, 2, 'one readiness and one execution; no retry or fallback');
424
+ assertEvent(actualEvents[0], testCase, runner, 'readiness');
425
+ assertEvent(actualEvents[1], testCase, runner, 'execution');
426
+ });
427
+ }
428
+
429
+ for (const scenario of ['ready-now', 'not-ready', 'ready-two-dots', 'ready-lowercase', 'ready-commentary', 'ready-bad-label', 'ready-label-then-text']) {
430
+ check(`${runner} rejects readiness answer ${scenario}`, () => {
431
+ const testCase = makeCase(`${runner} ${scenario}`);
432
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, { readiness: scenario }), 12, 'NOT_READY');
433
+ assertReadinessRefusal(testCase, runner, response);
434
+ });
435
+ }
436
+
437
+ check(`${runner} nonzero readiness refuses even when stdout or raw output says READY.`, () => {
438
+ const testCase = makeCase(`${runner} READY period nonzero`);
439
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, { readiness: 'ready-period-failed' }), 12, 'NOT_READY');
440
+ assertReadinessAnswer(runner, response, 'READY.\n');
441
+ assertReadinessRefusal(testCase, runner, response);
442
+ });
443
+
444
+ check(`${runner} readiness timeout refuses after emitting READY.`, () => {
445
+ const testCase = makeCase(`${runner} READY period timeout`);
446
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, {
447
+ readiness: 'ready-period-timeout', testTimeoutMs: 300, outerTimeoutMs: 5000,
448
+ }), 12, 'NOT_READY');
449
+ assertReadinessAnswer(runner, response, 'READY.\n');
450
+ assertReadinessRefusal(testCase, runner, response);
451
+ assertProcessExited(events(testCase)[0].pid);
452
+ });
453
+
454
+ if (process.platform !== 'win32') {
455
+ check(`${runner} signaled readiness refuses even when it emits READY.`, () => {
456
+ const testCase = makeCase(`${runner} READY period signal`);
457
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, { readiness: 'ready-period-signal' }), 12, 'NOT_READY');
458
+ assertReadinessAnswer(runner, response, 'READY.\n');
459
+ assertReadinessRefusal(testCase, runner, response);
460
+ assertProcessExited(events(testCase)[0].pid);
461
+ });
462
+ }
463
+
391
464
  check(`${runner} supported provider text on successful READY does not refuse`, () => {
392
465
  const testCase = makeCase(`${runner} provider text on success`);
393
466
  const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, {
@@ -495,6 +568,65 @@ try {
495
568
  });
496
569
  }
497
570
 
571
+ for (const { label, runner, values } of [
572
+ { label: 'invalid value', values: ['--effort', 'ultra'] },
573
+ { label: 'missing value', values: ['--effort'] },
574
+ { label: 'duplicate value', values: ['--effort', 'low', '--effort', 'high'] },
575
+ { label: 'OpenCode runner', runner: 'opencode', values: ['--effort', 'low'] },
576
+ ]) {
577
+ check(`INVALID_INPUT effort ${label} refuses before spawn or writes`, () => {
578
+ const testCase = makeCase(`invalid effort ${label}`);
579
+ const argsForCase = [...argsFor(testCase, runner || 'codex'), ...values];
580
+ const response = jsonResponse(cli([...argsForCase, '--json'], testCase), 10, 'INVALID_INPUT');
581
+ assert.equal(response.phase, 'input');
582
+ assertNoRunner(testCase);
583
+ assertNoScratchOrReport(testCase);
584
+ });
585
+ }
586
+
587
+ for (const effort of ['low', 'medium', 'high', 'xhigh']) {
588
+ check(`Codex --effort ${effort} appears in dry-run JSON and both spawned argv arrays`, () => {
589
+ const testCase = makeCase(`Codex effort ${effort}`);
590
+ const args = [...argsFor(testCase), '--effort', effort];
591
+ const dryRun = jsonResponse(cli([...args, '--dry-run', '--json'], testCase), 0, 'DRY_RUN_OK');
592
+ assert.equal(dryRun.effort, effort);
593
+ assertEffortArgs(dryRun.argv.slice(1), effort);
594
+ assertNoRunner(testCase);
595
+ assertNoScratchOrReport(testCase);
596
+
597
+ const response = jsonResponse(cli([...args, '--json'], testCase), 0, 'DONE');
598
+ assert.equal(response.effort, effort);
599
+ const actualEvents = events(testCase);
600
+ assert.equal(actualEvents.length, 2);
601
+ for (const event of actualEvents) assertEffortArgs(event.args, effort);
602
+ const executionArgv = [actualEvents[1].runner, ...actualEvents[1].args];
603
+ const outputIndex = executionArgv.indexOf('-o') + 1;
604
+ executionArgv[outputIndex] = dryRun.argv[outputIndex];
605
+ assert.deepEqual(dryRun.argv, executionArgv);
606
+ assert.equal(fs.readFileSync(response.evidence.report, 'utf8'), 'Fixture completed the packet.\nSTATUS: DONE\n');
607
+ });
608
+ }
609
+
610
+ check('Codex omitted --effort leaves the default unoverridden and omits JSON effort', () => {
611
+ const testCase = makeCase('Codex default effort');
612
+ const args = argsFor(testCase);
613
+ const dryRun = jsonResponse(cli([...args, '--dry-run', '--json'], testCase), 0, 'DRY_RUN_OK');
614
+ assert.equal(dryRun.effort, undefined);
615
+ assertEffortArgs(dryRun.argv.slice(1), undefined);
616
+ const response = jsonResponse(cli([...args, '--json'], testCase), 0, 'DONE');
617
+ assert.equal(response.effort, undefined);
618
+ for (const event of events(testCase)) assertEffortArgs(event.args, undefined);
619
+ });
620
+
621
+ check('Codex validated effort remains in JSON when readiness refuses', () => {
622
+ const testCase = makeCase('Codex effort readiness refusal');
623
+ const response = jsonResponse(cli([...argsFor(testCase), '--effort', 'high', '--json'], testCase, { readiness: 'ready-failed' }), 12, 'NOT_READY');
624
+ assert.equal(response.effort, 'high');
625
+ assertReadinessAnswer('codex', response, 'READY\n');
626
+ assertReadinessRefusal(testCase, 'codex', response);
627
+ assertEffortArgs(events(testCase)[0].args, 'high');
628
+ });
629
+
498
630
  check('missing selected Codex executable -> NOT_READY without OpenCode fallback', () => {
499
631
  const testCase = makeCase('missing codex executable');
500
632
  const response = jsonResponse(cli([...argsFor(testCase, 'codex'), '--json'], testCase, { path: openCodeOnlyBin }), 12, 'NOT_READY');
@@ -510,6 +642,12 @@ try {
510
642
  assert.match(fs.readFileSync(response.evidence.reportWriterLog, 'utf8'), /stripped the terminal host label/);
511
643
  });
512
644
 
645
+ check('497 Codex raw output with a blank line before the host label is accepted', () => {
646
+ const testCase = makeCase('Codex host label after blank');
647
+ jsonResponse(cli([...argsFor(testCase), '--json'], testCase, { execution: 'raw-label-blank' }), 0, 'DONE');
648
+ assert.equal(fs.readFileSync(testCase.report, 'utf8'), 'Fixture completed the packet.\nSTATUS: DONE\n');
649
+ });
650
+
513
651
  for (const scenario of ['missing-raw', 'no-status', 'multiple-status', 'bad-label']) {
514
652
  check(`Codex ${scenario} -> REPORT_INVALID`, () => runReportInvalidCase('codex', scenario));
515
653
  }
@@ -528,7 +666,7 @@ try {
528
666
  check('entry usage mentions every option used by the CLI contract', () => {
529
667
  const testCase = makeCase('usage options');
530
668
  const response = jsonResponse(cli(['--help', '--json'], testCase), 0, 'HELP');
531
- for (const option of ['--runner', '--model', '--packet', '--worktree', '--scratch', '--report', '--dry-run', '--json', '--help']) {
669
+ for (const option of ['--runner', '--model', '--packet', '--worktree', '--scratch', '--report', '--effort', '--dry-run', '--json', '--help']) {
532
670
  assert.ok(response.message.includes(option), `usage is missing ${option}`);
533
671
  }
534
672
  });
@@ -57,6 +57,87 @@ function seedLedger(name) {
57
57
  return { root, dir, index: path.join(dir, 'index.jsonl'), record: path.join(dir, 'E-0001-root-test.md') };
58
58
  }
59
59
 
60
+ const ACTION_RULE = { tool: 'shell', executable: 'git', subcommand: 'commit' };
61
+
62
+ function recordWithMatch(match) {
63
+ const metadata = { id: 'E-0003', signature: 'schema-test', class: 'test', scope: 'in', status: 'lesson', match };
64
+ return `---\n${JSON.stringify(metadata)}\n---\nA schema fixture.\n`;
65
+ }
66
+
67
+ let invalidMatchNumber = 0;
68
+ function assertInvalidMatch(label, match) {
69
+ const root = path.join(temp, `invalid match ${++invalidMatchNumber}`);
70
+ const dir = path.join(root, '.agents', 'harness-everything', 'errors');
71
+ const record = 'E-0003-schema-test.md';
72
+ fs.mkdirSync(dir, { recursive: true });
73
+ fs.writeFileSync(path.join(dir, record), recordWithMatch(match));
74
+
75
+ const result = invoke(['--root', root]);
76
+ assert.notEqual(result.status, 0, `${label}: errors:sync rejects malformed match data`);
77
+ assert.ok(result.stderr.includes(record), `${label}: errors:sync names the malformed record: ${result.stderr}`);
78
+ assert.equal(fs.existsSync(path.join(dir, 'index.jsonl')), false, `${label}: malformed data does not publish an index`);
79
+ }
80
+
81
+ function assertMatchSchema() {
82
+ const rows = render().trimEnd().split('\n').map(JSON.parse);
83
+ const e3 = rows.find(row => row.id === 'E-0003');
84
+ assert.deepEqual(e3.match, {
85
+ actions: [ACTION_RULE],
86
+ failures: [{ ...ACTION_RULE, diagnostics: ['subject-case', 'header-max-length', 'type-empty', 'subject-empty'] }],
87
+ }, 'the real E-0003 row carries both match rule lists');
88
+ const e3Text = fs.readFileSync(path.join(ROOT, e3.file), 'utf8');
89
+ const rawFrontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(e3Text)[1].replace(/\r\n?/g, '\n');
90
+ const expectedBinding = crypto.createHash('sha256').update(JSON.stringify([
91
+ rawFrontmatter, e3.id, e3.signature, e3.file, e3.match
92
+ ])).digest('hex');
93
+ assert.equal(e3.matchBinding, expectedBinding, 'the binding hashes normalized raw frontmatter and the generated rule row');
94
+ assert.equal(Object.hasOwn(rows.find(row => row.id === 'E-0001'), 'match'), false,
95
+ 'records without match keep the field absent');
96
+
97
+ const boundaryRoot = path.join(temp, 'match boundary repo');
98
+ const boundaryDir = path.join(boundaryRoot, '.agents', 'harness-everything', 'errors');
99
+ fs.mkdirSync(boundaryDir, { recursive: true });
100
+ const boundaryMatch = {
101
+ actions: Array.from({ length: 8 }, (_, i) => ({
102
+ tool: 'shell', executable: i === 0 ? 'a'.repeat(64) : 'git', subcommand: i === 0 ? 'c' : `cmd${i}`,
103
+ })),
104
+ failures: Array.from({ length: 8 }, (_, i) => ({
105
+ ...ACTION_RULE,
106
+ subcommand: `cmd${i}`,
107
+ diagnostics: i === 0 ? Array.from({ length: 16 }, (_, j) => `diag-${j}`) : ['x'],
108
+ })),
109
+ };
110
+ fs.writeFileSync(path.join(boundaryDir, 'E-0003-schema-test.md'), recordWithMatch(boundaryMatch));
111
+ assert.deepEqual(JSON.parse(render(boundaryRoot).trim()).match, boundaryMatch,
112
+ 'schema accepts the 1/64-character, 8-rule, and 16-diagnostic boundaries');
113
+
114
+ const failure = (overrides = {}) => ({ ...ACTION_RULE, ...overrides });
115
+ const malformed = [
116
+ ['match mapping', null],
117
+ ['match has a supported field', { actions: [ACTION_RULE], unknown: [] }],
118
+ ['match contains actions or failures', {}],
119
+ ['actions is an array', { actions: ACTION_RULE }],
120
+ ['actions has at least one rule', { actions: [] }],
121
+ ['actions has at most eight rules', { actions: Array(9).fill(ACTION_RULE) }],
122
+ ['action rule is a mapping', { actions: ['git'] }],
123
+ ['action rule has exact keys', { actions: [failure({ extra: true })] }],
124
+ ['action tool is shell', { actions: [failure({ tool: 'git' })] }],
125
+ ['executable is lowercase', { actions: [failure({ executable: 'Git' })] }],
126
+ ['subcommand is a literal id', { actions: [failure({ subcommand: 'commit --amend' })] }],
127
+ ['literal id is at most 64 characters', { actions: [failure({ executable: 'a'.repeat(65) })] }],
128
+ ['failures is an array', { failures: ACTION_RULE }],
129
+ ['failures has at least one rule', { failures: [] }],
130
+ ['failures has at most eight rules', { failures: Array(9).fill({ ...ACTION_RULE, diagnostics: ['subject-case'] }) }],
131
+ ['failure rule has exact keys', { failures: [{ ...ACTION_RULE, diagnostics: ['subject-case'], extra: true }] }],
132
+ ['failure rule requires diagnostics', { failures: [ACTION_RULE] }],
133
+ ['diagnostics has 1 to 16 values', { failures: [{ ...ACTION_RULE, diagnostics: [] }] }],
134
+ ['diagnostics has at most 16 values', { failures: [{ ...ACTION_RULE, diagnostics: Array(17).fill('x') }] }],
135
+ ['diagnostics are unique', { failures: [{ ...ACTION_RULE, diagnostics: ['type-empty', 'type-empty'] }] }],
136
+ ['diagnostics are lowercase literal ids', { failures: [{ ...ACTION_RULE, diagnostics: ['Subject-Case'] }] }],
137
+ ];
138
+ for (const [label, match] of malformed) assertInvalidMatch(label, match);
139
+ }
140
+
60
141
  function assertUnsafeRefused(target, unchanged, tempDirs) {
61
142
  const before = unchanged.map(snapshot);
62
143
  const harnessBefore = fs.readFileSync(HARNESS_INDEX);
@@ -75,9 +156,10 @@ function assertUnsafeRefused(target, unchanged, tempDirs) {
75
156
 
76
157
  try {
77
158
  const harnessIndexDigest = digest(HARNESS_INDEX);
78
- const harnessIndex = fs.readFileSync(HARNESS_INDEX, 'utf8');
79
- assert.equal(invoke(['--check']).status, 0, 'the no-root Harness check is the regression control');
80
- assert.equal(render(), harnessIndex, 'render() defaults to the current Harness root');
159
+ assertMatchSchema();
160
+ const generatedControl = seedLedger('generated check control');
161
+ assert.equal(invoke(['--check', '--root', generatedControl.root]).status, 0,
162
+ 'errors-sync --check validates a generated temporary ledger');
81
163
  assert.ok(targetRoot.includes(' '), 'the target root must contain a space');
82
164
  assert.equal(isWithin(ROOT, targetRoot), false, 'the temporary target must stay outside the Harness root');
83
165
 
@@ -116,7 +198,7 @@ try {
116
198
  fs.copyFileSync(SCRIPT, isolatedScript);
117
199
  const isolatedInvoke = args => invokeScript(isolatedScript, args, isolatedDefault.root, {
118
200
  ...process.env,
119
- NODE_PATH: [path.join(ROOT, 'node_modules'), process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
201
+ NODE_PATH: [...require.resolve.paths('js-yaml'), process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
120
202
  });
121
203
  assert.equal(isolatedInvoke(['--check']).status, 0, 'no-root check uses its isolated default ledger');
122
204
  fs.writeFileSync(isolatedDefault.index, 'deliberately stale default ledger\n');
@@ -169,6 +169,19 @@ test('assembles BLOCKED from a raw body, blank line, and one EOF host label', t
169
169
  assertOk(run(['check', '--file', output]));
170
170
  });
171
171
 
172
+ test('497 accepts the live codex -o shape: STATUS, one blank line, then the EOF host label', t => {
173
+ const dir = tempDir(t);
174
+ const raw = path.join(dir, 'raw.txt');
175
+ const output = path.join(dir, 'report.md');
176
+ fs.writeFileSync(raw, `probe ok\nSTATUS: DONE\n\n${VALID_LABEL}`);
177
+
178
+ const result = run(writeArgs(output, 'DONE', ['--from-codex-output', raw]));
179
+
180
+ assertOk(result);
181
+ assert.equal(fs.readFileSync(output, 'utf8'), 'probe ok\nSTATUS: DONE\n');
182
+ assertOk(run(['check', '--file', output]));
183
+ });
184
+
172
185
  test('rejects embedded STATUS in body without changing an existing target', t => {
173
186
  const dir = tempDir(t);
174
187
  const output = path.join(dir, 'report.md');
@@ -257,7 +270,6 @@ test('rejects mismatched, malformed, duplicate, or trailing Codex controls and p
257
270
  ['Summary\nSTATUS: DONE\nSTATUS: DONE\n', 'DONE'],
258
271
  ['Summary\nSTATUS: DONE\n\n', 'DONE'],
259
272
  ['Summary\nSTATUS: DONE\ntext after status\n', 'DONE'],
260
- [`Summary\nSTATUS: DONE\n\n${VALID_LABEL}`, 'DONE'],
261
273
  [`Summary\nSTATUS: DONE\ntext\n${VALID_LABEL}`, 'DONE'],
262
274
  [`Summary\nSTATUS: DONE\n${VALID_LABEL}\n${VALID_LABEL}\n`, 'DONE'],
263
275
  [`Summary\nSTATUS: DONE\n${VALID_LABEL}\ntrailing text`, 'DONE'],