harness-everything 1.3.2 → 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 (46) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/release.yml +23 -6
  4. package/CHANGELOG.md +42 -0
  5. package/RELEASING.md +2 -0
  6. package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
  7. package/ci/mechanism-2x-release-automation.test.js +17 -0
  8. package/ci/mechanism-system-one-colab.test.js +528 -0
  9. package/ci/mechanism-system-one-contract.test.js +30 -0
  10. package/ci/mechanism-system-one-curves.test.js +85 -0
  11. package/ci/mechanism-system-one-cycle.test.js +344 -34
  12. package/ci/mechanism-system-one-install.test.js +47 -0
  13. package/ci/mechanism-system-one-provider.test.js +2 -0
  14. package/ci/mechanism-system-one-resident.test.js +69 -0
  15. package/ci/system-one-adapter-test.py +86 -0
  16. package/ci/system-one-fit-layer-test.py +371 -0
  17. package/ci/system-one-layer-test.py +122 -0
  18. package/ci/system-one-train-test.py +26 -0
  19. package/docs/system-one-cycle.md +10 -0
  20. package/docs/system-one-training.md +3 -1
  21. package/harness-everything/SKILL.md +1 -1
  22. package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  23. package/harness-everything/scripts/system-one/install.js +10 -0
  24. package/harness-everything/scripts/system-one/layer.py +178 -0
  25. package/harness-everything/scripts/system-one/manifest.js +8 -1
  26. package/harness-everything/scripts/system-one/provider.js +12 -2
  27. package/opencode-plugin/plugin.json +1 -1
  28. package/package.json +1 -1
  29. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  30. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  31. package/plugins/harness-everything/plugin.json +1 -1
  32. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  33. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  34. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
  35. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +178 -0
  36. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
  37. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
  38. package/sbom.cdx.json +7 -7
  39. package/scripts/system-one-colab.js +240 -0
  40. package/scripts/system-one-curves.js +52 -8
  41. package/scripts/system-one-cycle/evaluate.js +56 -5
  42. package/scripts/system-one-cycle/package.js +61 -3
  43. package/scripts/system-one-cycle/score.py +23 -2
  44. package/scripts/system-one-cycle/train.js +212 -20
  45. package/scripts/system-one-fit-layer.py +369 -0
  46. package/scripts/system-one-train.py +36 -9
@@ -15,6 +15,19 @@ import tempfile
15
15
  import threading
16
16
  import time
17
17
 
18
+ import importlib.util
19
+
20
+ # Load the sibling layer module by path: callers load this adapter by file location, so its directory is not on sys.path.
21
+ _layer_spec = importlib.util.spec_from_file_location('harness_system_one_layer', Path(__file__).resolve().with_name('layer.py'))
22
+ _layer = importlib.util.module_from_spec(_layer_spec)
23
+ _write_bytecode = sys.dont_write_bytecode
24
+ sys.dont_write_bytecode = True # never leave __pycache__ in the shipped tree (installer stale-tree check)
25
+ try:
26
+ _layer_spec.loader.exec_module(_layer)
27
+ finally:
28
+ sys.dont_write_bytecode = _write_bytecode
29
+ apply_layer, load_layer = _layer.apply_layer, _layer.load_layer
30
+
18
31
  ACTIVE_STAGES = ('validity', 'intent', 'tier')
19
32
  LEGACY_ROUTING_METADATA = frozenset(('domain', 'bestEpoch', 'validation', 'datasets', 'seed', 'catalog'))
20
33
 
@@ -97,6 +110,12 @@ def load_scorer(weights, manifest):
97
110
  example = ChoiceExample(context=request['context'], options=tuple(o['text'] for o in request['options']), label=0)
98
111
  with torch.inference_mode():
99
112
  logits = model(collator([example]))
113
+ if 'layerPath' in manifest:
114
+ raw = logits[0].tolist()
115
+ fitted = manifest.get('_loadedLayer')
116
+ if fitted is None:
117
+ fitted = load_layer(manifest['layerPath'], manifest['layerSha256'], task, manifest['options'])
118
+ return apply_layer(fitted, raw, request['context'])
100
119
  return (logits.softmax(-1) if semantics == 'categorical' else logits.sigmoid())[0].tolist()
101
120
  score.score_semantics = semantics
102
121
  score.training_task = task
@@ -147,6 +166,8 @@ def _active_fingerprint(version, directory, scorers):
147
166
  for stage in ACTIVE_STAGES:
148
167
  entry = scorers[stage]
149
168
  values.extend((stage, entry['sha256'], entry['manifest']['configSha256']))
169
+ if entry.get('layerSha256'):
170
+ values.append(entry['layerSha256'])
150
171
  return hashlib.sha256('\0'.join(values).encode('utf-8')).hexdigest()
151
172
 
152
173
 
@@ -154,6 +175,8 @@ def _active_stamp(bundle):
154
175
  paths = [Path(bundle['activePath']), Path(bundle['manifestPath'])]
155
176
  for stage in ACTIVE_STAGES:
156
177
  paths.extend((bundle['scorers'][stage]['weights'], bundle['scorers'][stage]['configPath']))
