harness-everything 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/release.yml +16 -5
  4. package/CHANGELOG.md +25 -0
  5. package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
  6. package/ci/mechanism-2x-release-automation.test.js +17 -0
  7. package/ci/mechanism-system-one-colab.test.js +83 -5
  8. package/ci/mechanism-system-one-contract.test.js +30 -0
  9. package/ci/mechanism-system-one-curves.test.js +85 -0
  10. package/ci/mechanism-system-one-cycle.test.js +344 -34
  11. package/ci/mechanism-system-one-install.test.js +47 -0
  12. package/ci/mechanism-system-one-provider.test.js +2 -0
  13. package/ci/mechanism-system-one-resident.test.js +69 -0
  14. package/ci/system-one-adapter-test.py +86 -0
  15. package/ci/system-one-fit-layer-test.py +371 -0
  16. package/ci/system-one-layer-test.py +122 -0
  17. package/harness-everything/SKILL.md +1 -1
  18. package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  19. package/harness-everything/scripts/system-one/install.js +10 -0
  20. package/harness-everything/scripts/system-one/layer.py +178 -0
  21. package/harness-everything/scripts/system-one/manifest.js +8 -1
  22. package/harness-everything/scripts/system-one/provider.js +12 -2
  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/cua_adapter.py +36 -1
  30. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
  31. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +178 -0
  32. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
  33. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
  34. package/sbom.cdx.json +7 -7
  35. package/scripts/system-one-colab.js +6 -4
  36. package/scripts/system-one-curves.js +52 -8
  37. package/scripts/system-one-cycle/evaluate.js +56 -5
  38. package/scripts/system-one-cycle/package.js +61 -3
  39. package/scripts/system-one-cycle/score.py +23 -2
  40. package/scripts/system-one-cycle/train.js +212 -20
  41. package/scripts/system-one-fit-layer.py +369 -0
@@ -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') {
@@ -95,10 +97,192 @@ function pythonExecutable() {
95
97
  return process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
96
98
  }
97
99
 
