harness-everything 1.4.0 → 1.5.1

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 (53) 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/.github/workflows/release.yml +16 -5
  5. package/CHANGELOG.md +33 -0
  6. package/benchmarks/results/error-ledger-oracle-484-pilot/README.md +57 -0
  7. package/benchmarks/results/error-ledger-oracle-484-pilot/candidates.json +22802 -0
  8. package/benchmarks/results/error-ledger-oracle-484-pilot/labels.json +131 -0
  9. package/benchmarks/results/error-ledger-oracle-484-pilot/oracle.json +362 -0
  10. package/benchmarks/results/error-ledger-oracle-484-pilot/rows.json +648 -0
  11. package/benchmarks/results/error-ledger-oracle-484-pilot/sample.json +215 -0
  12. package/benchmarks/results/error-ledger-oracle-484-pilot/select.js +127 -0
  13. package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
  14. package/ci/mechanism-2x-release-automation.test.js +17 -0
  15. package/ci/mechanism-349-ci-change-scope.test.js +69 -1
  16. package/ci/mechanism-548-bigint-identity.test.js +1 -1
  17. package/ci/mechanism-571-fit-guard.test.js +165 -0
  18. package/ci/mechanism-571-nll-labels.test.js +79 -0
  19. package/ci/mechanism-system-one-colab.test.js +83 -5
  20. package/ci/mechanism-system-one-contract.test.js +30 -0
  21. package/ci/mechanism-system-one-curves.test.js +91 -0
  22. package/ci/mechanism-system-one-cycle.test.js +417 -34
  23. package/ci/mechanism-system-one-install.test.js +47 -0
  24. package/ci/mechanism-system-one-provider.test.js +2 -0
  25. package/ci/mechanism-system-one-resident.test.js +69 -0
  26. package/ci/system-one-adapter-test.py +86 -0
  27. package/ci/system-one-fit-layer-test.py +371 -0
  28. package/ci/system-one-layer-test.py +122 -0
  29. package/harness-everything/SKILL.md +1 -1
  30. package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  31. package/harness-everything/scripts/system-one/install.js +10 -0
  32. package/harness-everything/scripts/system-one/layer.py +188 -0
  33. package/harness-everything/scripts/system-one/manifest.js +8 -1
  34. package/harness-everything/scripts/system-one/provider.js +12 -2
  35. package/opencode-plugin/plugin.json +1 -1
  36. package/package.json +1 -1
  37. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  38. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  39. package/plugins/harness-everything/plugin.json +1 -1
  40. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  41. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  42. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
  43. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +188 -0
  44. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
  45. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
  46. package/sbom.cdx.json +7 -7
  47. package/scripts/system-one-colab.js +6 -4
  48. package/scripts/system-one-curves.js +114 -13
  49. package/scripts/system-one-cycle/evaluate.js +72 -9
  50. package/scripts/system-one-cycle/package.js +61 -3
  51. package/scripts/system-one-cycle/score.py +23 -2
  52. package/scripts/system-one-cycle/train.js +254 -20
  53. package/scripts/system-one-fit-layer.py +379 -0
@@ -1,19 +1,23 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('node:crypto');
3
4
  const fs = require('node:fs');
4
5
  const path = require('node:path');
5
6
  const { spawnSync } = require('node:child_process');
6
7
  const { REPO, dataPath, writeJson, assertPrivateDataDir, assertPrivateHistoryFile } = require('./common');
7
8
  const { buildVersion } = require('./package');
8
- const { TASKS } = require('./train');
9
+ const { TASKS, fitLayerStage, hasTrainerReport } = require('./train');
9
10
  const { validateVersionManifest } = require('../../harness-everything/scripts/system-one/manifest');
10
11
 
11
12
  const HOLDOUTS = { validity: 'system-one-holdout.json', tier: 'system-one-holdout.json', intent: 'system-one-intent-holdout.json' };
12
13
 
13
- function runProcess(command, args) {
14
- 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,
15
16
  env: { ...process.env, HARNESS_SYSTEM_ONE_NODE: process.execPath } });
16
- 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
+ }
17
21
  }
18
22
 