178
+ if bundle['scorers'][stage].get('layerPath'):
179
+ paths.append(bundle['scorers'][stage]['layerPath'])
157
180
  return [(file.stat().st_size, file.stat().st_mtime_ns) for file in paths]
158
181
 
159
182
 
@@ -195,6 +218,14 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
195
218
  config_path = _active_artifact(directory, entry['config'], '.json')
196
219
  if hashlib.sha256(weights.read_bytes()).hexdigest() != entry['sha256']:
197
220
  raise ValueError('artifact-hash')
221
+ layer_path = None
222
+ if entry.get('layer') is not None:
223
+ layer_path = _active_artifact(directory, entry['layer'], '.json')
224
+ if not entry['layer'].endswith('.layer.json'):
225
+ raise ValueError('checkpoint-format')
226
+ layer_value = load_layer(layer_path, entry['layerSha256'], stage, entry['options'])
227
+ else:
228
+ layer_value = None
198
229
  stage_manifest = {
199
230
  'checkpoint': str(weights),
200
231
  'config': str(config_path),
@@ -204,11 +235,15 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
204
235
  'revision': pointer['version'],
205
236
  'domain': 'harness-routing-v1',
206
237
  }
238
+ if layer_path is not None:
239
+ stage_manifest.update({'layerPath': str(layer_path), 'layerSha256': entry['layerSha256'],
240
+ 'options': entry['options'], '_loadedLayer': layer_value})
207
241
  score, config = loader(weights, stage_manifest)
208
242
  if scorer_loader is None and (score.score_semantics != 'independent' or score.training_task != stage):
209
243
  raise ValueError('active-stage')
210
244
  scorers[stage] = {**entry, 'manifest': stage_manifest, 'score': score, 'config': config,
211
- 'weights': weights, 'configPath': config_path}
245
+ 'weights': weights, 'configPath': config_path,
246
+ **({'layerPath': layer_path, 'layer': layer_value} if layer_path is not None else {})}
212
247
  fingerprint = _active_fingerprint(pointer['version'], pointer['dir'], scorers)
213
248
  if expected_fingerprint is not None and fingerprint != expected_fingerprint:
214
249
  raise ValueError('active-changed')
@@ -164,6 +164,14 @@ function readCheckpoint(dir, version) {
164
164
  const config = resolveManifestFile(root, record.config);
165
165
  if (hash(fs.readFileSync(weights.path)) !== record.sha256) throw new Error(`checkpoint-hash-mismatch: ${stage}`);
166
166
  files.set(weights.relative, weights); files.set(config.relative, config);
167
+ if (record.layer !== undefined) {
168
+ const layer = resolveManifestFile(root, record.layer);
169
+ if (!record.layer.endsWith('.layer.json') || fs.statSync(layer.path).size > 32 * 1024 * 1024) {
170
+ throw new Error('checkpoint-format');
171
+ }
172
+ if (hash(fs.readFileSync(layer.path)) !== record.layerSha256) throw new Error('artifact-hash');
173
+ files.set(layer.relative, { ...layer, private: true });
174
+ }
167
175
  }
168
176
  if (manifest.evaluation !== null) {
169
177
  const evaluation = resolveManifestFile(root, manifest.evaluation);
@@ -191,6 +199,7 @@ function installVersion(source, version, dir = defaultDir()) {
191
199
  return fs.existsSync(other) && fs.readFileSync(file.path).equals(fs.readFileSync(other));
192
200
  });
193
201
  if (!same) throw new Error(`version-conflict: ${version} is already installed with different files`);
202
+ for (const file of existing.files) if (file.private) fs.chmodSync(file.path, 0o600);
194
203
  return { version, dir: target, status: 'already-installed' };
195
204
  }
196
205
  const staging = fs.mkdtempSync(path.join(versions, `.${version}.`));
@@ -200,6 +209,7 @@ function installVersion(source, version, dir = defaultDir()) {
200
209
  const dest = path.join(staging, relative);
201
210
  fs.mkdirSync(path.dirname(dest), { recursive: true });
202
211
  fs.copyFileSync(file.path, dest, fs.constants.COPYFILE_EXCL);
212
+ if (file.private) fs.chmodSync(dest, 0o600);
203
213
  }
204
214
  fs.renameSync(staging, target);
