harness-everything 1.5.0 → 1.5.2

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 (36) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +16 -0
  4. package/CHANGELOG.md +15 -0
  5. package/benchmarks/results/error-ledger-oracle-484-pilot/README.md +57 -0
  6. package/benchmarks/results/error-ledger-oracle-484-pilot/candidates.json +22802 -0
  7. package/benchmarks/results/error-ledger-oracle-484-pilot/labels.json +131 -0
  8. package/benchmarks/results/error-ledger-oracle-484-pilot/oracle.json +362 -0
  9. package/benchmarks/results/error-ledger-oracle-484-pilot/rows.json +648 -0
  10. package/benchmarks/results/error-ledger-oracle-484-pilot/sample.json +215 -0
  11. package/benchmarks/results/error-ledger-oracle-484-pilot/select.js +127 -0
  12. package/ci/mechanism-332-fable-directive.test.js +98 -2
  13. package/ci/mechanism-349-ci-change-scope.test.js +69 -1
  14. package/ci/mechanism-548-bigint-identity.test.js +1 -1
  15. package/ci/mechanism-571-fit-guard.test.js +165 -0
  16. package/ci/mechanism-571-nll-labels.test.js +79 -0
  17. package/ci/mechanism-report-writer.test.js +17 -0
  18. package/ci/mechanism-system-one-curves.test.js +11 -5
  19. package/ci/mechanism-system-one-cycle.test.js +73 -0
  20. package/harness-everything/SKILL.md +1 -1
  21. package/harness-everything/scripts/system-one/layer.py +11 -1
  22. package/harness-everything/scripts/tier-router.js +27 -12
  23. package/opencode-plugin/plugin.json +1 -1
  24. package/package.json +1 -1
  25. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  26. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  27. package/plugins/harness-everything/plugin.json +1 -1
  28. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  29. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +11 -1
  30. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +27 -12
  31. package/sbom.cdx.json +7 -7
  32. package/scripts/report-writer.js +1 -1
  33. package/scripts/system-one-curves.js +72 -15
  34. package/scripts/system-one-cycle/evaluate.js +25 -13
  35. package/scripts/system-one-cycle/train.js +67 -25
  36. package/scripts/system-one-fit-layer.py +11 -1
@@ -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:6661f5f0-5209-57ad-9fcc-0e658727ece7",
5
+ "serialNumber": "urn:uuid:6a6091b8-299b-5def-a625-1e771d1b564c",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-12-01T04:13:31.424Z",
8
+ "timestamp": "2026-12-01T19:03:45.350Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "1.5.0"
13
+ "version": "1.5.2"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@1.5.0",
18
+ "bom-ref": "pkg:npm/harness-everything@1.5.2",
19
19
  "name": "harness-everything",