100
+ function sha256(file) {
101
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
102
+ }
103
+
104
+ function reportLabelFile(task, target) {
105
+ return task === 'intent' && target === 'scores' ? 'labels-intent-scores.jsonl'
106
+ : task === 'intent' ? 'labels-intent.jsonl' : 'labels.jsonl';
107
+ }
108
+
109
+ function readTrainerReport(runDir, task) {
110
+ try {
111
+ const report = JSON.parse(fs.readFileSync(path.join(runDir, 'train-report.json'), 'utf8'));
112
+ const datasets = report.datasets;
113
+ return report.schemaVersion === 1 && report.task === task
114
+ && (report.target === 'label' || (task === 'intent' && report.target === 'scores'))
115
+ && Array.isArray(report.catalog) && report.catalog.length > 0
116
+ && report.catalog.every(id => typeof id === 'string' && id.length > 0)
117
+ && new Set(report.catalog).size === report.catalog.length
118
+ && Number.isInteger(report.counts?.validation) && report.counts.validation > 0
119
+ && Number.isInteger(report.counts?.train) && report.counts.train > 0
120
+ && datasets && typeof datasets === 'object' && !Array.isArray(datasets)
121
+ && Object.keys(datasets).sort().join(',') === ['prompts.jsonl', reportLabelFile(task, report.target)].sort().join(',')
122
+ && Object.values(datasets).every(hash => /^[a-f0-9]{64}$/.test(hash))
123
+ && report.config && typeof report.config === 'object' && !Array.isArray(report.config)
124
+ && Number.isInteger(report.bestEpoch) && report.bestEpoch > 0
125
+ && Array.isArray(report.history) && typeof report.device === 'string' && typeof report.torch === 'string'
126
+ ? report : null;
127
+ } catch { return null; }
128
+ }
129
+
130
+ function hasTrainerReport(runDir, task) {
131
+ return Boolean(readTrainerReport(runDir, task));
132
+ }
133
+
134
+ function successfulGuard(runDir) {
135
+ try {
136
+ const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
137
+ if (guard.schemaVersion !== 1 || guard.exitCode !== 0 || guard.killedForLimit || guard.monitorFailed) return false;
138
+ if (guard.remote === undefined) return Number.isFinite(guard.peakRssMb) && guard.peakRssMb >= 0
139
+ && Number.isFinite(guard.maxRssMb) && guard.maxRssMb > 0 && Number.isInteger(guard.threads) && guard.threads > 0;
140
+ const remote = guard.remote;
141
+ if (remote?.provider !== 'colab' || typeof remote.session !== 'string' || !remote.session.length
142
+ || !(remote.gpu === null || ['T4', 'L4', 'A100'].includes(remote.gpu))
143
+ || typeof remote.invocationId !== 'string' || !/^[a-f0-9-]{36}$/.test(remote.invocationId)
144
+ || !/^[a-f0-9]{64}$/.test(remote.manifestSha256 || '') || !remote.files || typeof remote.files !== 'object') return false;
145
+ const required = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
146
+ return required.every(file => /^[a-f0-9]{64}$/.test(remote.files[file] || '')
147
+ && fs.existsSync(path.join(runDir, file)) && remote.files[file] === sha256(path.join(runDir, file)));
148
+ } catch { return false; }
149
+ }
150
+
151
+ function validateFitStage({ runDir, task, dataDir, checkpointPath, checkpointConfigPath }) {
152
+ const report = readTrainerReport(runDir, task);
153
+ if (!report) throw new Error(`${task} trainer report is missing or invalid`);
154
+ if (!successfulGuard(runDir)) {
155
+ let detail = 'missing, failed, or lacks verified remote provenance';
156
+ try {
157
+ const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
158
+ if (guard.remote?.files) detail = `remote file hash mismatch: ${Object.entries(guard.remote.files)
159
+ .filter(([name, value]) => !fs.existsSync(path.join(runDir, name)) || sha256(path.join(runDir, name)) !== value)
160
+ .map(([name]) => name).join(', ')}`;
161
+ } catch { /* retain generic guard diagnostic */ }
162
+ throw new Error(`${task} training guard is ${detail}`);
163
+ }
164
+ const files = Object.fromEntries(Object.entries(report.datasets).map(([name, expected]) => {
165
+ const file = dataDir && path.join(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1', name);
166
+ if (file && (!fs.existsSync(file) || sha256(file) !== expected)) throw new Error(`${task} trainer dataset provenance is stale`);
167
+ return [name, expected];
168
+ }));
169
+ const outcomePath = path.join(runDir, 'layer-outcome.json');
170
+ const calibrationPath = path.join(runDir, 'calibration.json');
171
+ let outcome;
172
+ let calibration;
173
+ try {
174
+ outcome = JSON.parse(fs.readFileSync(outcomePath, 'utf8'));
175
+ calibration = JSON.parse(fs.readFileSync(calibrationPath, 'utf8'));
176
+ } catch { throw new Error(`${task} fit outcome or calibration is missing or invalid`); }
177
+ const checkpoint = checkpointPath || path.join(runDir, 'harness-routing-v1.safetensors');
178
+ const checkpointConfig = checkpointConfigPath || path.join(runDir, 'harness-routing-v1.json');
179
+ const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
180
+ const scorePath = path.join(runDir, input);
181
+ const holdoutPath = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
182
+ const hash = file => fs.existsSync(file) ? sha256(file) : null;
183
+ if (outcome.schemaVersion !== 1 || outcome.task !== task || !['layer', 'keep-base'].includes(outcome.outcome)
184
+ || JSON.stringify(outcome.datasetSha256) !== JSON.stringify(files)
185
+ || outcome.trainerReportSha256 !== hash(path.join(runDir, 'train-report.json'))
186
+ || outcome.holdoutSha256 !== hash(holdoutPath)
187
+ || outcome.checkpointSha256 !== hash(checkpoint)
188
+ || !/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
189
+ || outcome.checkpointConfigSha256 !== hash(checkpointConfig)
190
+ || outcome.calibrationInput !== input || outcome.calibrationInputSha256 !== hash(scorePath)
191
+ || outcome.calibrationSha256 !== hash(calibrationPath)) {
192
+ throw new Error(`${task} fit outcome, checkpoint, calibration, or selected score file is stale`);
193
+ }
194
+ if (!calibration.thresholds || Object.keys(calibration.thresholds).sort().join('\0') !== [...report.catalog].sort().join('\0')
195
+ || Object.values(calibration.thresholds).some(value => value !== null && (!Number.isFinite(value) || value < 0 || value > 1))) {
196
+ throw new Error(`${task} calibration has no finite per-option thresholds matching the trainer catalog`);
197
+ }
198
+ let rows;
199
+ try { rows = fs.readFileSync(scorePath, 'utf8').trim().split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line)); }
200
+ catch { throw new Error(`${task} selected score file is invalid`); }
201
+ const ids = rows.map(row => row.id);
202
+ if (!rows.length || ids.some(id => typeof id !== 'string' || !id) || new Set(ids).size !== ids.length
203
+ || !Array.isArray(outcome.validationIds) || outcome.validationIds.length !== ids.length
204
+ || [...outcome.validationIds].sort().join('\0') !== [...ids].sort().join('\0')
205
+ || rows.some(row => typeof row.gold !== 'string' || !row.scores
206
+ || Object.keys(row.scores).sort().join('\0') !== [...report.catalog].sort().join('\0')
207
+ || Object.values(row.scores).some(value => !Number.isFinite(value)))) {
208
+ throw new Error(`${task} selected score file does not match the fit outcome`);
209
+ }
210
+ if (outcome.outcome === 'layer') {
211
+ const layerPath = path.join(runDir, 'layer.json');
212
+ if (outcome.oofScoreSpace !== 'h-transform-v2' || outcome.layerSha256 !== hash(layerPath))
213
+ throw new Error(`${task} layered fit is stale or lacks corrected OOF score-space evidence`);
214
+ const layer = JSON.parse(fs.readFileSync(layerPath, 'utf8'));
215
+ if (layer.stage !== task || layer.kind !== 'echl-h' || layer.fit?.oof !== true
216
+ || layer.options?.join('\0') !== report.catalog.join('\0')) throw new Error(`${task} layer does not match fit outcome`);
217
+ } else if (outcome.oofScoreSpace !== null || fs.existsSync(path.join(runDir, 'layer.json'))
218
+ || outcome.calibrationInput !== 'val-scores.jsonl') {
219
+ throw new Error(`${task} keep-base fit outcome is inconsistent`);
220
+ }
221
+ return { report, outcome, calibration, scorePath };
222
+ }
223
+
224
+ function fitLayerStage({ dataDir, runDir, task }) {
225
+ const fitter = path.join(REPO, 'scripts', 'system-one-fit-layer.py');
226
+ const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
227
+ const bundle = dataPath(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
228
+ const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
229
+ const sha256 = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
230
+ const outcomeFile = path.join(runDir, 'layer-outcome.json');
231
+ if (fs.existsSync(outcomeFile)) {
232
+ try {
233
+ const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
234
+ const report = readTrainerReport(runDir, task);
235
+ if (!report) throw new Error('invalid trainer report');
236
+ const labelFile = reportLabelFile(task, report.target);
237
+ const datasets = Object.fromEntries(['prompts.jsonl', labelFile].map(file => [file, sha256(path.join(bundle, file))]));
238
+ const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
239
+ const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
240
+ const layerPath = path.join(runDir, 'layer.json');
241
+ const current = outcome.schemaVersion === 1 && outcome.task === task && ['layer', 'keep-base'].includes(outcome.outcome)
242
+ && (outcome.outcome === 'layer' ? outcome.oofScoreSpace === 'h-transform-v2' : outcome.oofScoreSpace === null)
243
+ && JSON.stringify(outcome.datasetSha256) === JSON.stringify(datasets)
244
+ && outcome.trainerReportSha256 === sha256(path.join(runDir, 'train-report.json'))
245
+ && outcome.holdoutSha256 === sha256(holdout)
246
+ && outcome.checkpointSha256 === sha256(path.join(runDir, 'harness-routing-v1.safetensors'))
247
+ && /^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
248
+ && outcome.checkpointConfigSha256 === sha256(path.join(runDir, 'harness-routing-v1.json'))
249
+ && outcome.calibrationInput === input && outcome.calibrationInputSha256 === sha256(path.join(runDir, input))
250
+ && outcome.calibrationSha256 === sha256(path.join(runDir, 'calibration.json'))
251
+ && (outcome.outcome === 'layer' ? fs.existsSync(layerPath) && outcome.layerSha256 === sha256(layerPath)
252
+ : !fs.existsSync(layerPath));
253
+ if (current) {
254
+ validateFitStage({ runDir, task, dataDir });
255
+ return outcome;
256
+ }
257
+ } catch { /* Refit incomplete or stale stage artifacts below. */ }
258
+ }
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;
281
+ }
282
+
98
283
  async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run = runGuarded }) {
99
284
  const privateDir = assertPrivateDataDir(dataDir);
100
285
  const trainer = path.join(REPO, 'scripts', 'system-one-train.py');
101
- const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
102
286
  const outputs = [];
103
287
  let trained = 0;
104
288
  let skipped = 0;
@@ -107,30 +291,38 @@ async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run
107
291
  const source = dataPath(privateDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
108
292
  const out = dataPath(privateDir, 'training', 'runs', version, task);
109
293
  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'];
294
+ const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
111
295
  const guardFile = path.join(out, 'resource-guard.json');
296
+ let trainedThisTask = false;
112
297
  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) {
298
+ if (successfulGuard(out) && hasTrainerReport(out, task)) {
115
299
  skipped++;
116
- outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
117
- continue;
118
- }
300
+ } else trainedThisTask = true;
301
+ } else trainedThisTask = true;
302
+ if (trainedThisTask) {
303
+ const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
304
+ threads, maxRssMb,
305
+ });
306
+ const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
307
+ writeJson(path.join(out, 'resource-guard.json'), guard);
308
+ if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
309
+ if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
310
+ if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
311
+ if (!hasTrainerReport(out, task)) throw new Error(`training ${task} produced a missing or invalid trainer report`);
312
+ trained++;
313
+ }
314
+ if (!hasTrainerReport(out, task)) throw new Error(`training ${task} has no valid trainer report`);
315
+ const outcome = fitLayerStage({ dataDir: privateDir, runDir: out, task });
316
+ validateFitStage({ runDir: out, task, dataDir: privateDir });
317
+ if (fs.existsSync(guardFile)) outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
318
+ if (outcome) {
319
+ outputs.push(`training/runs/${version}/${task}/calibration.json`, `training/runs/${version}/${task}/layer-outcome.json`);
320
+ if (outcome.outcome === 'layer') outputs.push(`training/runs/${version}/${task}/layer.json`,
321
+ `training/runs/${version}/${task}/val-scores-layered.jsonl`);
119
322
  }
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
323
  }
133
324
  return { trained, skipped, threads, maxRssMb, outputs };
134
325
  }
135
326
 
136
- module.exports = { runGuarded, processTreeRssMb, trainCycle, TASKS };
327
+ module.exports = { runGuarded, processTreeRssMb, trainCycle, fitLayerStage, hasTrainerReport, successfulGuard,
328
+ validateFitStage, TASKS, HOLDOUTS };