205
215
  } catch (error) {
@@ -0,0 +1,178 @@
1
+ """Shared System One H-layer scoring primitives (stdlib only)."""
2
+ from collections import Counter
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import os
7
+ from pathlib import Path
8
+
9
+ MAX_LAYER_BYTES = 32 * 1024 * 1024
10
+ _TOP_KEYS = {'schemaVersion', 'kind', 'stage', 'options', 'temperature', 'bias',
11
+ 'alpha', 'k', 'ngrams', 'maxChars', 'index', 'fit'}
12
+
13
+
14
+ def _finite_number(value):
15
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
16
+
17
+
18
+ def _positive_int(value):
19
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
20
+
21
+
22
+ def _format_error():
23
+ raise ValueError('checkpoint-format')
24
+
25
+
26
+ def _width(stage, options):
27
+ if stage not in ('validity', 'intent', 'tier') or not isinstance(options, list) or not options:
28
+ _format_error()
29
+ return 1 if stage == 'validity' else len(options)
30
+
31
+
32
+ def grams(text, ngrams=(3, 4, 5), max_chars=2000):
33
+ """Return experiment-order L2-normalized character gram counts."""
34
+ if not isinstance(text, str):
35
+ _format_error()
36
+ # Keep insertion order identical to the experiment: n ascending, then offset ascending.
37
+ counts = Counter()
38
+ padded = ' ' + text.lower()[:max_chars] + ' '
39
+ for n in ngrams:
40
+ for i in range(len(padded) - n + 1):
41
+ counts[padded[i:i + n]] += 1
42
+ norm = math.sqrt(sum(value * value for value in counts.values())) or 1.0
43
+ return {gram: value / norm for gram, value in counts.items()}
44
+
45
+
46
+ class KnnIndex:
47
+ def __init__(self, rows, stage, k=15, ngrams=(3, 4, 5), max_chars=2000):
48
+ self.stage, self.k = stage, k
49
+ self.ngrams, self.max_chars = tuple(ngrams), max_chars
50
+ self.rows = rows
51
+ self.vectors = [grams(row['text'], self.ngrams, self.max_chars) for row in rows]
52
+ self.postings = {}
53
+ for row_id, vector in enumerate(self.vectors):
54
+ for gram, weight in vector.items():
55
+ self.postings.setdefault(gram, []).append((row_id, weight))
56
+
57
+ def _similarities(self, text):
58
+ scores = Counter()
59
+ for gram, weight in grams(text, self.ngrams, self.max_chars).items():
60
+ for row_id, other_weight in self.postings.get(gram, ()):
61
+ scores[row_id] += weight * other_weight
62
+ return scores
63
+
64
+ def maxsim(self, text):
65
+ scores = self._similarities(text)
66
+ return max(scores.values()) if scores else 0.0
67
+
68
+ def dist(self, text, width):
69
+ if not _positive_int(width):
70
+ _format_error()
71
+ result = [0.0] * width
72
+ for row_id, similarity in self._similarities(text).most_common(self.k):
73
+ target = self.rows[row_id]['target']
74
+ vector = [1 - target[0], target[0]] if self.stage == 'validity' else target
75
+ total = sum(vector) or 1.0
76
+ for i in range(width):
77
+ result[i] += similarity * vector[i] / total
78
+ total = sum(result)
79
+ return [value / total for value in result] if total else [1 / width] * width
80
+
81
+
82
+ def transform(logits, stage, temperature=1.0, bias=None):
83
+ """Scale raw model logits and reproduce ECHL probabilities."""
84
+ if stage not in ('validity', 'intent', 'tier') or not logits or any(not _finite_number(v) for v in logits):
85
+ _format_error()
86
+ if not _finite_number(temperature) or temperature <= 0 or (
87
+ bias is not None and (not isinstance(bias, list) or len(bias) != len(logits)
88
+ or any(not _finite_number(v) for v in bias))):
89
+ _format_error()
90
+ values = []
91
+ for i, value in enumerate(logits):
92
+ z = value / temperature + (bias[i] if bias is not None else 0.0)
93
+ p = 1 / (1 + math.exp(-z)) if z >= 0 else math.exp(z) / (1 + math.exp(z))
94
+ values.append(p)
95
+ if stage == 'validity':
96
+ if len(values) != 1:
97
+ _format_error()
98
+ return [1 - values[0], values[0]]
99
+ total = max(sum(values), 1e-9)
100
+ return [value / total for value in values]
101
+
102
+
103
+ def blend(q, d, alpha):
104
+ if not _finite_number(alpha) or not 0 <= alpha <= 1 or len(q) != len(d):
105
+ _format_error()
106
+ return [(1 - alpha) * base + alpha * neighbor for base, neighbor in zip(q, d)]
107
+
108
+
109
+ def _validate_layer(layer, stage, options):
110
+ width = _width(stage, options)
111
+ if (not isinstance(layer, dict) or set(layer) != _TOP_KEYS
112
+ or not isinstance(layer.get('schemaVersion'), int) or isinstance(layer['schemaVersion'], bool)
113
+ or layer['schemaVersion'] != 1 or layer.get('kind') != 'echl-h'
114
+ or layer.get('stage') != stage or layer.get('options') != options
115
+ or not _finite_number(layer.get('temperature')) or layer['temperature'] <= 0
116
+ or not _finite_number(layer.get('alpha')) or not 0 <= layer['alpha'] <= 1
117
+ or not _positive_int(layer.get('k')) or not isinstance(layer.get('ngrams'), list)
118
+ or not layer['ngrams'] or any(not _positive_int(n) for n in layer['ngrams'])
119
+ or not _positive_int(layer.get('maxChars')) or not isinstance(layer.get('index'), list)
120
+ or not isinstance(layer.get('fit'), dict)):
121
+ _format_error()
122
+ fit = layer['fit']
123
+ if (set(fit) != {'candidate', 'heldOutRows', 'nll', 'baseNll', 'oof'}
124
+ or not isinstance(fit['candidate'], str) or not fit['candidate']
125
+ or not _positive_int(fit['heldOutRows']) or not _finite_number(fit['nll'])
126
+ or not _finite_number(fit['baseNll']) or not isinstance(fit['oof'], bool)):
127
+ _format_error()
128
+ bias = layer.get('bias')
129
+ if bias is not None and (not isinstance(bias, list) or len(bias) != width
130
+ or any(not _finite_number(value) for value in bias)):
131
+ _format_error()
132
+ for row in layer['index']:
133
+ if (not isinstance(row, dict) or set(row) != {'text', 'target'}
134
+ or not isinstance(row['text'], str) or not isinstance(row['target'], list)
135
+ or len(row['target']) != width or any(not _finite_number(value) for value in row['target'])):
136
+ _format_error()
137
+ if layer['alpha'] > 0 and not layer['index']:
138
+ # An empty index is harmless; the reference returns a uniform neighbor distribution.
139
+ pass
140
+ return layer
141
+
142
+
143
+ def load_layer(path, expected_sha256, stage, options):
144
+ file = Path(path)
145
+ try:
146
+ with file.open('rb') as handle:
147
+ if os.fstat(handle.fileno()).st_size > MAX_LAYER_BYTES:
148
+ _format_error()
149
+ raw = handle.read(MAX_LAYER_BYTES + 1)
150
+ if len(raw) > MAX_LAYER_BYTES:
151
+ _format_error()
152
+ except (OSError, ValueError):
153
+ _format_error()
154
+ if hashlib.sha256(raw).hexdigest() != expected_sha256:
155
+ raise ValueError('artifact-hash')
156
+ try:
157
+ layer = json.loads(raw.decode('utf-8'))
158
+ except (UnicodeDecodeError, json.JSONDecodeError):
159
+ _format_error()
160
+ layer = _validate_layer(layer, stage, options)
161
+ if layer['alpha'] > 0: # index at load time (resident startup), never inside a request deadline
162
+ layer['_knn'] = KnnIndex(layer['index'], stage, layer['k'], layer['ngrams'], layer['maxChars'])
163
+ return layer
164
+
165
+
166
+ def apply_layer(layer, logits, text):
167
+ stage = layer['stage']
168
+ expected_width = 1 if stage == 'validity' else len(layer['options'])
169
+ if len(logits) != expected_width:
170
+ _format_error()
171
+ q = transform(logits, stage, layer['temperature'], layer['bias'])
172
+ if layer['alpha'] > 0:
173
+ # Build the inverted index once per loaded layer; rebuilding it per request costs ~1 s on a 2,000-row index.
174
+ index = layer.get('_knn')
175
+ if index is None:
176
+ index = layer['_knn'] = KnnIndex(layer['index'], stage, layer['k'], layer['ngrams'], layer['maxChars'])
177
+ q = blend(q, index.dist(text, len(q)), layer['alpha'])
178
+ return [q[1]] if stage == 'validity' else q
@@ -29,7 +29,9 @@ function validateVersionManifest(manifest, expectedVersion) {
29
29
  for (const name of STAGES) {
30
30
  const stage = manifest.stages[name];
31
31
  const fields = ['weights', 'config', 'sha256', 'options', 'thresholds'];
32
- if (!(exact(stage, fields) || exact(stage, [...fields, 'referenceOnly']))
32
+ if (!(exact(stage, fields) || exact(stage, [...fields, 'referenceOnly'])
33
+ || exact(stage, [...fields, 'layer', 'layerSha256'])
34
+ || exact(stage, [...fields, 'referenceOnly', 'layer', 'layerSha256']))
33
35
  || !safeRelative(stage.weights) || !safeRelative(stage.config) || !HASH.test(stage.sha256)
34
36
  || !Array.isArray(stage.options) || !stage.options.length
35
37
  || stage.options.some(id => typeof id !== 'string' || !SAFE_ID.test(id)
@@ -38,6 +40,11 @@ function validateVersionManifest(manifest, expectedVersion) {
38
40
  || Object.values(stage.thresholds).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) {
39
41
  fail(`malformed ${name} stage`);
40
42
  }
43
+ if ((Object.hasOwn(stage, 'layer') !== Object.hasOwn(stage, 'layerSha256'))
44
+ || (stage.layer !== undefined && (!safeRelative(stage.layer) || stage.layer.includes('/')
45
+ || !stage.layer.endsWith('.layer.json') || !HASH.test(stage.layerSha256)))) {
46
+ fail(`malformed ${name} layer`);
47
+ }
41
48
  if (stage.weights.includes('/') || stage.config.includes('/')) fail(`${name} weights and config must be flat filenames`);
42
49
  if (Object.hasOwn(stage, 'referenceOnly')
43
50
  && (!Array.isArray(stage.referenceOnly) || new Set(stage.referenceOnly).size !== stage.referenceOnly.length
@@ -20,6 +20,7 @@ const inRange = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v
20
20
  const LIVE_STAGES = STAGES;
21
21
  const SAFE_ID = /^[a-z0-9._-]{1,80}$/;
22
22
  const sha256 = value => createHash('sha256').update(value).digest('hex');
23
+ const MAX_LAYER_BYTES = 32 * 1024 * 1024;
23
24
  // secondaryThreshold is optional and belongs to intent checkpoints (docs/system-one-intent.md#scoring).
24
25
  const validAcceptance = a => (exact(a, ['minConfidence', 'minMargin']) || (exact(a, ['minConfidence', 'minMargin', 'secondaryThreshold']) && inRange(a.secondaryThreshold, 0.05, 0.5)))
25
26
  && inRange(a.minConfidence, 0.5, 0.99) && inRange(a.minMargin, 0, 0.9);
@@ -158,10 +159,19 @@ function readActive(env = process.env) {
158
159
  const weightsPath = readableFile(dir, stage.weights, '.safetensors');
159
160
  const configPath = readableFile(dir, stage.config, '.json');
160
161
  if (!weightsPath || !configPath || sha256(fs.readFileSync(weightsPath)) !== stage.sha256) return null;
162
+ let layerPath;
163
+ if (stage.layer !== undefined) {
164
+ layerPath = readableFile(dir, stage.layer, '.json');
165
+ if (!layerPath || !stage.layer.endsWith('.layer.json') || fs.statSync(layerPath).size > MAX_LAYER_BYTES
166
+ || sha256(fs.readFileSync(layerPath)) !== stage.layerSha256) return null;
167
+ }
161
168
  loadedStages[stageName] = { ...stage, referenceOnly: stage.referenceOnly ?? [], weightsPath, configPath,
162
- configSha256: sha256(fs.readFileSync(configPath)) };
169
+ ...(layerPath ? { layerPath } : {}), configSha256: sha256(fs.readFileSync(configPath)) };
163
170
  }
164
- const fingerprint = sha256(`${pointer.version}\0${dir}\0${LIVE_STAGES.map(stage => `${stage}\0${loadedStages[stage].sha256}\0${loadedStages[stage].configSha256}`).join('\0')}`);
171
+ const fingerprint = sha256(`${pointer.version}\0${dir}\0${LIVE_STAGES.map(stage => {
172
+ const entry = loadedStages[stage];
173
+ return `${stage}\0${entry.sha256}\0${entry.configSha256}${entry.layerSha256 ? `\0${entry.layerSha256}` : ''}`;
174
+ }).join('\0')}`);
165
175
  const python = env.HARNESS_SYSTEM_ONE_PYTHON || env.PYTHON || path.join(home, 'venv', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
166
176
  return { home, pointerPath, pointer, version: pointer.version, dir, manifest, stages: loadedStages,
167
177
  fingerprint, python, sha256: loadedStages.tier.sha256.slice(0, 16) };
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:ad2dd6b3-4d90-5e3c-9e74-ca74c744a70c",
5
+ "serialNumber": "urn:uuid:6661f5f0-5209-57ad-9fcc-0e658727ece7",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-28T07:15:24.159Z",
8
+ "timestamp": "2026-12-01T04:13:31.424Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "1.3.2"
13
+ "version": "1.5.0"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@1.3.2",
18
+ "bom-ref": "pkg:npm/harness-everything@1.5.0",
19
19
  "name": "harness-everything",
20
- "version": "1.3.2",
21
- "purl": "pkg:npm/harness-everything@1.3.2"
20
+ "version": "1.5.0",
21
+ "purl": "pkg:npm/harness-everything@1.5.0"
22
22
  }
23
23
  },
24
24
  "components": [
@@ -2033,7 +2033,7 @@
2033
2033
  ]
2034
2034
  },
2035
2035
  {
2036
- "ref": "pkg:npm/harness-everything@1.3.2",
2036
+ "ref": "pkg:npm/harness-everything@1.5.0",
2037
2037
  "dependsOn": [
2038
2038
  "pkg:npm/%40commitlint/cli@19.8.1",
2039
2039
  "pkg:npm/%40commitlint/config-conventional@19.8.1",
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { spawnSync } = require('node:child_process');
9
+ const { REPO, dataPath, writeJson, runNode, assertPrivateDataDir, parseFlags, flag, required } = require('./system-one-cycle/common');
10
+ const { TASKS, fitLayerStage, successfulGuard, hasTrainerReport } = require('./system-one-cycle/train');
11
+ const { validateVersion } = require('./system-one-cycle/package');
12
+ const { PINS } = require('../harness-everything/scripts/system-one/install');
13
+
14
+ const DATA_FILES = [
15
+ 'training/v1/prompts.jsonl', 'training/v1/labels.jsonl', 'training/v1/labels-intent.jsonl',
16
+ 'training/v1-validity/prompts.jsonl', 'training/v1-validity/labels.jsonl',
17
+ ];
18
+ const PUBLIC_FILES = [
19
+ 'scripts/system-one-train.py',
20
+ 'benchmarks/fixtures/system-one-holdout.json',
21
+ 'benchmarks/fixtures/system-one-intent-holdout.json',
22
+ ];
23
+ const REQUIRED_STAGE_FILES = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
24
+ const PUBLISH_STAGE_FILES = [...REQUIRED_STAGE_FILES, 'calibration.json'];
25
+ const TRAIN_SILENCE_SECONDS = 3600;
26
+ const REUSE_FILES = [...REQUIRED_STAGE_FILES, 'calibration.json', 'resource-guard.json'];
27
+ const USAGE = 'Usage: node scripts/system-one-colab.js --data-dir <private-cycle-dir> --version <id> [--gpu T4|L4|A100] [--session <name>] [--colab <bin>]';
28
+
29
+ function sha256(file) {
30
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
31
+ }
32
+
33
+ function allowListedFile(root, relative, optional = false) {
34
+ let current = root;
35
+ const parts = relative.split('/');
36
+ for (let index = 0; index < parts.length; index++) {
37
+ current = path.join(current, parts[index]);
38
+ let stat;
39
+ try { stat = fs.lstatSync(current); }
40
+ catch (error) {
41
+ if (optional && error.code === 'ENOENT') return null;
42
+ throw new Error(`missing training input ${relative}`);
43
+ }
44
+ if (stat.isSymbolicLink() || (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory())) {
45
+ throw new Error(`invalid allow-listed file ${relative}`);
46
+ }
47
+ }
48
+ return current;
49
+ }
50
+
51
+ function completeStage(dir) {
52
+ if (!REUSE_FILES.every(file => fs.existsSync(path.join(dir, file)))) return false;
53
+ return successfulGuard(dir) && hasTrainerReport(dir, path.basename(dir));
54
+ }
55
+
56
+ function writeJsonAtomic(file, value) {
57
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${crypto.randomUUID()}.tmp`);
58
+ try {
59
+ writeJson(temporary, value);
60
+ fs.renameSync(temporary, file);
61
+ } finally {
62
+ fs.rmSync(temporary, { force: true });
63
+ }
64
+ }
65
+
66
+ function outputTail(result) {
67
+ return `${result.stdout || ''}${result.stderr || ''}`.trim().split(/\r?\n/).slice(-20).join('\n');
68
+ }
69
+
70
+ function command(bin, args, { ignoreStatus = false } = {}) {
71
+ const result = spawnSync(bin, args, { cwd: REPO, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
72
+ if (result.error || (!ignoreStatus && result.status !== 0)) {
73
+ const tail = outputTail(result);
74
+ throw new Error(`colab ${args[0]} failed${tail ? `\n${tail}` : ''}`);
75
+ }
76
+ return result;
77
+ }
78
+
79
+ function remoteRunner({ version, task, device, invocationId, expectedManifestSha256 }) {
80
+ const trainer = '/content/scripts/system-one-train.py';
81
+ const source = task === 'validity' ? '/content/training/v1-validity' : '/content/training/v1';
82
+ const output = `/content/runs/${version}/${task}`;
83
+ const holdout = task === 'intent'
84
+ ? '/content/benchmarks/fixtures/system-one-intent-holdout.json'
85
+ : '/content/benchmarks/fixtures/system-one-holdout.json';
86
+ const holdoutArgs = task === 'validity' ? '' : `, '--holdout', ${JSON.stringify(holdout)}`;
87
+ return `import hashlib, json, pathlib, subprocess, sys\nROOT = pathlib.Path('/content')\nVERSION = ${JSON.stringify(version)}\nTASK = ${JSON.stringify(task)}\nDEVICE = ${JSON.stringify(device)}\nINVOCATION_ID = ${JSON.stringify(invocationId)}\nEXPECTED_MANIFEST_SHA256 = ${JSON.stringify(expectedManifestSha256)}\nmanifest_bytes = (ROOT / 'bundle-manifest.json').read_bytes()\nif hashlib.sha256(manifest_bytes).hexdigest() != EXPECTED_MANIFEST_SHA256:\n raise SystemExit('bundle-manifest-mismatch')\nmanifest = json.loads(manifest_bytes.decode('utf-8'))\nfor item in manifest['files']:\n target = ROOT / item['path']\n digest = hashlib.sha256(target.read_bytes()).hexdigest()\n if digest != item['sha256']:\n raise SystemExit('bundle-manifest-mismatch')\nresult = subprocess.run([sys.executable, ${JSON.stringify(trainer)}, '--data-dir', ${JSON.stringify(source)}, '--out', ${JSON.stringify(output)}, '--task', TASK, '--threads', '4', '--device', DEVICE${holdoutArgs}])\nif result.returncode != 0:\n raise SystemExit('remote-training-failed')\nout = pathlib.Path(${JSON.stringify(output)})\nfiles = ${JSON.stringify(REQUIRED_STAGE_FILES)}\nif not all((out / name).is_file() for name in files):\n raise SystemExit('remote-training-failed')\nstatus = {'schemaVersion': 1, 'ok': True, 'task': TASK, 'version': VERSION, 'invocationId': INVOCATION_ID, 'manifestSha256': EXPECTED_MANIFEST_SHA256, 'files': {name: hashlib.sha256((out / name).read_bytes()).hexdigest() for name in files}}\n(out / 'remote-status.json').write_text(json.dumps(status), encoding='utf-8')\n`;
88
+ }
89
+
90
+ function prepareRunner(files, version) {
91
+ const dirs = [...new Set([
92
+ ...files.map(file => `/content/${path.posix.dirname(file)}`),
93
+ `/content/runs/${version}`,
94
+ ])];
95
+ return `import os\nPATHS = ${JSON.stringify(dirs)}\nfor item in PATHS:\n os.makedirs(item, exist_ok=True)\n`;
96
+ }
97
+
98
+ function main(argv) {
99
+ const flags = parseFlags(argv);
100
+ if (flag(flags, 'help') === true) { process.stdout.write(`${USAGE}\n`); return; }
101
+ const allowedFlags = new Set(['data-dir', 'version', 'gpu', 'session', 'colab']);
102
+ for (const key of Object.keys(flags)) if (!allowedFlags.has(key)) throw new Error(`unknown option --${key}`);
103
+ const dataDir = assertPrivateDataDir(path.resolve(required(flags, 'data-dir')));
104
+ const version = validateVersion(required(flags, 'version'));
105
+ const gpu = flag(flags, 'gpu');
106
+ if (gpu !== undefined && !['T4', 'L4', 'A100'].includes(gpu)) throw new Error('--gpu must be T4, L4, or A100');
107
+ const device = gpu ? 'cuda' : 'cpu';
108
+ const session = flag(flags, 'session', `system-one-${version}-${process.pid}`);
109
+ if (typeof session !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(session)) throw new Error('--session must be a safe session name');
110
+ const colab = flag(flags, 'colab', process.env.COLAB_BIN || 'colab');
111
+ if (typeof colab !== 'string' || !colab.trim()) throw new Error('--colab must name a binary');
112
+ const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
113
+ const stageDirs = Object.fromEntries(TASKS.map(task => [task, dataPath(dataDir, 'training', 'runs', version, task)]));
114
+ const tasks = TASKS.filter(task => !completeStage(stageDirs[task]));
115
+ if (!tasks.length) {
116
+ for (const task of TASKS) fitLayerStage({ dataDir, runDir: stageDirs[task], task });
117
+ process.stdout.write(`${JSON.stringify({ version, trained: 0, skipped: TASKS.length, session: null })}\n`);
118
+ return;
119
+ }
120
+ const invocationId = crypto.randomUUID();
121
+
122
+ const localFiles = new Map();
123
+ for (const file of DATA_FILES) {
124
+ const local = allowListedFile(dataDir, file, true);
125
+ if (local) localFiles.set(file, local);
126
+ }
127
+ const requiredInputs = ['training/v1/prompts.jsonl', 'training/v1/labels.jsonl', 'training/v1/labels-intent.jsonl',
128
+ 'training/v1-validity/prompts.jsonl', 'training/v1-validity/labels.jsonl'];
129
+ for (const file of requiredInputs) if (!localFiles.has(file)) throw new Error(`missing training input ${file}`);
130
+ for (const file of PUBLIC_FILES) localFiles.set(file, allowListedFile(REPO, file));
131
+ const files = [...localFiles.keys()];
132
+ const manifest = { schemaVersion: 1, files: files.map(file => {
133
+ const local = localFiles.get(file);
134
+ return { path: file, sha256: sha256(local) };
135
+ }) };
136
+ const manifestBytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
137
+ const manifestDigest = crypto.createHash('sha256').update(manifestBytes).digest('hex');
138
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-colab-'));
139
+ const manifestFile = path.join(tempDir, 'bundle-manifest.json');
140
+ const runnerFile = path.join(tempDir, 'runner.py');
141
+ fs.writeFileSync(manifestFile, manifestBytes, { mode: 0o600 });
142
+ let interrupted = null;
143
+ const signalHandlers = {};
144
+ let failure = null;
145
+ for (const signal of ['SIGINT', 'SIGTERM']) {
146
+ signalHandlers[signal] = () => { interrupted = signal; };
147
+ process.on(signal, signalHandlers[signal]);
148
+ }
149
+ const runColab = (args, options) => {
150
+ const result = command(colab, args, options);
151
+ if (interrupted) throw new Error(`interrupted by ${interrupted}`);
152
+ return result;
153
+ };
154
+ try {
155
+ runColab(['new', '-s', session, ...(gpu ? ['--gpu', gpu] : [])]);
156
+ runColab(['install', '-s', session, PINS.cuaS1Spec]);
157
+ fs.writeFileSync(runnerFile, prepareRunner(files, version), { mode: 0o600 });
158
+ runColab(['exec', '-s', session, '-f', runnerFile], { ignoreStatus: true });
159
+ for (const file of files) {
160
+ runColab(['upload', '-s', session, localFiles.get(file), `/content/${file}`]);
161
+ }
162
+ runColab(['upload', '-s', session, manifestFile, '/content/bundle-manifest.json']);
163
+ for (const task of tasks) {
164
+ fs.writeFileSync(runnerFile, remoteRunner({ version, task, device, invocationId, expectedManifestSha256: manifestDigest }), { mode: 0o600 });
165
+ // The trainer subprocess sends no kernel output, so colab's default 30 s silence limit aborts the exec.
166
+ const execution = runColab(['exec', '-s', session, '-f', runnerFile, '--timeout', String(TRAIN_SILENCE_SECONDS)], { ignoreStatus: true });
167
+ const out = stageDirs[task];
168
+ const parent = path.dirname(out);
169
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
170
+ const staging = fs.mkdtempSync(path.join(parent, `.${task}-colab-stage-`));
171
+ fs.chmodSync(staging, 0o700);
172
+ try {
173
+ const statusFile = path.join(tempDir, `${task}-remote-status.json`);
174
+ try {
175
+ runColab(['download', '-s', session, `/content/runs/${version}/${task}/remote-status.json`, statusFile]);
176
+ } catch (error) {
177
+ throw new Error(`remote-status-missing: ${error.message}\n${outputTail(execution)}`);
178
+ }
179
+ let status;
180
+ try { status = JSON.parse(fs.readFileSync(statusFile, 'utf8')); }
181
+ catch { throw new Error(`remote-status-missing: invalid status JSON\n${outputTail(execution)}`); }
182
+ if (status?.ok !== true) throw new Error(`remote-training-failed: ${status?.reason || 'trainer did not complete'}\n${outputTail(execution)}`);
183
+ if (status.schemaVersion !== 1 || status.task !== task || status.version !== version
184
+ || status.invocationId !== invocationId || status.manifestSha256 !== manifestDigest) {
185
+ throw new Error(`remote-training-failed: status identity mismatch\n${outputTail(execution)}`);
186
+ }
187
+ if (!status.files || typeof status.files !== 'object') {
188
+ throw new Error(`remote-status-missing: stage file hashes missing\n${outputTail(execution)}`);
189
+ }
190
+ for (const file of REQUIRED_STAGE_FILES) {
191
+ const local = path.join(staging, file);
192
+ try {
193
+ runColab(['download', '-s', session, `/content/runs/${version}/${task}/${file}`, local]);
194
+ } catch (error) {
195
+ throw new Error(`remote-training-failed: missing ${task}/${file}\n${error.message}\n${outputTail(execution)}`);
196
+ }
197
+ if (!/^[a-f0-9]{64}$/.test(status.files[file] || '') || sha256(local) !== status.files[file]) {
198
+ throw new Error(`stage-hash-mismatch: ${task}/${file}\n${outputTail(execution)}`);
199
+ }
200
+ }
201
+ const guard = { schemaVersion: 1, exitCode: 0, killedForLimit: false, monitorFailed: false,
202
+ createdAt: new Date().toISOString(), remote: { provider: 'colab', gpu: gpu || null, session,
203
+ invocationId, manifestSha256: manifestDigest, files: status.files } };
204
+ runNode(calibrator, [path.join(staging, 'val-scores.jsonl'), path.join(staging, 'calibration.json'), '--task', task,
205
+ '--catalog', path.join(staging, 'train-report.json')]);
206
+ fs.mkdirSync(out, { recursive: true, mode: 0o700 });
207
+ fs.rmSync(path.join(out, 'resource-guard.json'), { force: true });
208
+ for (const file of PUBLISH_STAGE_FILES) fs.renameSync(path.join(staging, file), path.join(out, file));
209
+ writeJsonAtomic(path.join(out, 'resource-guard.json'), guard);
210
+ if (interrupted) throw new Error(`interrupted by ${interrupted}`);
211
+ } finally {
212
+ fs.rmSync(staging, { recursive: true, force: true });
213
+ }
214
+ }
215
+ } catch (error) {
216
+ failure = error;
217
+ } finally {
218
+ try { command(colab, ['stop', '-s', session]); }
219
+ catch (error) {
220
+ const cleanup = `Colab stop failed: ${error.message}\nSession ID: ${session}\nManual stop command: colab stop -s ${session}`;
221
+ failure = failure ? new Error(`${failure.message}\n${cleanup}`) : new Error(cleanup);
222
+ }
223
+ fs.rmSync(tempDir, { recursive: true, force: true });
224
+ for (const signal of ['SIGINT', 'SIGTERM']) {
225
+ process.removeListener(signal, signalHandlers[signal]);
226
+ }
227
+ }
228
+ if (failure) throw failure;
229
+ for (const task of TASKS) fitLayerStage({ dataDir, runDir: stageDirs[task], task });
230
+ const hashes = manifest.files.map(({ path: file, sha256: hash }) => ({ path: file, sha256: hash }));
231
+ process.stdout.write(`${JSON.stringify({ version, trained: tasks.length, skipped: TASKS.length - tasks.length,
232
+ gpu: gpu || null, device, session, uploaded: files.length + 1, manifestSha256: manifestDigest, files: hashes })}\n`);
233
+ }
234
+
235
+ if (require.main === module) {
236
+ try { main(process.argv.slice(2)); }
237
+ catch (error) { process.stderr.write(`system-one-colab: ${error.message}\n`); process.exitCode = 1; }
238
+ }
239
+
240
+ module.exports = { main, remoteRunner, completeStage };