20
- "version": "1.5.0",
21
- "purl": "pkg:npm/harness-everything@1.5.0"
20
+ "version": "1.5.2",
21
+ "purl": "pkg:npm/harness-everything@1.5.2"
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.0",
2036
+ "ref": "pkg:npm/harness-everything@1.5.2",
2037
2037
  "dependsOn": [
2038
2038
  "pkg:npm/%40commitlint/cli@19.8.1",
2039
2039
  "pkg:npm/%40commitlint/config-conventional@19.8.1",
@@ -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
 
@@ -314,13 +314,53 @@ function assertVersionReusable(history, curves) {
314
314
  return existing;
315
315
  }
316
316
 
317
- function validateSavedCurves(curves, version, manifest, digest, expectedScores) {
317
+ function validateSavedCurves(curves, version, versionDir, manifest, digest, expectedScores, requireCycleEvidence) {
318
318
  validateCurveRecord(curves);
319
319
  if (curves.version !== version || Object.keys(curves.stages).length !== Object.keys(manifest.stages).length
320
320
  || Object.keys(curves.stages).some(stage => !Object.hasOwn(manifest.stages, stage))) fail();
321
321
  const layered = hasLayeredStages(manifest);
322
- if (layered && curves.candidateDigest !== digest) fail();
323
- if (layered && (!expectedScores || !isDeepStrictEqual(curves.scoreDigests, expectedScores))) fail();
322
+ if (requireCycleEvidence && curves.cycleEvidenceVersion !== 1) {
323
+ throw new TypeError('unbound-cycle-evaluation-cannot-resume');
324
+ }
325
+ if ((layered || requireCycleEvidence) && curves.candidateDigest !== digest) {
326
+ throw new TypeError('saved-candidate-evaluation-evidence-is-stale');
327
+ }
328
+ if ((layered || requireCycleEvidence)
329
+ && (!expectedScores || !isDeepStrictEqual(curves.scoreDigests, expectedScores))) {
330
+ throw new TypeError('saved-score-evaluation-evidence-is-stale');
331
+ }
332
+ const expectedFitEvidence = layerFitEvidence(manifest, versionDir);
333
+ if ((Object.keys(expectedFitEvidence).length || Object.hasOwn(curves, 'fitEvidence'))
334
+ && !isDeepStrictEqual(curves.fitEvidence || {}, expectedFitEvidence)) fail();
335
+ const expectedSources = { validation: Object.fromEntries(Object.keys(curves.stages).map(stage => [stage,
336
+ manifest.stages[stage].layer ? 'cross-fit-validation-scores' : 'validation-scores'])),
337
+ holdout: Object.keys(curves.floor.detail.stages).length ? 'independent-holdout-scores' : null };
338
+ if (Object.hasOwn(curves, 'evaluationSources')
339
+ && !isDeepStrictEqual(curves.evaluationSources, expectedSources)) fail();
340
+ for (const [stage, metrics] of Object.entries(curves.stages)) {
341
+ if (Object.hasOwn(metrics, 'logLossSource') && metrics.logLossSource !== expectedSources.validation[stage]) fail();
342
+ }
343
+ }
344
+
345
+ function layerFitEvidence(manifest, versionDir) {
346
+ const evidence = {};
347
+ for (const [stage, entry] of Object.entries(manifest.stages)) {
348
+ if (!entry.layer) continue;
349
+ let fit;
350
+ try { fit = JSON.parse(fs.readFileSync(path.join(versionDir, entry.layer), 'utf8')).fit; }
351
+ catch (_) { continue; } // Preserve legacy history records whose layer bytes are opaque here.
352
+ const keys = ['fitNll', 'fitNllSource', 'baseFitNll', 'baseFitNllSource', 'oofNll', 'oofNllSource'];
353
+ if (keys.every(key => !Object.hasOwn(fit || {}, key))) continue;
354
+ if (!fit || !Number.isFinite(fit.fitNll) || fit.fitNllSource !== 'full-validation-recipe-selection'
355
+ || !Number.isFinite(fit.baseFitNll) || fit.baseFitNllSource !== 'full-validation-base-scores'
356
+ || !Number.isFinite(fit.oofNll) || fit.oofNllSource !== 'two-fold-cross-fit-validation') fail();
357
+ evidence[stage] = {
358
+ fitNll: { value: fit.fitNll, source: fit.fitNllSource },
359
+ baseFitNll: { value: fit.baseFitNll, source: fit.baseFitNllSource },
360
+ oofNll: { value: fit.oofNll, source: fit.oofNllSource },
361
+ };
362
+ }
363
+ return evidence;
324
364
  }
325
365
 
326
366
  function validateSavedTrend(trend, version) {
@@ -422,10 +462,15 @@ function stageFiles(args, option) {
422
462
  }
423
463
 
424
464
  function parseArgs(argv) {
425
- const parsed = { val: [], holdout: [] };
465
+ const parsed = { val: [], holdout: [], cycleEvidence: false };
426
466
  const names = { '--version': 'version', '--version-dir': 'versionDir', '--val-scores': 'val', '--holdout-scores': 'holdout',
427
467
  '--history': 'history', '--out': 'out', '--resume-curves': 'resumeCurves' };
428
468
  for (let i = 0; i < argv.length; i++) {
469
+ if (argv[i] === '--cycle-evidence') {
470
+ if (parsed.cycleEvidence) fail();
471
+ parsed.cycleEvidence = true;
472
+ continue;
473
+ }
429
474
  const key = names[argv[i]]; const value = argv[++i];
430
475
  if (!key || value === undefined) fail();
431
476
  if (key === 'val' || key === 'holdout') parsed[key].push(value);
@@ -444,8 +489,9 @@ function run(argv) {
444
489
  args.history = assertPrivateHistoryFile(args.history);
445
490
  const manifest = readManifest(args.versionDir, args.version);
446
491
  const layered = hasLayeredStages(manifest);
447
- if (args.resumeCurves && !layered && (args.val.length || args.holdout.length)) fail();
448
- const digest = layered ? candidateDigest(args.versionDir, manifest) : null;
492
+ if (args.resumeCurves && !layered && !args.cycleEvidence && (args.val.length || args.holdout.length)) fail();
493
+ const bindsEvidence = layered || args.cycleEvidence;
494
+ const digest = bindsEvidence ? candidateDigest(args.versionDir, manifest) : null;
449
495
  if (args.resumeCurves) {
450
496
  const valFiles = stageFiles(args, 'val');
451
497
  const holdoutFiles = stageFiles(args, 'holdout');
@@ -454,10 +500,10 @@ function run(argv) {
454
500
  curves = JSON.parse(fs.readFileSync(args.resumeCurves, 'utf8'));
455
501
  trend = JSON.parse(fs.readFileSync(path.join(args.out, 'trend.json'), 'utf8'));
456
502
  } catch (_) { fail(); }
457
- const expectedScores = layered && Object.keys(valFiles).length && Object.keys(holdoutFiles).length
503
+ const expectedScores = bindsEvidence && Object.keys(valFiles).length && Object.keys(holdoutFiles).length
458
504
  ? { validation: scoreDigests(valFiles), holdout: scoreDigests(holdoutFiles) } : null;
459
- if (layered && (!expectedScores || !isDeepStrictEqual(Object.keys(valFiles).sort(), Object.keys(holdoutFiles).sort()))) fail();
460
- validateSavedCurves(curves, args.version, manifest, digest, expectedScores);
505
+ if (bindsEvidence && (!expectedScores || !isDeepStrictEqual(Object.keys(valFiles).sort(), Object.keys(holdoutFiles).sort()))) fail();
506
+ validateSavedCurves(curves, args.version, args.versionDir, manifest, digest, expectedScores, args.cycleEvidence);
461
507
  validateSavedTrend(trend, args.version);
462
508
  const history = readHistory(args.history);
463
509
  validateBaselineReferences(curves, history);
@@ -476,6 +522,7 @@ function run(argv) {
476
522
  const valRows = readRows(file, stage, entry.options);
477
523
  const referenceOnly = entry.referenceOnly ?? [];
478
524
  stages[stage] = scoreRows(valRows, stage, entry.options, referenceOnly);
525
+ stages[stage].logLossSource = entry.layer ? 'cross-fit-validation-scores' : 'validation-scores';
479
526
  if (holdoutFiles[stage]) {
480
527
  const holdoutRows = readRows(holdoutFiles[stage], stage, entry.options);
481
528
  const valIds = new Set(valRows.map(row => row.id));
@@ -487,9 +534,15 @@ function run(argv) {
487
534
  const history = readHistory(args.history);
488
535
  if (history.some(row => row.version === args.version)) throw new TypeError(VERSION_ALREADY_RECORDED);
489
536
  const floor = assessFloor(Object.keys(holdoutMetrics).length ? holdoutMetrics : null, history);
537
+ const fitEvidence = layerFitEvidence(manifest, args.versionDir);
490
538
  const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(),
491
- ...(layered ? { candidateDigest: digest,
492
- scoreDigests: { validation: scoreDigests(valFiles), holdout: scoreDigests(holdoutFiles) } } : {}), stages, floor };
539
+ ...(args.cycleEvidence ? { cycleEvidenceVersion: 1 } : {}),
540
+ ...(bindsEvidence ? { candidateDigest: digest,
541
+ scoreDigests: { validation: scoreDigests(valFiles), holdout: scoreDigests(holdoutFiles) } } : {}),
542
+ ...(bindsEvidence ? { evaluationSources: { validation: Object.fromEntries(Object.keys(stages).map(stage => [stage,
543
+ stages[stage].logLossSource])),
544
+ holdout: Object.keys(holdoutFiles).length ? 'independent-holdout-scores' : null } } : {}),
545
+ ...(Object.keys(fitEvidence).length ? { fitEvidence } : {}), stages, floor };
493
546
  validateBaselineReferences(curves, history);
494
547
  const trend = decideTrend(curves, history, floor);
495
548
  fs.mkdirSync(args.out, { recursive: true });
@@ -499,21 +552,25 @@ function run(argv) {
499
552
  const summary = Object.fromEntries(Object.entries(stages).map(([stage, value]) => [stage, {
500
553
  rows: readJsonl(valFiles[stage]).length,
501
554
  logLoss: value.logLoss,
555
+ logLossSource: value.logLossSource,
502
556
  brier: value.brier,
503
557
  ece: value.ece,
504
558
  coverageAccuracyAuc: coverageAccuracyAuc(value.coverageCurve),
559
+ ...(fitEvidence[stage] ? { fitEvidence: fitEvidence[stage] } : {}),
505
560
  }]));
506
- console.log(JSON.stringify({ rows: Object.values(summary).reduce((sum, item) => sum + item.rows, 0), stages: summary }));
561
+ console.log(JSON.stringify({ rows: Object.values(summary).reduce((sum, item) => sum + item.rows, 0),
562
+ evaluationSources: curves.evaluationSources, stages: summary }));
507
563
  return { curves, trend };
508
564
  }
509
565
 
510
566
  if (require.main === module) {
511
567
  try { run(process.argv.slice(2)); } catch (error) {
512
- const message = error?.message === VERSION_ALREADY_RECORDED ? VERSION_ALREADY_RECORDED
513
- : 'invalid arguments, manifest, history, or score input';
568
+ const publicErrors = new Set([VERSION_ALREADY_RECORDED, 'unbound-cycle-evaluation-cannot-resume',
569
+ 'saved-candidate-evaluation-evidence-is-stale', 'saved-score-evaluation-evidence-is-stale']);
570
+ const message = publicErrors.has(error?.message) ? error.message : 'invalid arguments, manifest, history, or score input';
514
571
  console.error(`system-one-curves: ${message}`);
515
572
  process.exitCode = 1;
516
573
  }
517
574
  }
518
575
 
519
- module.exports = { coverageAccuracyAuc, run, scoreRows };
576
+ module.exports = { coverageAccuracyAuc, layerFitEvidence, run, scoreRows };
@@ -11,10 +11,13 @@ const { validateVersionManifest } = require('../../harness-everything/scripts/sy
11
11
 
12
12
  const HOLDOUTS = { validity: 'system-one-holdout.json', tier: 'system-one-holdout.json', intent: 'system-one-intent-holdout.json' };
13
13
 
14
- function runProcess(command, args) {
15
- const result = spawnSync(command, args, { cwd: REPO, stdio: 'ignore', windowsHide: true,
14
+ function runProcess(command, args, { includeError = false } = {}) {
15
+ const result = spawnSync(command, args, { cwd: REPO, stdio: includeError ? ['ignore', 'ignore', 'pipe'] : 'ignore', windowsHide: true,
16
16
  env: { ...process.env, HARNESS_SYSTEM_ONE_NODE: process.execPath } });
17
- if (result.error || result.status !== 0) throw new Error(`${path.basename(command)} failed${result.status === null ? '' : ` (${result.status})`}`);
17
+ if (result.error || result.status !== 0) {
18
+ const detail = includeError && result.stderr ? `: ${result.stderr.toString('utf8').trim()}` : '';
19
+ throw new Error(`${path.basename(command)} failed${result.status === null ? '' : ` (${result.status})`}${detail}`);
20
+ }
18
21
  }
19
22
 
20
23
  function pythonExecutable() {
@@ -30,6 +33,13 @@ function recordEvaluation(manifestFile, version) {
30
33
  return manifest;
31
34
  }
32
35
 
36
+ function fitEvidenceMatches(layerFit, outcome) {
37
+ const keys = ['fitNll', 'fitNllSource', 'baseFitNll', 'baseFitNllSource', 'oofNll', 'oofNllSource'];
38
+ const hasOutcomeEvidence = keys.some(key => Object.hasOwn(outcome, key));
39
+ if (!hasOutcomeEvidence) return true;
40
+ return keys.every(key => Object.hasOwn(layerFit, key) && layerFit[key] === outcome[key]);
41
+ }
42
+
33
43
  function verifyLayerPair(versionDir, sourceDir, outcomes) {
34
44
  const manifestFile = path.join(versionDir, 'manifest.json');
35
45
  const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
@@ -49,6 +59,8 @@ function verifyLayerPair(versionDir, sourceDir, outcomes) {
49
59
  throw new Error(`${task} candidate thresholds do not match the current validated calibration`);
50
60
  if (entry.sha256 !== outcome.checkpointSha256)
51
61
  throw new Error(`${task} candidate checkpoint does not match its fit outcome`);
62
+ if (digest(path.join(versionDir, entry.weights)) !== outcome.checkpointSha256)
63
+ throw new Error(`${task} candidate weights do not match its fit outcome`);
52
64
  if (!/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
53
65
  || digest(path.join(versionDir, entry.config)) !== outcome.checkpointConfigSha256)
54
66
  throw new Error(`${task} candidate checkpoint config does not match its fit outcome`);
@@ -57,6 +69,8 @@ function verifyLayerPair(versionDir, sourceDir, outcomes) {
57
69
  || entry.layerSha256 !== outcome.layerSha256 || entry.sha256 !== outcome.checkpointSha256) {
58
70
  throw new Error(`${task} candidate layer does not match its fit`);
59
71
  }
72
+ const layer = JSON.parse(fs.readFileSync(path.join(sourceDir, task, 'layer.json'), 'utf8'));
73
+ if (!fitEvidenceMatches(layer.fit || {}, outcome)) throw new Error(`${task} candidate NLL evidence does not match its fit`);
60
74
  } else if (entry.layer || outcome.outcome !== 'keep-base') {
61
75
  throw new Error(`${task} candidate layer fit is missing or inconsistent`);
62
76
  }
@@ -83,15 +97,13 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
83
97
  if (fs.existsSync(curvesFile) && fs.existsSync(trendFile)) {
84
98
  const candidate = verifyLayerPair(versionDir, source, outcomes);
85
99
  const resumeArgs = [curvesScript, '--version', version, '--version-dir', versionDir,
86
- '--history', history, '--out', evaluationDir, '--resume-curves', curvesFile];
87
- if (Object.values(candidate.stages).some(stage => stage.layer)) {
88
- for (const task of TASKS) {
89
- const validation = candidate.stages[task].layer ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
90
- resumeArgs.push('--val-scores', `${task}=${path.join(source, task, validation)}`);
91
- resumeArgs.push('--holdout-scores', `${task}=${path.join(evaluationDir, `${task}-holdout-scores.jsonl`)}`);
92
- }
100
+ '--history', history, '--out', evaluationDir, '--resume-curves', curvesFile, '--cycle-evidence'];
101
+ for (const task of TASKS) {
102
+ const validation = candidate.stages[task].layer ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
103
+ resumeArgs.push('--val-scores', `${task}=${path.join(source, task, validation)}`);
104
+ resumeArgs.push('--holdout-scores', `${task}=${path.join(evaluationDir, `${task}-holdout-scores.jsonl`)}`);
93
105
  }
94
- runProcess(process.execPath, resumeArgs);
106
+ runProcess(process.execPath, resumeArgs, { includeError: true });
95
107
  const manifestFile = path.join(versionDir, 'manifest.json');
96
108
  recordEvaluation(manifestFile, version);
97
109
  const trend = JSON.parse(fs.readFileSync(trendFile, 'utf8'));
@@ -103,7 +115,7 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
103
115
  fs.mkdirSync(evaluationDir, { recursive: true, mode: 0o700 });
104
116
  const scoreScript = path.join(__dirname, 'score.py');
105
117
  const holdoutDir = path.join(REPO, 'benchmarks', 'fixtures');
106
- const curvesArgs = ['--version', version, '--version-dir', versionDir];
118
+ const curvesArgs = ['--version', version, '--version-dir', versionDir, '--cycle-evidence'];
107
119
  for (const task of TASKS) {
108
120
  const heldOut = path.join(holdoutDir, HOLDOUTS[task]);
109
121
  const scores = path.join(evaluationDir, `${task}-holdout-scores.jsonl`);
@@ -121,4 +133,4 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
121
133
  return { version, verdict: trend.verdict, compared: trend.compared.length };
122
134
  }
123
135
 
124
- module.exports = { evaluateCycle, HOLDOUTS, verifyLayerPair };
136
+ module.exports = { evaluateCycle, fitEvidenceMatches, HOLDOUTS, verifyLayerPair };
@@ -93,6 +93,18 @@ function runGuarded(command, args, { maxRssMb = 6144, threads = 4, pollMs = 500,
93
93
  });
94
94
  }
95
95
 
96
+ function runGuardedSync(command, args, options) {
97
+ const script = `const { runGuarded } = require(${JSON.stringify(__filename)});
98
+ runGuarded(process.argv[1], JSON.parse(process.argv[2]), JSON.parse(process.argv[3])).then(
99
+ result => process.stdout.write(JSON.stringify(result)),
100
+ error => { process.stderr.write(error.message); process.exitCode = 1; });`;
101
+ const result = spawnSync(process.execPath, ['-e', script, command, JSON.stringify(args), JSON.stringify(options)], {
102
+ cwd: REPO, encoding: 'utf8', windowsHide: true,
103
+ });
104
+ if (result.error || result.status !== 0) throw new Error(`resource guard failed${result.status === null ? '' : ` (${result.status})`}`);
105
+ return JSON.parse(result.stdout);
106
+ }
107
+
96
108
  function pythonExecutable() {
97
109
  return process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
98
110
  }
@@ -173,7 +185,7 @@ function validateFitStage({ runDir, task, dataDir, checkpointPath, checkpointCon
173
185
  try {
174
186
  outcome = JSON.parse(fs.readFileSync(outcomePath, 'utf8'));
175
187
  calibration = JSON.parse(fs.readFileSync(calibrationPath, 'utf8'));
176
- } catch { throw new Error(`${task} fit outcome or calibration is missing or invalid`); }
188
+ } catch { throw new Error(`${task} fit outcome or calibration is missing, invalid, or stale`); }
177
189
  const checkpoint = checkpointPath || path.join(runDir, 'harness-routing-v1.safetensors');
178
190
  const checkpointConfig = checkpointConfigPath || path.join(runDir, 'harness-routing-v1.json');
179
191
  const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
@@ -221,7 +233,7 @@ function validateFitStage({ runDir, task, dataDir, checkpointPath, checkpointCon
221
233
  return { report, outcome, calibration, scorePath };
222
234
  }
223
235
 
224
- function fitLayerStage({ dataDir, runDir, task }) {
236
+ function fitLayerStage({ dataDir, runDir, task, run, maxRssMb = 6144, threads = 4, pollMs = 500, rssReader }) {
225
237
  const fitter = path.join(REPO, 'scripts', 'system-one-fit-layer.py');
226
238
  const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
227
239
  const bundle = dataPath(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
@@ -256,28 +268,58 @@ function fitLayerStage({ dataDir, runDir, task }) {
256
268
  }
257
269
  } catch { /* Refit incomplete or stale stage artifacts below. */ }
258
270
  }
259
- const result = spawnSync(pythonExecutable(), [fitter, '--run-dir', runDir, '--data-dir', bundle,
260
- '--task', task, '--holdout', holdout], { cwd: REPO, stdio: 'ignore', windowsHide: true });
261
- if (result.error || result.status !== 0) throw new Error(`system-one-fit-layer.py failed${result.status === null ? '' : ` (${result.status})`}`);
262
- const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
263
- if (!['layer', 'keep-base'].includes(outcome.outcome)) throw new Error(`layer fit for ${task} has no explicit outcome`);
264
- const scores = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
265
- if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
266
- || !fs.existsSync(path.join(runDir, scores)))) throw new Error(`layer fit for ${task} is incomplete`);
267
- runNode(calibrator, [path.join(runDir, scores), path.join(runDir, 'calibration.json'), '--task', task,
268
- '--catalog', path.join(runDir, 'train-report.json')]);
269
- if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
270
- || !fs.existsSync(path.join(runDir, 'val-scores-layered.jsonl')))) throw new Error(`layer fit for ${task} is incomplete`);
271
- outcome.calibrationInput = scores;
272
- outcome.calibrationInputSha256 = sha256(path.join(runDir, scores));
273
- outcome.calibrationSha256 = sha256(path.join(runDir, 'calibration.json'));
274
- if (outcome.outcome === 'layer' && outcome.oofScoreSpace !== 'h-transform-v2')
275
- throw new Error(`layer fit for ${task} does not prove corrected OOF score space`);
276
- if (outcome.outcome === 'keep-base' && outcome.oofScoreSpace !== null)
277
- throw new Error(`layer fit for ${task} has an invalid keep-base score-space marker`);
278
- writeJson(outcomeFile, outcome);
279
- validateFitStage({ runDir, task, dataDir });
280
- return outcome;
271
+ const finishFit = () => {
272
+ const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
273
+ if (!['layer', 'keep-base'].includes(outcome.outcome)) throw new Error(`layer fit for ${task} has no explicit outcome`);
274
+ const scores = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
275
+ if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
276
+ || !fs.existsSync(path.join(runDir, scores)))) throw new Error(`layer fit for ${task} is incomplete`);
277
+ runNode(calibrator, [path.join(runDir, scores), path.join(runDir, 'calibration.json'), '--task', task,
278
+ '--catalog', path.join(runDir, 'train-report.json')]);
279
+ if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
280
+ || !fs.existsSync(path.join(runDir, 'val-scores-layered.jsonl')))) throw new Error(`layer fit for ${task} is incomplete`);
281
+ outcome.calibrationInput = scores;
282
+ outcome.calibrationInputSha256 = sha256(path.join(runDir, scores));
283
+ outcome.calibrationSha256 = sha256(path.join(runDir, 'calibration.json'));
284
+ if (outcome.outcome === 'layer' && outcome.oofScoreSpace !== 'h-transform-v2')
285
+ throw new Error(`layer fit for ${task} does not prove corrected OOF score space`);
286
+ if (outcome.outcome === 'keep-base' && outcome.oofScoreSpace !== null)
287
+ throw new Error(`layer fit for ${task} has an invalid keep-base score-space marker`);
288
+ writeJson(outcomeFile, outcome);
289
+ validateFitStage({ runDir, task, dataDir });
290
+ return outcome;
291
+ };
292
+
293
+ const removeOutcome = () => fs.rmSync(outcomeFile, { force: true });
294
+ const discardFailedFit = () => writeJson(outcomeFile, { schemaVersion: 0, task, failedFit: true });
295
+ const completeGuardedFit = result => {
296
+ if (result.killedForLimit) {
297
+ discardFailedFit();
298
+ throw new Error(`layer fit for ${task} exceeded the ${maxRssMb} MB RSS limit`);
299
+ }
300
+ if (result.monitorFailed) {
301
+ discardFailedFit();
302
+ throw new Error(`system-one-fit-layer.py failed (RSS monitoring failed)`);
303
+ }
304
+ if (result.exitCode !== 0) {
305
+ discardFailedFit();
306
+ throw new Error(`system-one-fit-layer.py failed${result.exitCode === null ? '' : ` (${result.exitCode})`}`);
307
+ }
308
+ try { return finishFit(); }
309
+ catch (error) { discardFailedFit(); throw error; }
310
+ };
311
+ removeOutcome();
312
+ let guarded;
313
+ try {
314
+ guarded = (run || runGuardedSync)(pythonExecutable(), [fitter, '--run-dir', runDir, '--data-dir', bundle,
315
+ '--task', task, '--holdout', holdout], { maxRssMb, threads, pollMs, rssReader });
316
+ } catch (error) {
317
+ discardFailedFit();
318
+ throw error;
319
+ }
320
+ if (guarded && typeof guarded.then === 'function')
321
+ return guarded.then(completeGuardedFit, error => { discardFailedFit(); throw error; });
322
+ return completeGuardedFit(guarded);
281
323
  }
282
324
 
283
325
  async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run = runGuarded }) {
@@ -312,7 +354,7 @@ async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run
312
354
  trained++;
313
355
  }
314
356
  if (!hasTrainerReport(out, task)) throw new Error(`training ${task} has no valid trainer report`);
315
- const outcome = fitLayerStage({ dataDir: privateDir, runDir: out, task });
357
+ const outcome = await fitLayerStage({ dataDir: privateDir, runDir: out, task, run, threads, maxRssMb });
316
358
  validateFitStage({ runDir: out, task, dataDir: privateDir });
317
359
  if (fs.existsSync(guardFile)) outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
318
360
  if (outcome) {
@@ -58,6 +58,14 @@ def row_nll(rows, predictions, task):
58
58
  return loss / len(rows)
59
59
 
60
60
 
61
+ def nll_evidence(selected, rows, oof_predictions, task):
62
+ """Name recipe-selection loss separately from cross-fit validation loss."""
63
+ return {'fitNll': selected['nll'], 'fitNllSource': 'full-validation-recipe-selection',
64
+ 'baseFitNll': selected['baseNll'], 'baseFitNllSource': 'full-validation-base-scores',
65
+ 'oofNll': row_nll(rows, oof_predictions, task),
66
+ 'oofNllSource': 'two-fold-cross-fit-validation'}
67
+
68
+
61
69
  def _layered_scores(logits, row, task, recipe, knn, layer_api, neighbor_distribution=None):
62
70
  q = layer_api.transform(logits, task, recipe['temperature'], recipe['bias'])
63
71
  if recipe['alpha']:
@@ -318,6 +326,7 @@ def fit_layer(run_dir, data_dir, task, holdout):
318
326
  neighbor_distributions = precompute_knn(rows, task, knn, logits_by_id)
319
327
  recipes, oof = cross_fit(rows, logits_by_id, task, knn, layer_api, fit_temp_bias, neighbor_distributions)
320
328
  final = select_recipe(rows, logits_by_id, task, knn, layer_api, fit_temp_bias, neighbor_distributions)
329
+ evidence = nll_evidence(final, rows, oof, task)
321
330
  output_rows = score_rows(rows, report['catalog'], task, oof)
322
331
  output = Path(run_dir)
323
332
  write_private(output / 'val-scores-layered.jsonl', ''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in output_rows))
@@ -329,6 +338,7 @@ def fit_layer(run_dir, data_dir, task, holdout):
329
338
  'validationIds': [row['id'] for row in rows], 'folds': recipes,
330
339
  'candidate': final['candidate'], 'temperature': final['temperature'], 'alpha': final['alpha'],
331
340
  'baseNll': final['baseNll'], 'selectedNll': final['nll'],
341
+ **evidence,
332
342
  'oofScoreSpace': oof_score_space(final['candidate'])}
333
343
  if final['candidate'] == 'keep-base':
334
344
  for filename in ('layer.json', 'val-scores-layered.jsonl'):
@@ -341,7 +351,7 @@ def fit_layer(run_dir, data_dir, task, holdout):
341
351
  'temperature': final['temperature'], 'bias': final['bias'], 'alpha': final['alpha'],
342
352
  'k': 15, 'ngrams': [3, 4, 5], 'maxChars': 2000, 'index': index,
343
353
  'fit': {'candidate': final['candidate'], 'heldOutRows': len(rows), 'nll': final['nll'],
344
- 'baseNll': final['baseNll'], 'oof': True}}
354
+ 'baseNll': final['baseNll'], 'oof': True, **evidence}}
345
355
  write_private(output / 'layer.json', json.dumps(layer, separators=(',', ':')) + '\n')
346
356
  outcome['outcome'] = 'layer'
347
357
  outcome['layerSha256'] = trainer.sha256_file(output / 'layer.json')