19
23
  function pythonExecutable() {
@@ -29,6 +33,51 @@ function recordEvaluation(manifestFile, version) {
29
33
  return manifest;
30
34
  }
31
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
+
43
+ function verifyLayerPair(versionDir, sourceDir, outcomes) {
44
+ const manifestFile = path.join(versionDir, 'manifest.json');
45
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
46
+ validateVersionManifest(manifest);
47
+ const digest = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
48
+ for (const task of TASKS) {
49
+ const entry = manifest.stages[task];
50
+ const outcome = outcomes[task];
51
+ if (!outcome) throw new Error(`${task} candidate fit outcome is missing`);
52
+ if (entry.weights !== `${task}.safetensors` || entry.config !== `${task}.json`)
53
+ throw new Error(`${task} candidate manifest paths do not match the scorer checkpoint files`);
54
+ const runDir = path.join(sourceDir, task);
55
+ const calibration = JSON.parse(fs.readFileSync(path.join(runDir, 'calibration.json'), 'utf8'));
56
+ const expectedThresholds = Object.fromEntries(entry.options.map(id => [id,
57
+ calibration.thresholds?.[id] === null ? 1 : calibration.thresholds?.[id]]));
58
+ if (JSON.stringify(expectedThresholds) !== JSON.stringify(entry.thresholds))
59
+ throw new Error(`${task} candidate thresholds do not match the current validated calibration`);
60
+ if (entry.sha256 !== outcome.checkpointSha256)
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`);
64
+ if (!/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
65
+ || digest(path.join(versionDir, entry.config)) !== outcome.checkpointConfigSha256)
66
+ throw new Error(`${task} candidate checkpoint config does not match its fit outcome`);
67
+ if (outcome.outcome === 'layer') {
68
+ if (!entry.layer || entry.layerSha256 !== digest(path.join(sourceDir, task, 'layer.json'))
69
+ || entry.layerSha256 !== outcome.layerSha256 || entry.sha256 !== outcome.checkpointSha256) {
70
+ throw new Error(`${task} candidate layer does not match its fit`);
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`);
74
+ } else if (entry.layer || outcome.outcome !== 'keep-base') {
75
+ throw new Error(`${task} candidate layer fit is missing or inconsistent`);
76
+ }
77
+ }
78
+ return manifest;
79
+ }
80
+
32
81
  function evaluateCycle({ dataDir, version, history: historyOption }) {
33
82
  const privateDir = assertPrivateDataDir(dataDir);
34
83
  const history = assertPrivateHistoryFile(historyOption === undefined
@@ -40,25 +89,39 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
40
89
  const trendFile = path.join(evaluationDir, 'trend.json');
41
90
  const curvesScript = path.join(REPO, 'scripts', 'system-one-curves.js');
42
91
  if (!fs.existsSync(curvesScript)) throw new Error('contract C curves CLI is not available in this checkout');
92
+ const outcomes = Object.fromEntries(TASKS.map(task => {
93
+ const runDir = path.join(source, task);
94
+ const hasFitInputs = hasTrainerReport(runDir, task);
95
+ return [task, hasFitInputs ? fitLayerStage({ dataDir: privateDir, runDir, task }) : null];
96
+ }));
43
97
  if (fs.existsSync(curvesFile) && fs.existsSync(trendFile)) {
44
- runProcess(process.execPath, [curvesScript, '--version', version, '--version-dir', versionDir,
45
- '--history', history, '--out', evaluationDir, '--resume-curves', curvesFile]);
98
+ const candidate = verifyLayerPair(versionDir, source, outcomes);
99
+ const resumeArgs = [curvesScript, '--version', version, '--version-dir', versionDir,
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`)}`);
105
+ }
106
+ runProcess(process.execPath, resumeArgs, { includeError: true });
46
107
  const manifestFile = path.join(versionDir, 'manifest.json');
47
108
  recordEvaluation(manifestFile, version);
48
109
  const trend = JSON.parse(fs.readFileSync(trendFile, 'utf8'));
49
110
  return { version, verdict: trend.verdict, compared: trend.compared.length, resumed: true };
50
111
  }
51
112
  buildVersion({ dataDir: privateDir, version, sourceDir: source, versionDir });
113
+ const candidate = verifyLayerPair(versionDir, source, outcomes);
52
114
 
53
115
  fs.mkdirSync(evaluationDir, { recursive: true, mode: 0o700 });
54
116
  const scoreScript = path.join(__dirname, 'score.py');
55
117
  const holdoutDir = path.join(REPO, 'benchmarks', 'fixtures');
56
- const curvesArgs = ['--version', version, '--version-dir', versionDir];
118
+ const curvesArgs = ['--version', version, '--version-dir', versionDir, '--cycle-evidence'];
57
119
  for (const task of TASKS) {
58
120
  const heldOut = path.join(holdoutDir, HOLDOUTS[task]);
59
121
  const scores = path.join(evaluationDir, `${task}-holdout-scores.jsonl`);
60
122
  runProcess(pythonExecutable(), [scoreScript, '--weights', path.join(versionDir, `${task}.safetensors`), '--holdout', heldOut, '--task', task, '--out', scores]);
61
- curvesArgs.push('--val-scores', `${task}=${path.join(source, task, 'val-scores.jsonl')}`);
123
+ const validation = candidate.stages[task].layer ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
124
+ curvesArgs.push('--val-scores', `${task}=${path.join(source, task, validation)}`);
62
125
  curvesArgs.push('--holdout-scores', `${task}=${scores}`);
63
126
  }
64
127
  curvesArgs.push('--history', history, '--out', evaluationDir);
@@ -70,4 +133,4 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
70
133
  return { version, verdict: trend.verdict, compared: trend.compared.length };
71
134
  }
