harness-everything 1.5.1 → 1.5.3

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.
@@ -10,7 +10,7 @@
10
10
  "name": "harness-everything",
11
11
  "source": "./",
12
12
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
13
- "version": "1.5.1",
13
+ "version": "1.5.3",
14
14
  "author": {
15
15
  "name": "Miya Daniel"
16
16
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-everything",
3
3
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
4
- "version": "1.5.1",
4
+ "version": "1.5.3",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [1.5.3](https://github.com/dyphn1/Harness-everything/compare/v1.5.2...v1.5.3) (2026-12-01)
6
+
7
+ ### Bug Fixes
8
+
9
+ * **dispatch:** report cache-inclusive token budgets ([b8667c7](https://github.com/dyphn1/Harness-everything/commit/b8667c733958f8ec3e3763f1c77aa0721cb16db9)), closes [#466](https://github.com/dyphn1/Harness-everything/issues/466)
10
+
11
+ ## [1.5.2](https://github.com/dyphn1/Harness-everything/compare/v1.5.1...v1.5.2) (2026-12-01)
12
+
13
+ ### Bug Fixes
14
+
15
+ * **reports:** reject padded finalized status lines ([1b4963c](https://github.com/dyphn1/Harness-everything/commit/1b4963c6ee2b3ec8c4f9b8237c720a6339e56202)), closes [#542](https://github.com/dyphn1/Harness-everything/issues/542)
16
+ * **router:** honor fable quote boundaries and negation ([bdd4e44](https://github.com/dyphn1/Harness-everything/commit/bdd4e44d62becc104385b72ab5f2ba4baedd9f72)), closes [#558](https://github.com/dyphn1/Harness-everything/issues/558)
17
+
5
18
  ## [1.5.1](https://github.com/dyphn1/Harness-everything/compare/v1.5.0...v1.5.1) (2026-12-01)
6
19
 
7
20
  ### Bug Fixes
@@ -5,9 +5,14 @@ const path = require('node:path');
5
5
 
6
6
  const ROOT = path.resolve(__dirname, '..');
7
7
  const ROUTER = path.join(ROOT, 'harness-everything', 'scripts', 'kernel-router.js');
8
+ const PACKAGED_ROUTER = path.join(ROOT, 'plugins', 'harness-everything', 'skills', 'harness-everything', 'scripts', 'kernel-router.js');
9
+ const ROUTERS = [
10
+ ['source', ROUTER],
11
+ ['packaged', PACKAGED_ROUTER],
12
+ ];
8
13
 
9
- function route(prompt) {
10
- const result = spawnSync(process.execPath, [ROUTER], {
14
+ function route(prompt, router = ROUTER) {
15
+ const result = spawnSync(process.execPath, [router], {
11
16
  cwd: ROOT,
12
17
  encoding: 'utf8',
13
18
  input: JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt }),
@@ -177,4 +182,95 @@ const quotedSeparator = route('Use “fable; use fable on opus” as an example'
177
182
  assert.notEqual(quotedSeparator.strategy, 'fable-staged');
178
183
  assert.ok(!quotedSeparator.reasonCodes.includes('explicit-strategy-request'));
179
184
 
185
+ const quotedFableExamples = [
186
+ '用「fable; use fable on opus」當例子說明',
187
+ '使用「fable; use fable on opus」作為範例',
188
+ '用『fable; use fable on opus』當例子說明',
189
+ 'Use 「fable; use fable on opus」 as an example',
190
+ 'Use 《fable; use fable on opus》 as an example',
191
+ ];
192
+ const polarityCases = [
193
+ {
194
+ prompt: '不要改用 fable 重構整個 repository architecture',
195
+ tier: 'tier3',
196
+ strategy: 'iterative-single',
197
+ },
198
+ {
199
+ prompt: 'Do not switch to fable; redesign the architecture across the repository',
200
+ tier: 'tier3',
201
+ strategy: 'iterative-single',
202
+ },
203
+ ];
204
+ const contradictionCases = [
205
+ '不要改用 fable;改用 fable-staged 做這個任務',
206
+ '改用 fable-staged 做這個任務;不要改用 fable',
207
+ 'Do not switch to fable; use fable-staged for this task',
208
+ 'Use fable-staged for this task; do not switch to fable',
209
+ 'Do not use fable; use fable-staged for this task',
210
+ ];
211
+
212
+ for (const [name, router] of ROUTERS) {
213
+ const quotedProhibitionWithOuterRequest = route('用「不要使用 fable」當例子說明;改用 fable-staged 重構整個 repository architecture', router);
214
+ assert.equal(quotedProhibitionWithOuterRequest.strategy, 'fable-staged', `${name}: quoted prohibition is data and the real outer request selects Fable`);
215
+ assert.ok(quotedProhibitionWithOuterRequest.reasonCodes.includes('explicit-strategy-request'), `${name}: outer request is explicit`);
216
+ assert.notEqual(quotedProhibitionWithOuterRequest.fallback.disposition, 'blocked', `${name}: quoted prohibition does not conflict with the outer request`);
217
+
218
+ const quoteBoundaryDoesNotJoin = route('Do not "example" fable; use fable-staged for this task', router);
219
+ assert.equal(quoteBoundaryDoesNotJoin.strategy, 'fable-staged', `${name}: excluding a quote does not join text into a false prohibition`);
220
+ assert.notEqual(quoteBoundaryDoesNotJoin.fallback.disposition, 'blocked', `${name}: quote removal does not manufacture a conflict`);
221
+
222
+ const unquotedContradiction = route('不要使用 fable;改用 fable-staged 重構整個 repository architecture', router);
223
+ assert.equal(unquotedContradiction.fallback.disposition, 'blocked', `${name}: unquoted prohibition still conflicts`);
224
+ assert.ok(unquotedContradiction.reasonCodes.includes('explicit-request-conflicts-with-prohibition'), `${name}: unquoted conflict is recorded`);
225
+
226
+ for (const prompt of quotedFableExamples) {
227
+ const plan = route(prompt, router);
228
+ assert.ok(!String(plan.strategy).startsWith('fable-'), `${name}: ${prompt}: quoted text selects no Fable strategy`);
229
+ assert.ok(!plan.reasonCodes.includes('explicit-strategy-request'), `${name}: ${prompt}: quoted text is not an explicit request`);
230
+ assert.ok(!plan.routerOutput.includes('REQUESTED FABLE PROFILE'), `${name}: ${prompt}: quoted profile is not requested`);
231
+ }
232
+
233
+ const quotedAndUnquoted = route('Use 「fable; use fable on opus」 as an example; use fable-staged for this task', router);
234
+ assert.equal(quotedAndUnquoted.strategy, 'fable-staged', `${name}: unquoted directive still selects Fable`);
235
+ assert.ok(quotedAndUnquoted.reasonCodes.includes('explicit-strategy-request'), `${name}: unquoted directive is explicit`);
236
+ assert.ok(!quotedAndUnquoted.routerOutput.includes('REQUESTED FABLE PROFILE'), `${name}: quoted profile stays data`);
237
+
238
+ for (const verb of ['use', 'run', 'enter', 'switch to']) {
239
+ const affirmative = route(`${verb} fable for this task`, router);
240
+ assert.equal(affirmative.strategy, 'fable-staged', `${name}: ${verb} is an affirmative directive`);
241
+ assert.ok(affirmative.reasonCodes.includes('explicit-strategy-request'), `${name}: ${verb} is recorded as explicit`);
242
+ const prohibited = route(`Do not ${verb} fable; redesign the repository architecture`, router);
243
+ assert.equal(prohibited.strategy, 'iterative-single', `${name}: do not ${verb} fable downgrades the topology`);
244
+ assert.ok(prohibited.reasonCodes.includes('user-prohibited-fable'), `${name}: do not ${verb} fable is a prohibition`);
245
+ }
246
+
247
+ for (const verb of ['使用', '用', '啟用', '進入', '執行', '改用']) {
248
+ const affirmative = route(`${verb} fable 做這個任務`, router);
249
+ assert.equal(affirmative.strategy, 'fable-staged', `${name}: ${verb} is an affirmative directive`);
250
+ assert.ok(affirmative.reasonCodes.includes('explicit-strategy-request'), `${name}: ${verb} is recorded as explicit`);
251
+ const prohibited = route(`不要${verb} fable 重構整個 repository architecture`, router);
252
+ assert.equal(prohibited.strategy, 'iterative-single', `${name}: 不要${verb} fable downgrades the topology`);
253
+ assert.ok(prohibited.reasonCodes.includes('user-prohibited-fable'), `${name}: 不要${verb} fable is a prohibition`);
254
+ }
255
+
256
+ for (const { prompt, tier, strategy } of polarityCases) {
257
+ const plan = route(prompt, router);
258
+ assert.equal(plan.tier, tier, `${name}: ${prompt}: structural tier remains`);
259
+ assert.equal(plan.strategy, strategy, `${name}: ${prompt}: prohibition selects a single-agent topology`);
260
+ assert.ok(plan.reasonCodes.includes('user-prohibited-fable'), `${name}: ${prompt}: prohibition is recorded`);
261
+ }
262
+
263
+ for (const prompt of contradictionCases) {
264
+ const plan = route(prompt, router);
265
+ assert.equal(plan.fallback.disposition, 'blocked', `${name}: ${prompt}: contradiction is blocked`);
266
+ assert.ok(plan.reasonCodes.includes('explicit-request-conflicts-with-prohibition'), `${name}: ${prompt}: conflict is recorded`);
267
+ }
268
+
269
+ const existingChineseControl = route('不要使用 fable 重構整個 repository architecture', router);
270
+ assert.equal(existingChineseControl.strategy, 'iterative-single', `${name}: existing prohibition control downgrades`);
271
+ assert.ok(existingChineseControl.reasonCodes.includes('user-prohibited-fable'));
272
+ const quotedControl = route('Use “fable; use fable on opus” as an example', router);
273
+ assert.ok(!String(quotedControl.strategy).startsWith('fable-'), `${name}: paired curly-quote control stays non-Fable`);
274
+ }
275
+
180
276
  console.log('PASS: #332 Fable directive real-entry controls');
@@ -43,6 +43,7 @@ const reports = path.join(fixtureRoot, 'reports with spaces');
43
43
  const runnerBin = path.join(fixtureRoot, 'runner bin');
44
44
  const openCodeOnlyBin = path.join(fixtureRoot, 'opencode only bin');
45
45
  const rawOverridePreload = path.join(fixtureRoot, 'raw-override.cjs');
46
+ const usagePreload = path.join(fixtureRoot, 'usage-preload.cjs');
46
47
  const admissionPreload = path.join(fixtureRoot, 'admission-preload.cjs');
47
48
  const agyStubScript = path.join(fixtureRoot, 'agy-stub.cjs');
48
49
  const agyWinPreload = path.join(fixtureRoot, 'agy-win-preload.cjs');
@@ -251,6 +252,7 @@ function cliEnv(testCase, config = {}) {
251
252
  DISPATCH_FIXTURE_EXECUTION: config.execution || 'done',
252
253
  };
253
254
  const preloads = [];
255
+ preloads.push(`--require "${usagePreload.replace(/\\/g, '/')}"`);
254
256
  if (process.platform === 'win32') preloads.push(`--require "${agyWinPreload.replace(/\\/g, '/')}"`);
255
257
  if (config.rawOverride !== undefined) {
256
258
  env.DISPATCH_FIXTURE_RAW_OVERRIDE = config.rawOverride;
@@ -404,6 +406,7 @@ function runSuccessAndArgvMatch(runner, requestedModel = runner === 'codex' ? 'f
404
406
  const result = jsonResponse(cli([...args, '--json'], testCase, config), 0, 'DONE');
405
407
  assert.equal(result.runner, runner);
406
408
  assert.equal(result.model, model);
409
+ assert.ok(result.usage && Number.isSafeInteger(result.usage.totalTokens), 'successful structured runner telemetry is reported');
407
410
  assert.equal(fs.existsSync(testCase.scratch), true);
408
411
  assert.equal(fs.readFileSync(result.evidence.report, 'utf8'), 'Fixture completed the packet.\nSTATUS: DONE\n');
409
412
  const actualEvents = events(testCase);
@@ -458,6 +461,42 @@ if (
458
461
  };
459
462
  }
460
463
  `);
464
+ fs.writeFileSync(usagePreload, `'use strict';
465
+ const path = require('node:path');
466
+ const originalWrite = process.stdout.write.bind(process.stdout);
467
+ const script = path.basename(process.argv[1] || '');
468
+ const runner = script === 'exec' ? 'codex' : script === 'run' ? 'opencode' : script === path.basename(${JSON.stringify(agyStubScript)}) ? 'agy' : null;
469
+ const args = process.argv.slice(2);
470
+ const phase = args.includes('Reply with the single word READY') ? 'readiness' : 'execution';
471
+ if (runner && phase === 'execution') {
472
+ const structured = runner === 'codex' ? args.includes('--json') : runner === 'opencode' ? args.includes('--format') : args.includes('--output-format');
473
+ const option = runner === 'codex' ? null : args[args.indexOf(runner === 'opencode' ? '--format' : '--output-format') + 1];
474
+ if (structured && (runner === 'codex' || option === (runner === 'opencode' ? 'json' : 'json'))) {
475
+ const supplied = process.env.DISPATCH_FIXTURE_USAGE;
476
+ let source = null;
477
+ try { source = supplied ? JSON.parse(supplied) : null; } catch {}
478
+ process.stdout.write = function (chunk, ...rest) {
479
+ if (!String(chunk).includes('fixture child output')) return originalWrite(chunk, ...rest);
480
+ if (supplied === 'missing') return originalWrite('', ...rest);
481
+ if (typeof supplied === 'string' && supplied.startsWith('prose ')) return originalWrite(supplied.slice(6) + '\\n', ...rest);
482
+ if (runner === 'codex') {
483
+ const usage = source || { input_tokens: 10, cached_input_tokens: 8, output_tokens: 4 };
484
+ return originalWrite(JSON.stringify({ type: 'turn.completed', usage }) + '\\n', ...rest);
485
+ }
486
+ if (runner === 'opencode') {
487
+ const totals = source?.totals || [21, 14];
488
+ const lines = totals.map((total, index) => {
489
+ const cacheWrite = source?.cacheWrite || 0;
490
+ return JSON.stringify({ type: 'step_finish', part: { id: 'fixture-step-' + index, reason: index === totals.length - 1 ? 'stop' : 'tool-calls', type: 'step-finish', tokens: { total, input: 1, output: 1, reasoning: 0, cache: { read: Math.max(0, total - 2 - cacheWrite), write: cacheWrite } } } });
491
+ });
492
+ return originalWrite(lines.join('\\n') + '\\n', ...rest);
493
+ }
494
+ const usage = source || { input_tokens: 10, output_tokens: 2, thinking_tokens: 1, cache_read_tokens: 8, total_tokens: 12 };
495
+ return originalWrite(JSON.stringify({ status: 'SUCCESS', response: '', usage }) + '\\n', ...rest);
496
+ };
497
+ }
498
+ }
499
+ `);
461
500
  fs.writeFileSync(admissionPreload, `'use strict';
462
501
  const fs = require('node:fs');
463
502
  const path = require('node:path');
@@ -502,6 +541,58 @@ fs.mkdirSync(path.join(fixtureRoot, `${path.basename(worktree)}-sibling`));
502
541
  fs.symlinkSync(repositoryParent, symlinkedParent, process.platform === 'win32' ? 'junction' : 'dir');
503
542
 
504
543
  try {
544
+ check('468 token usage counts cached input once and marks only totals strictly above 30M', () => {
545
+ const runUsage = (telemetry, label) => {
546
+ const testCase = makeCase(`usage ${label}`);
547
+ const usageText = typeof telemetry === 'string' ? telemetry : JSON.stringify(telemetry);
548
+ const result = jsonResponse(cli([...argsFor(testCase, 'codex'), '--json'], testCase, { extraEnv: { DISPATCH_FIXTURE_USAGE: usageText } }), 0, 'DONE');
549
+ return { testCase, result };
550
+ };
551
+ assert.deepEqual(runUsage({ input_tokens: 29_999_999, cached_input_tokens: 12_000_000, output_tokens: 0 }, 'below').result.usage, { totalTokens: 29_999_999 });
552
+ assert.deepEqual(runUsage({ input_tokens: 30_000_000, cached_input_tokens: 15_000_000, output_tokens: 0 }, 'exact').result.usage, { totalTokens: 30_000_000 });
553
+ const above = runUsage({ input_tokens: 30_000_000, cached_input_tokens: 10_000_000, output_tokens: 1 }, 'above');
554
+ assert.deepEqual(above.result.usage, { totalTokens: 30_000_001, mark: 'OVER-BUDGET' });
555
+ assert.equal(runUsage('prose tokens used: 30000001', 'unknown').result.usage, null);
556
+ assert.equal(runUsage('missing', 'missing').result.usage, null);
557
+ assert.equal(runUsage({ input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 }, 'codex default fallback').result.usage, null);
558
+ assert.equal(events(above.testCase).length, 2, 'the advisory must not change lifecycle calls');
559
+ });
560
+
561
+ check('468 structured usage controls: Codex, OpenCode, malformed and prose telemetry', () => {
562
+ const codex = makeCase('Codex cache-inclusive usage');
563
+ assert.deepEqual(jsonResponse(cli([...argsFor(codex, 'codex'), '--json'], codex, { extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify({ input_tokens: 10, cached_input_tokens: 8, output_tokens: 4 }) } }), 0, 'DONE').usage, { totalTokens: 14 });
564
+ const opencode = makeCase('OpenCode cache-inclusive usage');
565
+ assert.deepEqual(jsonResponse(cli([...argsFor(opencode, 'opencode'), '--json'], opencode, { extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify({ totals: [21, 14] }) } }), 0, 'DONE').usage, { totalTokens: 35 });
566
+ const opencodeCacheWrite = makeCase('OpenCode cache-write usage unknown');
567
+ assert.equal(jsonResponse(cli([...argsFor(opencodeCacheWrite, 'opencode'), '--json'], opencodeCacheWrite, { extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify({ totals: [21], cacheWrite: 3 }) } }), 0, 'DONE').usage, null);
568
+ const malformed = makeCase('malformed usage');
569
+ assert.equal(jsonResponse(cli([...argsFor(malformed, 'codex'), '--json'], malformed, { extraEnv: { DISPATCH_FIXTURE_USAGE: '{"input_tokens":"30M"}' } }), 0, 'DONE').usage, null);
570
+ const prose = makeCase('prose usage');
571
+ assert.equal(jsonResponse(cli([...argsFor(prose, 'opencode'), '--json'], prose, { extraEnv: { DISPATCH_FIXTURE_USAGE: 'prose tokens used: 30000001' } }), 0, 'DONE').usage, null);
572
+ });
573
+
574
+ check('468 human DONE prints the cache-inclusive total without changing exit or report status', () => {
575
+ const testCase = makeCase('human token usage');
576
+ const result = cli(argsFor(testCase, 'codex'), testCase, { extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify({ input_tokens: 10, cached_input_tokens: 8, output_tokens: 4 }) } });
577
+ assert.equal(result.status, 0, result.stderr);
578
+ assert.match(result.stdout, /total tokens incl\. cache: 14/);
579
+ assert.ok(fs.readFileSync(testCase.report, 'utf8').endsWith('STATUS: DONE\n'));
580
+ });
581
+ check('468 completed telemetry is retained when a valid BLOCKED report is delivered', () => {
582
+ const telemetry = { input_tokens: 30_000_000, cached_input_tokens: 12_000_000, output_tokens: 1 };
583
+ const doneCase = makeCase('done report with same usage');
584
+ const done = jsonResponse(cli([...argsFor(doneCase, 'codex'), '--json'], doneCase, {
585
+ extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify(telemetry) },
586
+ }), 0, 'DONE');
587
+ const testCase = makeCase('blocked report with usage');
588
+ const response = jsonResponse(cli([...argsFor(testCase, 'codex'), '--json'], testCase, {
589
+ execution: 'blocked',
590
+ extraEnv: { DISPATCH_FIXTURE_USAGE: JSON.stringify(telemetry) },
591
+ }), 17, 'WORKER_BLOCKED');
592
+ assert.deepEqual(done.usage, { totalTokens: 30_000_001, mark: 'OVER-BUDGET' });
593
+ assert.deepEqual(response.usage, done.usage);
594
+ assert.match(response.message, /valid BLOCKED report/);
595
+ });
505
596
  check('HELP human and JSON', () => {
506
597
  const testCase = makeCase('help');
507
598
  const human = cli(['--help'], testCase);
@@ -758,6 +849,7 @@ try {
758
849
  check(`${runner} execution failure -> RUN_FAILED with no retry/fallback`, () => {
759
850
  const testCase = makeCase(`${runner} run failed`);
760
851
  const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, { execution: 'exit-failure' }), 15, 'RUN_FAILED');
852
+ assert.equal(response.usage, null, 'failed telemetry is unknown');
761
853
  const actualEvents = events(testCase);
762
854
  assert.equal(actualEvents.length, 2);
763
855
  assert.ok(actualEvents.every(event => event.runner === runner));
@@ -767,9 +859,10 @@ try {
767
859
 
768
860
  check(`${runner} execution timeout -> RUN_TIMEOUT and child exited`, () => {
769
861
  const testCase = makeCase(`${runner} run timeout`);
770
- jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, {
862
+ const response = jsonResponse(cli([...argsFor(testCase, runner), '--json'], testCase, {
771
863
  execution: 'timeout', testTimeoutMs: 300, outerTimeoutMs: 5000,
772
864
  }), 15, 'RUN_TIMEOUT');
865
+ assert.equal(response.usage, null, 'interrupted telemetry is unknown');
773
866
  const actualEvents = events(testCase);
774
867
  assert.equal(actualEvents.length, 2);
775
868
  assert.ok(actualEvents.every(event => event.runner === runner));
@@ -1395,7 +1488,7 @@ try {
1395
1488
  '--report', testCase.reportRel,
1396
1489
  ];
1397
1490
  }
1398
- function assertAgyArgv(argv, model, prompt, timeoutSeconds) {
1491
+ function assertAgyArgv(argv, model, prompt, timeoutSeconds, structured = false) {
1399
1492
  assert.deepEqual(argv, [
1400
1493
  '-p', prompt,
1401
1494
  '--model', model,
@@ -1403,6 +1496,7 @@ try {
1403
1496
  '--sandbox',
1404
1497
  '--settings', agySettings,
1405
1498
  '--print-timeout', `${timeoutSeconds}s`,
1499
+ ...(structured ? ['--output-format', 'json'] : []),
1406
1500
  ]);
1407
1501
  }
1408
1502
  function assertAgyEvent(event, testCase, phase, model = 'gemini-4-neon-medium') {
@@ -1414,7 +1508,7 @@ try {
1414
1508
  const expectedPrompt = phase === 'readiness'
1415
1509
  ? 'Reply with the single word READY'
1416
1510
  : `Execute the packet at ${testCase.packetRel} and write the complete report to ${testCase.reportRel}. Use only paths relative to the current directory.`;
1417
- assertAgyArgv(event.args, model, expectedPrompt, phase === 'readiness' ? 120 : 2700);
1511
+ assertAgyArgv(event.args, model, expectedPrompt, phase === 'readiness' ? 120 : 2700, phase === 'execution');
1418
1512
  if (phase === 'execution') {
1419
1513
  assert.equal(expectedPrompt.includes(worktree), false, 'agy prompt must use cwd-relative paths');
1420
1514
  }
@@ -1430,7 +1524,7 @@ try {
1430
1524
  assertSameCanonicalPath(dryRun.cwd, worktree);
1431
1525
  assert.equal(dryRun.argv[0], 'agy');
1432
1526
  const expectedPrompt = `Execute the packet at ${testCase.packetRel} and write the complete report to ${testCase.reportRel}. Use only paths relative to the current directory.`;
1433
- assertAgyArgv(dryRun.argv.slice(1), 'gemini-4-neon-medium', expectedPrompt, 2700);
1527
+ assertAgyArgv(dryRun.argv.slice(1), 'gemini-4-neon-medium', expectedPrompt, 2700, true);
1434
1528
  assertNoRunner(testCase);
1435
1529
  assertNoScratchOrReport(testCase);
1436
1530
 
@@ -1439,6 +1533,7 @@ try {
1439
1533
  assert.equal(response.runner, 'agy');
1440
1534
  assert.equal(response.model, 'gemini-4-neon-medium');
1441
1535
  assert.equal(response.sandbox, 'requested');
1536
+ assert.deepEqual(response.usage, { totalTokens: 12 });
1442
1537
  assert.equal(fs.readFileSync(response.evidence.report, 'utf8'), 'Fixture completed the packet.\nSTATUS: DONE\n');
1443
1538
  const actualEvents = events(testCase);
1444
1539
  assert.equal(actualEvents.length, 2, 'one readiness and one execution');
@@ -205,6 +205,18 @@ test('441-A accepts trailing ASCII spaces or tabs on raw Codex STATUS and writes
205
205
  assert.deepEqual(fs.readFileSync(output), Buffer.from('Summary\nSTATUS: DONE\n'));
206
206
  assertOk(run(['check', '--file', output]));
207
207
 
208
+ // Raw Codex input remains normalized for both outcomes and padding forms.
209
+ for (const [rawStatus, status, reason, expected] of [
210
+ ['STATUS: DONE ', 'DONE', null, 'STATUS: DONE'],
211
+ ['STATUS: BLOCKED: verification unavailable\t', 'BLOCKED', 'verification unavailable', 'STATUS: BLOCKED: verification unavailable'],
212
+ ]) {
213
+ fs.writeFileSync(raw, `Summary\n${rawStatus}\n`);
214
+ const args = writeArgs(output, status, ['--from-codex-output', raw], ...(reason ? ['--reason', reason] : []));
215
+ assertOk(run(args));
216
+ assert.deepEqual(fs.readFileSync(output), Buffer.from(`Summary\n${expected}\n`));
217
+ assertOk(run(['check', '--file', output]));
218
+ }
219
+
208
220
  // Padded STATUS: BLOCKED followed by a blank line and an EOF host label.
209
221
  const labeledRaw = Buffer.from(`Summary\nSTATUS: BLOCKED: verification unavailable \t\n\n${VALID_LABEL}\n`);
210
222
  fs.writeFileSync(raw, labeledRaw);
@@ -371,6 +383,11 @@ test('check accepts one terminal status with LF or CRLF and rejects other contro
371
383
  for (const invalid of [
372
384
  'Summary',
373
385
  'Summary\nSTATUS: DONE ',
386
+ 'Summary\nSTATUS: DONE\t',
387
+ 'Summary\nSTATUS: BLOCKED: reason ',
388
+ 'Summary\nSTATUS: BLOCKED: reason\t',
389
+ 'Summary\nSTATUS: BLOCKED: reason',
390
+ 'Summary\nSTATUS: BLOCKED: reason ',
374
391
  'Summary\n STATUS: DONE',
375
392
  'Summary\nSTATUS: DONE\n\n',
376
393
  'Summary\nSTATUS: DONE\ntrailing',
@@ -30,6 +30,18 @@ npm run --silent dispatch -- --runner <codex|opencode|agy> --model <id> \
30
30
 
31
31
  In JSON mode the common shape is `{ok, code, phase, message}` with resolved `runner`, `model`, and existing `evidence` paths when available. A validated requested Codex `--effort` is also returned as `effort`; it records the request and does not claim the provider applied it. For `agy`, JSON also returns `sandbox: "requested"`; it records the requested `--sandbox` flag only and does not claim proven isolation (scope any isolation claim to separately executed evidence). Dry run also returns `argv` and `cwd`; Codex's generated raw-output argument uses a `<run-id>` placeholder. Human-mode refusals go to stderr. Child logs and raw output stay in evidence files, not in the JSON result.
32
32
 
33
+ ## Usage field
34
+
35
+ A completed runner process is measured before report validation, so a valid BLOCKED delivery (and a later report-validation refusal) can include `usage: { "totalTokens": <integer>, "mark"?: "OVER-BUDGET" }` when its structured telemetry is supported. Missing, malformed, incomplete, or uncertain telemetry returns `usage: null`. The same total is printed in the human DONE message. `OVER-BUDGET` is advisory and appears only when the cache-inclusive total is **strictly greater than 30,000,000**. It does not change the exit code, report status, timeout, or cleanup path. Runner failures and interruptions return `usage: null`.
36
+
37
+ | Runner | Structured execution channel and accepted usage shape | Cache accounting | Evidence boundary |
38
+ | --- | --- | --- | --- |
39
+ | Codex | `codex exec ... --json`; exactly one JSONL `turn.completed` event with integer `usage.input_tokens`, `usage.cached_input_tokens`, and `usage.output_tokens`. Total = `input_tokens + output_tokens`. All-zero usage is unknown because Codex can emit `Usage::default()` when no token update was received. | Codex `input_tokens` already includes cached input; `cached_input_tokens` is validated as a subset and is not added again. | **Fixture:** `468-dispatch` mechanism test. [Codex CLI v0.172.0 source](https://github.com/openai/codex/blob/rust-v0.172.0/codex-rs/exec/src/event_processor_with_jsonl_output.rs#L120-L130) emits a terminal turn event with usage and uses the all-zero default when no token update was received; no retained C8 live run has this telemetry capture. |
40
+ | OpenCode | `opencode run ... --format json`; JSONL `step_finish` events with unique `part.id`, `part.type: "step-finish"`, `part.tokens.{total,input,output,reasoning,cache:{read,write}}`; final step reason must be `stop`. Total = sum of each `tokens.total`. | Each step's native `tokens.total` is checked against input, output, reasoning and cache-read counts. Any nonzero cache-write count is reported as unknown because retained complete-run evidence does not establish whether `tokens.total` includes writes. | **Fixture:** `468-dispatch` mechanism test. **Real-host:** two retained OpenCode 2.1.4 JSONL traces end with `tool-calls`, so they provide no complete live measurement; the C8 stdout channel is not live-traced. [OpenCode documents JSONL run output](https://opencode.ai/docs/cli/commands/). |
41
+ | `agy` | `agy -p ... --output-format json`; one JSON object with `status: "SUCCESS"` and integer `usage.{input_tokens,output_tokens,thinking_tokens,cache_read_tokens,total_tokens}`. Require `total_tokens = input_tokens + output_tokens`. | `input_tokens` includes cache reads; `thinking_tokens` is within output and `cache_read_tokens` is within input. Neither subset is added again. | **Fixture:** `468-dispatch` mechanism test. [Google documents this JSON envelope and fields](https://antigravity.google/docs/cli/headless/); previous retained C8 AGY runs used text mode and have no usage trace. |
42
+
43
+ Only the runner's structured stdout is parsed. Human `tokens used` prose, malformed JSON, invalid counts, duplicate/missing terminal events, non-final OpenCode stop events, and incomplete runs produce `usage: null`; no arbitrary log or task/runner-authored text is treated as usage.
44
+
33
45
  ## Exit and JSON codes
34
46
 
35
47
  | Exit | JSON `code` | Meaning |
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 1.5.1
7
+ version: 1.5.2
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -146,20 +146,33 @@ const FABLE_STRATEGIES = [
146
146
  ['fable-parallel', /\bfable[- ]parallel\b|\bparallel fable\b/i],
147
147
  ['fable-staged', /\bfable[- ]staged\b|\bstaged fable\b/i],
148
148
  ];
149
- const FABLE_PROHIBITION = /\b(?:no|without|do\s+not|don't|never|cannot|can't|not)\s+(?:use\s+)?fable(?:[- ]mode)?\b|(?:不要|不需要|無需|無須|不必|毋須|不用|別|勿|請勿|避免|停止|不)\s*(?:使用|用|啟用|進入|執行)?\s*fable(?:[- ]mode)?/i;
149
+ const FABLE_DIRECTIVE_VERBS = {
150
+ english: '(?:use|run|enter|switch\\s+to)',
151
+ chinese: '(?:使用|用|啟用|進入|執行|改用)',
152
+ };
153
+ const FABLE_PROHIBITION = new RegExp(
154
+ `\\b(?:no|without|do\\s+not|don't|never|cannot|can't|not)\\s+(?:(?:${FABLE_DIRECTIVE_VERBS.english})\\s+)?fable(?:[- ]mode)?\\b|(?:不要|不需要|無需|無須|不必|毋須|不用|別|勿|請勿|避免|停止|不)\\s*(?:(?:${FABLE_DIRECTIVE_VERBS.chinese})\\s*)?fable(?:[- ]mode)?`,
155
+ 'i',
156
+ );
150
157
  const FABLE_REQUEST_PREFIX = /^(?:(?:please|let's|now|could\s+you(?:\s+please)?|would\s+you(?:\s+please)?)\s+|(?:請|幫我|麻煩)\s*)*/i;
151
- const FABLE_REQUEST_VERB = /^(?:use|run|enter)\s+fable(?:[- ]mode)?\b|^(?:使用|用|啟用|進入|執行|改用)\s*fable(?:[- ]mode)?/i;
152
- const FABLE_NAMED_REQUEST = /^(?:use|run|enter|改用)\s+(fable[- ](?:multi[- ]agent[- ]workspace|parallel|staged))\b/i;
153
- const FABLE_PROFILE_REQUEST = /^(?:use|run|enter|改用)\s+fable(?:[- ]mode)?\s+(?:on|with)\s+(haiku|sonnet|sonnect|opus)\b/i;
158
+ const FABLE_REQUEST_VERB = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english})\\s+fable(?:[- ]mode)?\\b|^(?:${FABLE_DIRECTIVE_VERBS.chinese})\\s*fable(?:[- ]mode)?`, 'i');
159
+ const FABLE_NAMED_REQUEST = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english}|改用)\\s+(fable[- ](?:multi[- ]agent[- ]workspace|parallel|staged))\\b`, 'i');
160
+ const FABLE_PROFILE_REQUEST = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english}|改用)\\s+fable(?:[- ]mode)?\\s+(?:on|with)\\s+(haiku|sonnet|sonnect|opus)\\b`, 'i');
161
+ const FABLE_QUOTE_PAIRS = new Map([
162
+ ['"', '"'], ['`', '`'], ["'", "'"], ['“', '”'], ['‘', '’'],
163
+ ['「', '」'], ['『', '』'], ['《', '》'],
164
+ ]);
154
165
 
155
166
  function splitFableDirectiveClauses(prompt) {
156
167
  const text = String(prompt || '');
157
168
  const parts = [];
158
169
  let part = '';
170
+ let unquotedPart = '';
159
171
  let quote = null;
160
172
  const push = () => {
161
- if (part.trim()) parts.push(part.trim());
173
+ if (part.trim()) parts.push({ text: part.trim(), unquotedText: unquotedPart.trim() });
162
174
  part = '';
175
+ unquotedPart = '';
163
176
  };
164
177
  const wordSeparators = /^(?:and\s+then|and|then|also|plus|afterwards|additionally|but|並且|並|以及|接著|然後|另外)/iu;
165
178
 
@@ -170,10 +183,11 @@ function splitFableDirectiveClauses(prompt) {
170
183
  part += char;
171
184
  continue;
172
185
  }
173
- if (char === '"' || char === '`' || char === '“' || char === '‘' ||
174
- (char === "'" && !/[\p{L}\p{N}]/u.test(text[i - 1] || '') && /[\p{L}\p{N}]/u.test(text[i + 1] || ''))) {
175
- quote = char === '“' ? '”' : char === '‘' ? '’' : char;
186
+ if (FABLE_QUOTE_PAIRS.has(char) &&
187
+ (char !== "'" || (!/[\p{L}\p{N}]/u.test(text[i - 1] || '') && /[\p{L}\p{N}]/u.test(text[i + 1] || '')))) {
188
+ quote = FABLE_QUOTE_PAIRS.get(char);
176
189
  part += char;
190
+ unquotedPart += '\u0000';
177
191
  continue;
178
192
  }
179
193
  if (/[;!??!,,;。、…]/u.test(char) || (char === '.' && (i + 1 === text.length || /\s/u.test(text[i + 1])))) {
@@ -188,6 +202,7 @@ function splitFableDirectiveClauses(prompt) {
188
202
  continue;
189
203
  }
190
204
  part += char;
205
+ unquotedPart += char;
191
206
  }
192
207
  push();
193
208
  return parts;
@@ -215,8 +230,8 @@ function detectFableDirective(prompt) {
215
230
  let strategy = null;
216
231
  let profile = null;
217
232
  let prohibited = false;
218
- for (const clause of clauses) {
219
- const negated = FABLE_PROHIBITION.test(clause);
233
+ for (const { text: clause, unquotedText } of clauses) {
234
+ const negated = FABLE_PROHIBITION.test(unquotedText);
220
235
  if (negated) prohibited = true;
221
236
  if (negated || strategy) continue;
222
237
  const request = detectFableRequest(clause);
@@ -226,8 +241,8 @@ function detectFableDirective(prompt) {
226
241
  }
227
242
  }
228
243
  if (!strategy) {
229
- const linkedContinuations = clauses.slice(0, -1).flatMap((clause, index) => {
230
- if (!isFableProfileLookup(clause, false) || !/^run\s+it\b/i.test(clauses[index + 1])) return [];
244
+ const linkedContinuations = clauses.slice(0, -1).flatMap(({ text: clause }, index) => {
245
+ if (!isFableProfileLookup(clause, false) || !/^run\s+it\b/i.test(clauses[index + 1].text)) return [];
231
246
  const matches = clause.match(new RegExp(FABLE_PROFILE_INVOCATION.source, 'gi')) || [];
232
247
  return matches.length === 1 ? [detectFableModel(clause)] : [];
233
248
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "1.5.1",
4
+ "version": "1.5.3",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "harness-everything",
4
- "version": "1.5.1",
4
+ "version": "1.5.3",
5
5
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
6
6
  "author": {
7
7
  "name": "Miya Daniel",
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 1.5.1
7
+ version: 1.5.2
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -146,20 +146,33 @@ const FABLE_STRATEGIES = [
146
146
  ['fable-parallel', /\bfable[- ]parallel\b|\bparallel fable\b/i],
147
147
  ['fable-staged', /\bfable[- ]staged\b|\bstaged fable\b/i],
148
148
  ];
149
- const FABLE_PROHIBITION = /\b(?:no|without|do\s+not|don't|never|cannot|can't|not)\s+(?:use\s+)?fable(?:[- ]mode)?\b|(?:不要|不需要|無需|無須|不必|毋須|不用|別|勿|請勿|避免|停止|不)\s*(?:使用|用|啟用|進入|執行)?\s*fable(?:[- ]mode)?/i;
149
+ const FABLE_DIRECTIVE_VERBS = {
150
+ english: '(?:use|run|enter|switch\\s+to)',
151
+ chinese: '(?:使用|用|啟用|進入|執行|改用)',
152
+ };
153
+ const FABLE_PROHIBITION = new RegExp(
154
+ `\\b(?:no|without|do\\s+not|don't|never|cannot|can't|not)\\s+(?:(?:${FABLE_DIRECTIVE_VERBS.english})\\s+)?fable(?:[- ]mode)?\\b|(?:不要|不需要|無需|無須|不必|毋須|不用|別|勿|請勿|避免|停止|不)\\s*(?:(?:${FABLE_DIRECTIVE_VERBS.chinese})\\s*)?fable(?:[- ]mode)?`,
155
+ 'i',
156
+ );
150
157
  const FABLE_REQUEST_PREFIX = /^(?:(?:please|let's|now|could\s+you(?:\s+please)?|would\s+you(?:\s+please)?)\s+|(?:請|幫我|麻煩)\s*)*/i;
151
- const FABLE_REQUEST_VERB = /^(?:use|run|enter)\s+fable(?:[- ]mode)?\b|^(?:使用|用|啟用|進入|執行|改用)\s*fable(?:[- ]mode)?/i;
152
- const FABLE_NAMED_REQUEST = /^(?:use|run|enter|改用)\s+(fable[- ](?:multi[- ]agent[- ]workspace|parallel|staged))\b/i;
153
- const FABLE_PROFILE_REQUEST = /^(?:use|run|enter|改用)\s+fable(?:[- ]mode)?\s+(?:on|with)\s+(haiku|sonnet|sonnect|opus)\b/i;
158
+ const FABLE_REQUEST_VERB = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english})\\s+fable(?:[- ]mode)?\\b|^(?:${FABLE_DIRECTIVE_VERBS.chinese})\\s*fable(?:[- ]mode)?`, 'i');
159
+ const FABLE_NAMED_REQUEST = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english}|改用)\\s+(fable[- ](?:multi[- ]agent[- ]workspace|parallel|staged))\\b`, 'i');
160
+ const FABLE_PROFILE_REQUEST = new RegExp(`^(?:${FABLE_DIRECTIVE_VERBS.english}|改用)\\s+fable(?:[- ]mode)?\\s+(?:on|with)\\s+(haiku|sonnet|sonnect|opus)\\b`, 'i');
161
+ const FABLE_QUOTE_PAIRS = new Map([
162
+ ['"', '"'], ['`', '`'], ["'", "'"], ['“', '”'], ['‘', '’'],
163
+ ['「', '」'], ['『', '』'], ['《', '》'],
164
+ ]);
154
165
 
155
166
  function splitFableDirectiveClauses(prompt) {
156
167
  const text = String(prompt || '');
157
168
  const parts = [];
158
169
  let part = '';
170
+ let unquotedPart = '';
159
171
  let quote = null;
160
172
  const push = () => {
161
- if (part.trim()) parts.push(part.trim());
173
+ if (part.trim()) parts.push({ text: part.trim(), unquotedText: unquotedPart.trim() });
162
174
  part = '';
175
+ unquotedPart = '';
163
176
  };
164
177
  const wordSeparators = /^(?:and\s+then|and|then|also|plus|afterwards|additionally|but|並且|並|以及|接著|然後|另外)/iu;
165
178
 
@@ -170,10 +183,11 @@ function splitFableDirectiveClauses(prompt) {
170
183
  part += char;
171
184
  continue;
172
185
  }
173
- if (char === '"' || char === '`' || char === '“' || char === '‘' ||
174
- (char === "'" && !/[\p{L}\p{N}]/u.test(text[i - 1] || '') && /[\p{L}\p{N}]/u.test(text[i + 1] || ''))) {
175
- quote = char === '“' ? '”' : char === '‘' ? '’' : char;
186
+ if (FABLE_QUOTE_PAIRS.has(char) &&
187
+ (char !== "'" || (!/[\p{L}\p{N}]/u.test(text[i - 1] || '') && /[\p{L}\p{N}]/u.test(text[i + 1] || '')))) {
188
+ quote = FABLE_QUOTE_PAIRS.get(char);
176
189
  part += char;
190
+ unquotedPart += '\u0000';
177
191
  continue;
178
192
  }
179
193
  if (/[;!??!,,;。、…]/u.test(char) || (char === '.' && (i + 1 === text.length || /\s/u.test(text[i + 1])))) {
@@ -188,6 +202,7 @@ function splitFableDirectiveClauses(prompt) {
188
202
  continue;
189
203
  }
190
204
  part += char;
205
+ unquotedPart += char;
191
206
  }
192
207
  push();
193
208
  return parts;
@@ -215,8 +230,8 @@ function detectFableDirective(prompt) {
215
230
  let strategy = null;
216
231
  let profile = null;
217
232
  let prohibited = false;
218
- for (const clause of clauses) {
219
- const negated = FABLE_PROHIBITION.test(clause);
233
+ for (const { text: clause, unquotedText } of clauses) {
234
+ const negated = FABLE_PROHIBITION.test(unquotedText);
220
235
  if (negated) prohibited = true;
221
236
  if (negated || strategy) continue;
222
237
  const request = detectFableRequest(clause);
@@ -226,8 +241,8 @@ function detectFableDirective(prompt) {
226
241
  }
227
242
  }
228
243
  if (!strategy) {
229
- const linkedContinuations = clauses.slice(0, -1).flatMap((clause, index) => {
230
- if (!isFableProfileLookup(clause, false) || !/^run\s+it\b/i.test(clauses[index + 1])) return [];
244
+ const linkedContinuations = clauses.slice(0, -1).flatMap(({ text: clause }, index) => {
245
+ if (!isFableProfileLookup(clause, false) || !/^run\s+it\b/i.test(clauses[index + 1].text)) return [];
231
246
  const matches = clause.match(new RegExp(FABLE_PROFILE_INVOCATION.source, 'gi')) || [];
232
247
  return matches.length === 1 ? [detectFableModel(clause)] : [];
233
248
  });
package/sbom.cdx.json CHANGED
@@ -2,23 +2,23 @@
2
2
  "$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.7",
5
- "serialNumber": "urn:uuid:d4f2594d-0c88-513f-a804-4a6b25d213a4",
5
+ "serialNumber": "urn:uuid:4f5b2ec8-ab04-5321-9a7c-27ba416536e9",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-12-01T17:35:03.593Z",
8
+ "timestamp": "2026-12-01T19:49:28.170Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "1.5.1"
13
+ "version": "1.5.3"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@1.5.1",
18
+ "bom-ref": "pkg:npm/harness-everything@1.5.3",
19
19
  "name": "harness-everything",
20
- "version": "1.5.1",
21
- "purl": "pkg:npm/harness-everything@1.5.1"
20
+ "version": "1.5.3",
21
+ "purl": "pkg:npm/harness-everything@1.5.3"
22
22
  }
23
23
  },
24
24
  "components": [
@@ -2033,7 +2033,7 @@
2033
2033
  ]
2034
2034
  },
2035
2035
  {
2036
- "ref": "pkg:npm/harness-everything@1.5.1",
2036
+ "ref": "pkg:npm/harness-everything@1.5.3",
2037
2037
  "dependsOn": [
2038
2038
  "pkg:npm/%40commitlint/cli@19.8.1",
2039
2039
  "pkg:npm/%40commitlint/config-conventional@19.8.1",
@@ -402,7 +402,7 @@ function validateInput(options) {
402
402
  }
403
403
 
404
404
  function response(options, outcome, evidence = evidencePaths, input) {
405
- const message = String(outcome.message || '').slice(0, 1000);
405
+ let message = String(outcome.message || '');
406
406
  const result = {
407
407
  ok: outcome.exitCode === 0,
408
408
  code: outcome.code,
@@ -421,6 +421,16 @@ function response(options, outcome, evidence = evidencePaths, input) {
421
421
  ? { pool: input.admission.pool, cap: input.admission.cap, slot: input.admission.slot }
422
422
  : { pool: input.admission.pool, cap: input.admission.cap };
423
423
  }
424
+ if (Object.hasOwn(outcome, 'usage')) {
425
+ result.usage = outcome.usage ?? null;
426
+ if (outcome.code === 'DONE') {
427
+ message += outcome.usage
428
+ ? `; total tokens incl. cache: ${outcome.usage.totalTokens}${outcome.usage.mark ? ` (${outcome.usage.mark})` : ''}`
429
+ : '; total tokens incl. cache: unknown';
430
+ }
431
+ } else if (input && Object.hasOwn(input, 'measuredUsage')) result.usage = input.measuredUsage;
432
+ else if (outcome.phase === 'execution') result.usage = null;
433
+ result.message = message.slice(0, 1000);
424
434
  if (outcome.argv) result.argv = outcome.argv;
425
435
  if (outcome.cwd) result.cwd = outcome.cwd;
426
436
  const paths = Object.fromEntries(Object.entries(evidence).filter(([, value]) => value && fs.existsSync(value)));
@@ -515,14 +525,83 @@ function runChild(command, args, worktree, scratch, logPath, timeout, appendLog
515
525
  });
516
526
  }
517
527
 
518
- function runnerArgs(input, prompt, outputPath, timeoutMs = EXECUTION_TIMEOUT_MS) {
528
+ function runnerArgs(input, prompt, outputPath, timeoutMs = EXECUTION_TIMEOUT_MS, structured = false) {
519
529
  if (input.runner === 'codex') {
520
- return ['exec', '-m', input.model, ...(input.effort ? ['-c', `model_reasoning_effort="${input.effort}"`] : []), '-s', 'workspace-write', '-C', input.worktree, '-o', outputPath, prompt];
530
+ return ['exec', '-m', input.model, ...(input.effort ? ['-c', `model_reasoning_effort="${input.effort}"`] : []), '-s', 'workspace-write', '-C', input.worktree, '-o', outputPath, ...(structured ? ['--json'] : []), prompt];
521
531
  }
522
532
  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`];
533
+ return ['-p', prompt, '--model', input.model, '--mode', 'accept-edits', '--sandbox', '--settings', AGY_SETTINGS, '--print-timeout', `${Math.ceil(timeoutMs / 1000)}s`, ...(structured ? ['--output-format', 'json'] : [])];
524
534
  }
525
- return ['run', '--auto', '-m', input.model, prompt];
535
+ return ['run', '--auto', '-m', input.model, ...(structured ? ['--format', 'json'] : []), prompt];
536
+ }
537
+
538
+ function tokenCount(value) {
539
+ return Number.isSafeInteger(value) && value >= 0;
540
+ }
541
+
542
+ function parseJsonLines(output) {
543
+ if (typeof output !== 'string' || !output.trim()) return null;
544
+ try {
545
+ return output.trim().split(/\r?\n/).map(line => JSON.parse(line));
546
+ } catch {
547
+ return null;
548
+ }
549
+ }
550
+
551
+ function codexTokenUsage(output) {
552
+ const events = parseJsonLines(output);
553
+ if (!events) return null;
554
+ const completed = events.filter(event => event?.type === 'turn.completed');
555
+ if (completed.length !== 1) return null;
556
+ const usage = completed[0].usage;
557
+ if (!tokenCount(usage?.input_tokens) || !tokenCount(usage?.cached_input_tokens) || !tokenCount(usage?.output_tokens)
558
+ || usage.cached_input_tokens > usage.input_tokens) return null;
559
+ if (usage.input_tokens === 0 && usage.cached_input_tokens === 0 && usage.output_tokens === 0) return null;
560
+ const totalTokens = usage.input_tokens + usage.output_tokens;
561
+ return tokenCount(totalTokens) ? totalTokens : null;
562
+ }
563
+
564
+ function openCodeTokenUsage(output) {
565
+ const events = parseJsonLines(output);
566
+ if (!events || !events.length) return null;
567
+ const steps = events.filter(event => event?.type === 'step_finish');
568
+ if (!steps.length || events.at(-1)?.type !== 'step_finish' || steps.at(-1)?.part?.reason !== 'stop') return null;
569
+ const ids = new Set();
570
+ let totalTokens = 0;
571
+ for (const event of steps) {
572
+ const part = event.part;
573
+ const usage = part?.tokens;
574
+ const cache = usage?.cache;
575
+ if (part?.type !== 'step-finish' || typeof part.id !== 'string' || !part.id || ids.has(part.id)
576
+ || !tokenCount(usage?.total) || !tokenCount(usage?.input) || !tokenCount(usage?.output)
577
+ || !tokenCount(usage?.reasoning) || !tokenCount(cache?.read) || !tokenCount(cache?.write)
578
+ || cache.write !== 0) return null;
579
+ if (usage.total !== usage.input + usage.output + usage.reasoning + cache.read) return null;
580
+ ids.add(part.id);
581
+ totalTokens += usage.total;
582
+ if (!tokenCount(totalTokens)) return null;
583
+ }
584
+ return totalTokens;
585
+ }
586
+
587
+ function agyTokenUsage(output) {
588
+ if (typeof output !== 'string' || !output.trim()) return null;
589
+ let envelope;
590
+ try { envelope = JSON.parse(output); } catch { return null; }
591
+ const usage = envelope?.usage;
592
+ if (envelope?.status !== 'SUCCESS' || !tokenCount(usage?.input_tokens) || !tokenCount(usage?.output_tokens)
593
+ || !tokenCount(usage?.thinking_tokens) || !tokenCount(usage?.cache_read_tokens) || !tokenCount(usage?.total_tokens)
594
+ || usage.thinking_tokens > usage.output_tokens || usage.cache_read_tokens > usage.input_tokens
595
+ || usage.total_tokens !== usage.input_tokens + usage.output_tokens) return null;
596
+ return usage.total_tokens;
597
+ }
598
+
599
+ function measuredTokenUsage(runner, output) {
600
+ const totalTokens = runner === 'codex' ? codexTokenUsage(output)
601
+ : runner === 'opencode' ? openCodeTokenUsage(output)
602
+ : runner === 'agy' ? agyTokenUsage(output) : null;
603
+ if (totalTokens === null) return null;
604
+ return { totalTokens, ...(totalTokens > 30_000_000 ? { mark: 'OVER-BUDGET' } : {}) };
526
605
  }
527
606
 
528
607
  const READINESS_DIAGNOSTICS = {
@@ -666,6 +745,7 @@ function retainAndClean(input, attempt, paths) {
666
745
  }
667
746
 
668
747
  async function execute(input, options) {
748
+ const responseInput = input;
669
749
  const managed = input.gates !== undefined;
670
750
  let reservation = null;
671
751
  if (managed) {
@@ -699,7 +779,7 @@ async function execute(input, options) {
699
779
  if (existsOrSymlink(input.report)) fail(16, 'REPORT_INVALID', 'report', 'report path was populated before execution; refusing stale delivery');
700
780
  const prompt = executionPrompt(input);
701
781
  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);
782
+ const run = await runChild(input.runner, runnerArgs(input, prompt, outputPath, EXECUTION_TIMEOUT_MS, true), input.worktree, input.scratch, paths.runLog, EXECUTION_TIMEOUT_MS, false, reservation);
703
783
  if (run.status !== 0) {
704
784
  if (input.runner === 'agy' && !existsOrSymlink(input.report)) {
705
785
  const diagnostic = agyQuotaDiagnostic(run);
@@ -708,6 +788,8 @@ async function execute(input, options) {
708
788
  const timedOut = run.error?.code === 'ETIMEDOUT';
709
789
  fail(15, timedOut ? 'RUN_TIMEOUT' : 'RUN_FAILED', 'execution', timedOut ? 'runner execution timed out' : `runner execution failed${run.error ? `: ${run.error.message}` : ''}`);
710
790
  }
791
+ input.measuredUsage = measuredTokenUsage(input.runner, run.stdout);
792
+ responseInput.measuredUsage = input.measuredUsage;
711
793
 
712
794
  if (input.runner === 'codex') {
713
795
  if (!fs.existsSync(paths.rawOutput) || existsOrSymlink(input.report)) fail(16, 'REPORT_INVALID', 'report', 'fresh Codex output or report path is missing');
@@ -733,6 +815,7 @@ async function execute(input, options) {
733
815
  code: 'DONE',
734
816
  phase: 'report',
735
817
  message: `Dispatch completed and the report is valid: ${input.report}`,
818
+ usage: input.measuredUsage,
736
819
  }, evidencePaths, input);
737
820
  }
738
821
 
@@ -758,7 +841,7 @@ async function main() {
758
841
  code: 'DRY_RUN_OK',
759
842
  phase: 'dry-run',
760
843
  message: `Validated ${input.runner} model ${input.model} for packet ${input.packet} in ${input.worktree}; scratch ${input.scratch}; report ${input.report}`,
761
- argv: [input.runner, ...runnerArgs(input, executionPrompt(input), outputPath)],
844
+ argv: [input.runner, ...runnerArgs(input, executionPrompt(input), outputPath, EXECUTION_TIMEOUT_MS, true)],
762
845
  cwd: input.worktree,
763
846
  }, evidencePaths, input);
764
847
  return;
@@ -79,7 +79,7 @@ function splitLines(text) {
79
79
  function statusLineStatus(line) {
80
80
  if (line === 'STATUS: DONE') return 'STATUS: DONE';
81
81
  const blocked = /^STATUS: BLOCKED: (.+)$/.exec(line);
82
- if (blocked && blocked[1].trim() !== '') return line;
82
+ if (blocked && blocked[1] !== '' && blocked[1] === blocked[1].trim()) return line;
83
83
  error('expected STATUS: DONE or STATUS: BLOCKED: <reason>');
84
84
  }
85
85