72
135
 
73
- module.exports = { evaluateCycle, HOLDOUTS };
136
+ module.exports = { evaluateCycle, fitEvidenceMatches, HOLDOUTS, verifyLayerPair };
@@ -5,7 +5,7 @@ const fs = require('node:fs');
5
5
  const path = require('node:path');
6
6
  const { spawnSync } = require('node:child_process');
7
7
  const { REPO, dataPath, writeJson, assertPrivateDataDir } = require('./common');
8
- const { TASKS } = require('./train');
8
+ const { TASKS, validateFitStage } = require('./train');
9
9
  const { validateVersionManifest } = require('../../harness-everything/scripts/system-one/manifest');
10
10
 
11
11
  function trainerCatalogs() {
@@ -41,11 +41,40 @@ function copy(source, target) {
41
41
  if (process.platform !== 'win32') fs.chmodSync(target, 0o600);
42
42
  }
43
43
 
44
+ function validatePackagedFitEvidence(runDir, stage, task, checkpointPath, checkpointConfigPath, options, dataDir) {
45
+ const evidence = validateFitStage({ runDir, task, checkpointPath, checkpointConfigPath, dataDir });
46
+ const legacyOptions = task === 'intent' ? options.filter(id => id !== 'unclassified') : options;
47
+ if (evidence.report.catalog.join('\0') !== options.join('\0')
48
+ || (stage.options.join('\0') !== options.join('\0') && stage.options.join('\0') !== legacyOptions.join('\0')))
49
+ throw new Error(`${task} candidate fit evidence is stale`);
50
+ const thresholds = Object.fromEntries(stage.options.map(id => [id,
51
+ evidence.calibration.thresholds[id] === null ? 1 : evidence.calibration.thresholds[id]]));
52
+ if (JSON.stringify(thresholds) !== JSON.stringify(stage.thresholds))
53
+ throw new Error(`${task} candidate thresholds do not match their bound calibration`);
54
+ return evidence;
55
+ }
56
+
44
57
  function safeRelative(value) {
45
58
  return typeof value === 'string' && value.length > 0 && !path.isAbsolute(value)
46
59
  && !value.split(/[\\/]/).some(part => part === '..' || part === '.');
47
60
  }
48
61
 
62
+ function readLayer(source, task, options, expectedHash = null) {
63
+ const stat = fs.statSync(source);
64
+ if (!stat.isFile() || stat.size > 32 * 1024 * 1024) throw new Error(`${task} layer artifact is invalid`);
65
+ const actualHash = digest(source);
66
+ if (expectedHash && actualHash !== expectedHash) throw new Error(`${task} layer hash does not match its manifest`);
67
+ let layer;
68
+ try { layer = JSON.parse(fs.readFileSync(source, 'utf8')); }
69
+ catch { throw new Error(`${task} layer artifact is invalid`); }
70
+ if (layer.schemaVersion !== 1 || layer.kind !== 'echl-h' || layer.stage !== task
71
+ || !Array.isArray(layer.options) || layer.options.join('\0') !== options.join('\0')
72
+ || !Number.isFinite(layer.temperature) || layer.temperature <= 0
73
+ || !Number.isFinite(layer.alpha) || layer.alpha < 0 || layer.alpha > 1
74
+ || !layer.fit || layer.fit.oof !== true) throw new Error(`${task} layer fit is missing or stale`);
75
+ return actualHash;
76
+ }
77
+
49
78
  function buildVersion({ dataDir, version, versionDir, sourceDir }) {
50
79
  validateVersion(version);
51
80
  const privateDir = assertPrivateDataDir(dataDir);
@@ -64,6 +93,8 @@ function buildVersion({ dataDir, version, versionDir, sourceDir }) {
64
93
  let options;
65
94
  let thresholds;
66
95
  let priorReferenceOnly = [];
96
+ let sourceLayer = null;
97
+ let layerHash = null;
67
98
  let targetWeights = `${task}.safetensors`;
68
99
  let targetConfig = `${task}.json`;
69
100
 
@@ -81,6 +112,16 @@ function buildVersion({ dataDir, version, versionDir, sourceDir }) {
81
112
  thresholds = { ...stage.thresholds };
82
113
  priorReferenceOnly = stage.referenceOnly ?? [];
83
114
  if (digest(sourceWeights) !== stage.sha256) throw new Error(`${task} checkpoint hash does not match its manifest`);
115
+ const runDir = path.join(dataPath(privateDir, 'training', 'runs', version), task);
116
+ const evidence = validatePackagedFitEvidence(runDir, stage, task, sourceWeights, sourceConfig, options, privateDir);
117
+ if (evidence.outcome.outcome === 'layer') {
118
+ if (!stage.layer || stage.layerSha256 !== evidence.outcome.layerSha256)
119
+ throw new Error(`${task} candidate layer does not match its fit evidence`);
120
+ sourceLayer = path.join(source, stage.layer);
121
+ layerHash = readLayer(sourceLayer, task, options, stage.layerSha256);
122
+ } else if (stage.layer || evidence.outcome.outcome !== 'keep-base') {
123
+ throw new Error(`${task} candidate fit outcome is inconsistent`);
124
+ }
84
125
  } else {
85
126
  const runDir = path.join(source, task);
86
127
  sourceWeights = path.join(runDir, 'harness-routing-v1.safetensors');
@@ -88,6 +129,14 @@ function buildVersion({ dataDir, version, versionDir, sourceDir }) {
88
129
  const calibration = JSON.parse(fs.readFileSync(path.join(runDir, 'calibration.json'), 'utf8'));
89
130
  thresholds = calibration.thresholds;
90
131
  options = catalogs[task];
132
+ const evidence = validateFitStage({ runDir, task, dataDir: privateDir,
133
+ checkpointPath: sourceWeights, checkpointConfigPath: sourceConfig });
134
+ if (evidence.report.catalog.join('\0') !== options.join('\0'))
135
+ throw new Error(`${task} trainer report catalog does not match the package`);
136
+ if (evidence.outcome.outcome === 'layer') {
137
+ sourceLayer = path.join(runDir, 'layer.json');
138
+ layerHash = readLayer(sourceLayer, task, options, evidence.outcome.layerSha256);
139
+ }
91
140
  }
92
141
  // Older packages omitted this non-selectable intent option; restore its metadata without retraining.
93
142
  if (task === 'intent' && options.includes('unclassified') && thresholds && typeof thresholds === 'object'
@@ -110,8 +159,17 @@ function buildVersion({ dataDir, version, versionDir, sourceDir }) {
110
159
  const targetConfigPath = path.join(target, targetConfig);
111
160
  if (path.resolve(sourceWeights) !== targetWeightsPath) copy(sourceWeights, targetWeightsPath);
112
161
  if (path.resolve(sourceConfig) !== targetConfigPath) copy(sourceConfig, targetConfigPath);
113
- stages[task] = { weights: targetWeights, config: targetConfig, sha256: digest(targetWeightsPath),
162
+ const stageManifest = { weights: targetWeights, config: targetConfig, sha256: digest(targetWeightsPath),
114
163
  options: [...options], thresholds: finalThresholds, ...(referenceOnly.length ? { referenceOnly } : {}) };
164
+ if (sourceLayer) {
165
+ const targetLayer = `${task}.layer.json`;
166
+ const targetLayerPath = path.join(target, targetLayer);
167
+ if (path.resolve(sourceLayer) !== targetLayerPath) copy(sourceLayer, targetLayerPath);
168
+ if (digest(targetLayerPath) !== layerHash) throw new Error(`${task} layer copy did not preserve its hash`);
169
+ stageManifest.layer = targetLayer;
170
+ stageManifest.layerSha256 = layerHash;
171
+ } else fs.rmSync(path.join(target, `${task}.layer.json`), { force: true });
172
+ stages[task] = stageManifest;
115
173
  }
116
174
 
117
175
  const sourceEvaluation = path.join(source, 'evaluation');
@@ -170,4 +228,4 @@ function publishVersion({ dataDir, version }) {
170
228
  return { version, publishedPath: target };
171
229
  }
172
230
 
173
- module.exports = { buildVersion, publishVersion, trainerCatalogs, validateVersion, digest, safeRelative };
231
+ module.exports = { buildVersion, publishVersion, trainerCatalogs, validateVersion, digest, safeRelative, readLayer };
@@ -10,6 +10,7 @@ example a tier case with no tier) is skipped and counted in the printed `skipped
10
10
  import argparse
11
11
  import importlib.util
12
12
  import json
13
+ import math
13
14
  import os
14
15
  from pathlib import Path
15
16
  import shutil
@@ -51,6 +52,23 @@ def trained_catalog(weights, task, holdout):
51
52
  return [{'id': option_id, 'text': texts[option_id]} for option_id in ids]
52
53
 
53
54
 
55
+ def layer_for(weights, task, options):
56
+ manifest = json.loads((Path(weights).parent / 'manifest.json').read_text(encoding='utf-8'))
57
+ stage = manifest['stages'][task]
58
+ has_layer = 'layer' in stage
59
+ has_hash = 'layerSha256' in stage
60
+ if has_layer != has_hash:
61
+ raise ValueError('layer manifest is incomplete')
62
+ if not has_layer:
63
+ return None
64
+ layer_path = Path(weights).parent / stage['layer']
65
+ module_path = Path(__file__).resolve().parents[2] / 'harness-everything' / 'scripts' / 'system-one' / 'layer.py'
66
+ spec = importlib.util.spec_from_file_location('system_one_layer', module_path)
67
+ layer_api = importlib.util.module_from_spec(spec)
68
+ spec.loader.exec_module(layer_api)
69
+ return layer_api, layer_api.load_layer(layer_path, stage['layerSha256'], task, options)
70
+
71
+
54
72
  def eligible(case, task, ids):
55
73
  """A case is scored when its gold label is a catalog id; validity always scores."""
56
74
  if task == 'validity':
@@ -78,6 +96,7 @@ def main():
78
96
  catalog = trained_catalog(args.weights, args.task, args.holdout)
79
97
  ids = {option['id'] for option in catalog}
80
98
  options = tuple(option['text'] for option in catalog)
99
+ layer = layer_for(args.weights, args.task, [option['id'] for option in catalog])
81
100
 
82
101
  corpus = json.loads(Path(args.holdout).read_text(encoding='utf-8'))
83
102
  cases = [case for case in corpus.get('cases', []) if case.get('split') == 'holdout']
@@ -95,8 +114,10 @@ def main():
95
114
  if not isinstance(request.get('context'), str):
96
115
  raise ValueError('holdout case has no request.context')
97
116
  examples.append(ChoiceExample(context=request['context'], options=options, label=0))
98
- scores = model(collator(examples)).sigmoid().tolist()
99
- for case, values in zip(batch, scores, strict=True):
117
+ logits = model(collator(examples)).float().tolist()
118
+ for case, values in zip(batch, logits, strict=True):
119
+ values = layer[0].apply_layer(layer[1], values, case['request']['context']) if layer else \
120
+ [1.0 / (1.0 + math.exp(-max(-80.0, min(80.0, value)))) for value in values]
100
121
  gold = ('invalid' if case['gold'] is None else 'actionable') if args.task == 'validity' else case['gold']
101
122
  rows.append({'id': case['id'], 'gold': gold, 'scores': {option['id']: value for option, value in zip(catalog, values, strict=True)}})
102
123
 
@@ -1,11 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('node:crypto');
3
4
  const fs = require('node:fs');
4
5
  const path = require('node:path');
5
6
  const { spawn, spawnSync } = require('node:child_process');
6
7
  const { REPO, dataPath, writeJson, runNode, assertPrivateDataDir } = require('./common');
7
8
 
8
9
  const TASKS = ['validity', 'intent', 'tier'];
10
+ const HOLDOUTS = { validity: 'system-one-holdout.json', tier: 'system-one-holdout.json', intent: 'system-one-intent-holdout.json' };
9
11
 
10
12
  function processTreeRssMb(rootPid) {
11
13
  if (process.platform === 'win32') {
@@ -91,14 +93,238 @@ function runGuarded(command, args, { maxRssMb = 6144, threads = 4, pollMs = 500,
91
93
  });
92
94
  }
93
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
+
94
108
  function pythonExecutable() {
95
109
  return process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
96
110
  }
97
111
 
112
+ function sha256(file) {
113
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
114
+ }
115
+
116
+ function reportLabelFile(task, target) {
117
+ return task === 'intent' && target === 'scores' ? 'labels-intent-scores.jsonl'
118
+ : task === 'intent' ? 'labels-intent.jsonl' : 'labels.jsonl';
119
+ }
120
+
121
+ function readTrainerReport(runDir, task) {
122
+ try {
123
+ const report = JSON.parse(fs.readFileSync(path.join(runDir, 'train-report.json'), 'utf8'));
124
+ const datasets = report.datasets;
125
+ return report.schemaVersion === 1 && report.task === task
126
+ && (report.target === 'label' || (task === 'intent' && report.target === 'scores'))
127
+ && Array.isArray(report.catalog) && report.catalog.length > 0
128
+ && report.catalog.every(id => typeof id === 'string' && id.length > 0)
129
+ && new Set(report.catalog).size === report.catalog.length
130
+ && Number.isInteger(report.counts?.validation) && report.counts.validation > 0
131
+ && Number.isInteger(report.counts?.train) && report.counts.train > 0
132
+ && datasets && typeof datasets === 'object' && !Array.isArray(datasets)
133
+ && Object.keys(datasets).sort().join(',') === ['prompts.jsonl', reportLabelFile(task, report.target)].sort().join(',')
134
+ && Object.values(datasets).every(hash => /^[a-f0-9]{64}$/.test(hash))
135
+ && report.config && typeof report.config === 'object' && !Array.isArray(report.config)
136
+ && Number.isInteger(report.bestEpoch) && report.bestEpoch > 0
137
+ && Array.isArray(report.history) && typeof report.device === 'string' && typeof report.torch === 'string'
138
+ ? report : null;
139
+ } catch { return null; }
140
+ }
141
+
142
+ function hasTrainerReport(runDir, task) {
143
+ return Boolean(readTrainerReport(runDir, task));
144
+ }
145
+
146
+ function successfulGuard(runDir) {
147
+ try {
148
+ const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
149
+ if (guard.schemaVersion !== 1 || guard.exitCode !== 0 || guard.killedForLimit || guard.monitorFailed) return false;
150
+ if (guard.remote === undefined) return Number.isFinite(guard.peakRssMb) && guard.peakRssMb >= 0
151
+ && Number.isFinite(guard.maxRssMb) && guard.maxRssMb > 0 && Number.isInteger(guard.threads) && guard.threads > 0;
152
+ const remote = guard.remote;
153
+ if (remote?.provider !== 'colab' || typeof remote.session !== 'string' || !remote.session.length
154
+ || !(remote.gpu === null || ['T4', 'L4', 'A100'].includes(remote.gpu))
155
+ || typeof remote.invocationId !== 'string' || !/^[a-f0-9-]{36}$/.test(remote.invocationId)
156
+ || !/^[a-f0-9]{64}$/.test(remote.manifestSha256 || '') || !remote.files || typeof remote.files !== 'object') return false;
157
+ const required = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
158
+ return required.every(file => /^[a-f0-9]{64}$/.test(remote.files[file] || '')
159
+ && fs.existsSync(path.join(runDir, file)) && remote.files[file] === sha256(path.join(runDir, file)));
160
+ } catch { return false; }
161
+ }
162
+
163
+ function validateFitStage({ runDir, task, dataDir, checkpointPath, checkpointConfigPath }) {
164
+ const report = readTrainerReport(runDir, task);
165
+ if (!report) throw new Error(`${task} trainer report is missing or invalid`);
166
+ if (!successfulGuard(runDir)) {
167
+ let detail = 'missing, failed, or lacks verified remote provenance';
168
+ try {
169
+ const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
170
+ if (guard.remote?.files) detail = `remote file hash mismatch: ${Object.entries(guard.remote.files)
171
+ .filter(([name, value]) => !fs.existsSync(path.join(runDir, name)) || sha256(path.join(runDir, name)) !== value)
172
+ .map(([name]) => name).join(', ')}`;
173
+ } catch { /* retain generic guard diagnostic */ }
174
+ throw new Error(`${task} training guard is ${detail}`);
175
+ }
176
+ const files = Object.fromEntries(Object.entries(report.datasets).map(([name, expected]) => {
177
+ const file = dataDir && path.join(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1', name);
178
+ if (file && (!fs.existsSync(file) || sha256(file) !== expected)) throw new Error(`${task} trainer dataset provenance is stale`);
179
+ return [name, expected];
180
+ }));
181
+ const outcomePath = path.join(runDir, 'layer-outcome.json');
182
+ const calibrationPath = path.join(runDir, 'calibration.json');
183
+ let outcome;
184
+ let calibration;
185
+ try {
186
+ outcome = JSON.parse(fs.readFileSync(outcomePath, 'utf8'));
187
+ calibration = JSON.parse(fs.readFileSync(calibrationPath, 'utf8'));
188
+ } catch { throw new Error(`${task} fit outcome or calibration is missing, invalid, or stale`); }
189
+ const checkpoint = checkpointPath || path.join(runDir, 'harness-routing-v1.safetensors');
190
+ const checkpointConfig = checkpointConfigPath || path.join(runDir, 'harness-routing-v1.json');
191
+ const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
192
+ const scorePath = path.join(runDir, input);
193
+ const holdoutPath = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
194
+ const hash = file => fs.existsSync(file) ? sha256(file) : null;
195
+ if (outcome.schemaVersion !== 1 || outcome.task !== task || !['layer', 'keep-base'].includes(outcome.outcome)
196
+ || JSON.stringify(outcome.datasetSha256) !== JSON.stringify(files)
197
+ || outcome.trainerReportSha256 !== hash(path.join(runDir, 'train-report.json'))
198
+ || outcome.holdoutSha256 !== hash(holdoutPath)
199
+ || outcome.checkpointSha256 !== hash(checkpoint)
200
+ || !/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
201
+ || outcome.checkpointConfigSha256 !== hash(checkpointConfig)
202
+ || outcome.calibrationInput !== input || outcome.calibrationInputSha256 !== hash(scorePath)
203
+ || outcome.calibrationSha256 !== hash(calibrationPath)) {
204
+ throw new Error(`${task} fit outcome, checkpoint, calibration, or selected score file is stale`);
205
+ }
206
+ if (!calibration.thresholds || Object.keys(calibration.thresholds).sort().join('\0') !== [...report.catalog].sort().join('\0')
207
+ || Object.values(calibration.thresholds).some(value => value !== null && (!Number.isFinite(value) || value < 0 || value > 1))) {
208
+ throw new Error(`${task} calibration has no finite per-option thresholds matching the trainer catalog`);
209
+ }
210
+ let rows;
211
+ try { rows = fs.readFileSync(scorePath, 'utf8').trim().split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line)); }
212
+ catch { throw new Error(`${task} selected score file is invalid`); }
213
+ const ids = rows.map(row => row.id);
214
+ if (!rows.length || ids.some(id => typeof id !== 'string' || !id) || new Set(ids).size !== ids.length
215
+ || !Array.isArray(outcome.validationIds) || outcome.validationIds.length !== ids.length
216
+ || [...outcome.validationIds].sort().join('\0') !== [...ids].sort().join('\0')
217
+ || rows.some(row => typeof row.gold !== 'string' || !row.scores
218
+ || Object.keys(row.scores).sort().join('\0') !== [...report.catalog].sort().join('\0')
219
+ || Object.values(row.scores).some(value => !Number.isFinite(value)))) {
220
+ throw new Error(`${task} selected score file does not match the fit outcome`);
221
+ }
222
+ if (outcome.outcome === 'layer') {
223
+ const layerPath = path.join(runDir, 'layer.json');
224
+ if (outcome.oofScoreSpace !== 'h-transform-v2' || outcome.layerSha256 !== hash(layerPath))
225
+ throw new Error(`${task} layered fit is stale or lacks corrected OOF score-space evidence`);
226
+ const layer = JSON.parse(fs.readFileSync(layerPath, 'utf8'));
227
+ if (layer.stage !== task || layer.kind !== 'echl-h' || layer.fit?.oof !== true
228
+ || layer.options?.join('\0') !== report.catalog.join('\0')) throw new Error(`${task} layer does not match fit outcome`);
229
+ } else if (outcome.oofScoreSpace !== null || fs.existsSync(path.join(runDir, 'layer.json'))
230
+ || outcome.calibrationInput !== 'val-scores.jsonl') {
231
+ throw new Error(`${task} keep-base fit outcome is inconsistent`);
232
+ }
233
+ return { report, outcome, calibration, scorePath };
234
+ }
235
+
236
+ function fitLayerStage({ dataDir, runDir, task, run, maxRssMb = 6144, threads = 4, pollMs = 500, rssReader }) {
237
+ const fitter = path.join(REPO, 'scripts', 'system-one-fit-layer.py');
238
+ const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
239
+ const bundle = dataPath(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
240
+ const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
241
+ const sha256 = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
242
+ const outcomeFile = path.join(runDir, 'layer-outcome.json');
243
+ if (fs.existsSync(outcomeFile)) {
244
+ try {
245
+ const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
246
+ const report = readTrainerReport(runDir, task);
247
+ if (!report) throw new Error('invalid trainer report');
248
+ const labelFile = reportLabelFile(task, report.target);
249
+ const datasets = Object.fromEntries(['prompts.jsonl', labelFile].map(file => [file, sha256(path.join(bundle, file))]));
250
+ const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
251
+ const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
252
+ const layerPath = path.join(runDir, 'layer.json');
253
+ const current = outcome.schemaVersion === 1 && outcome.task === task && ['layer', 'keep-base'].includes(outcome.outcome)
254
+ && (outcome.outcome === 'layer' ? outcome.oofScoreSpace === 'h-transform-v2' : outcome.oofScoreSpace === null)
255
+ && JSON.stringify(outcome.datasetSha256) === JSON.stringify(datasets)
256
+ && outcome.trainerReportSha256 === sha256(path.join(runDir, 'train-report.json'))
257
+ && outcome.holdoutSha256 === sha256(holdout)
258
+ && outcome.checkpointSha256 === sha256(path.join(runDir, 'harness-routing-v1.safetensors'))
259
+ && /^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
260
+ && outcome.checkpointConfigSha256 === sha256(path.join(runDir, 'harness-routing-v1.json'))
261
+ && outcome.calibrationInput === input && outcome.calibrationInputSha256 === sha256(path.join(runDir, input))
262
+ && outcome.calibrationSha256 === sha256(path.join(runDir, 'calibration.json'))
263
+ && (outcome.outcome === 'layer' ? fs.existsSync(layerPath) && outcome.layerSha256 === sha256(layerPath)
264
+ : !fs.existsSync(layerPath));
265
+ if (current) {
266
+ validateFitStage({ runDir, task, dataDir });
267
+ return outcome;
268
+ }
269
+ } catch { /* Refit incomplete or stale stage artifacts below. */ }
270
+ }
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);
323
+ }
324
+
98
325
  async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run = runGuarded }) {
99
326
  const privateDir = assertPrivateDataDir(dataDir);
100
327
  const trainer = path.join(REPO, 'scripts', 'system-one-train.py');
101
- const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
102
328
  const outputs = [];
103
329
  let trained = 0;
104
330
  let skipped = 0;
@@ -107,30 +333,38 @@ async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run
107
333
  const source = dataPath(privateDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
108
334
  const out = dataPath(privateDir, 'training', 'runs', version, task);
109
335
  fs.mkdirSync(out, { recursive: true, mode: 0o700 });
110
- const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json', 'calibration.json', 'resource-guard.json'];
336
+ const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
111
337
  const guardFile = path.join(out, 'resource-guard.json');
338
+ let trainedThisTask = false;
112
339
  if (requiredFiles.every(file => fs.existsSync(path.join(out, file)))) {
113
- const priorGuard = JSON.parse(fs.readFileSync(guardFile, 'utf8'));
114
- if (priorGuard.exitCode === 0 && !priorGuard.killedForLimit && !priorGuard.monitorFailed) {
340
+ if (successfulGuard(out) && hasTrainerReport(out, task)) {
115
341
  skipped++;
116
- outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
117
- continue;
118
- }
342
+ } else trainedThisTask = true;
343
+ } else trainedThisTask = true;
344
+ if (trainedThisTask) {
345
+ const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
346
+ threads, maxRssMb,
347
+ });
348
+ const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
349
+ writeJson(path.join(out, 'resource-guard.json'), guard);
350
+ if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
351
+ if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
352
+ if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
353
+ if (!hasTrainerReport(out, task)) throw new Error(`training ${task} produced a missing or invalid trainer report`);
354
+ trained++;
355
+ }
356
+ if (!hasTrainerReport(out, task)) throw new Error(`training ${task} has no valid trainer report`);
357
+ const outcome = await fitLayerStage({ dataDir: privateDir, runDir: out, task, run, threads, maxRssMb });
358
+ validateFitStage({ runDir: out, task, dataDir: privateDir });
359
+ if (fs.existsSync(guardFile)) outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
360
+ if (outcome) {
361
+ outputs.push(`training/runs/${version}/${task}/calibration.json`, `training/runs/${version}/${task}/layer-outcome.json`);
362
+ if (outcome.outcome === 'layer') outputs.push(`training/runs/${version}/${task}/layer.json`,
363
+ `training/runs/${version}/${task}/val-scores-layered.jsonl`);
119
364
  }
120
- const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
121
- threads, maxRssMb,
122
- });
123
- const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
124
- writeJson(path.join(out, 'resource-guard.json'), guard);
125
- if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
126
- if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
127
- if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
128
- runNode(calibrator, [path.join(out, 'val-scores.jsonl'), path.join(out, 'calibration.json'), '--task', task,
129
- '--catalog', path.join(out, 'train-report.json')]);
130
- trained++;
131
- outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
132
365
  }
133
366
  return { trained, skipped, threads, maxRssMb, outputs };
134
367
  }
135
368
 
136
- module.exports = { runGuarded, processTreeRssMb, trainCycle, TASKS };
369
+ module.exports = { runGuarded, processTreeRssMb, trainCycle, fitLayerStage, hasTrainerReport, successfulGuard,
370
+ validateFitStage, TASKS, HOLDOUTS };