harness-everything 1.3.2 → 1.4.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.
@@ -10,7 +10,7 @@
10
10
  "name": "harness-everything",
11
11
  "source": "./",
12
12
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
13
- "version": "1.3.2",
13
+ "version": "1.4.0",
14
14
  "author": {
15
15
  "name": "Miya Daniel"
16
16
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-everything",
3
3
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
4
- "version": "1.3.2",
4
+ "version": "1.4.0",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
@@ -34,6 +34,10 @@ jobs:
34
34
  uses: actions/checkout@v7
35
35
  with:
36
36
  fetch-depth: 0
37
+ # #381 a1: ruleset main-protected requires status checks and cannot list the
38
+ # github-actions app as a bypass actor on a personal repo; the release commit
39
+ # and tag are pushed with this write deploy key, which the ruleset bypasses.
40
+ ssh-key: ${{ secrets.RELEASE_DEPLOY_KEY }}
37
41
 
38
42
  # Release tooling uses the repository's primary Node runtime.
39
43
  - name: Setup Node.js
@@ -70,7 +74,9 @@ jobs:
70
74
  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
71
75
  NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
72
76
  NPM_CONFIG_PROVENANCE: "true"
73
- run: npx --no-install semantic-release
77
+ # An SSH repository URL makes semantic-release push with the deploy key
78
+ # (its SSH auth check runs before any token fallback).
79
+ run: npx --no-install semantic-release --repository-url "git@github.com:${{ github.repository }}.git"
74
80
 
75
81
  - name: Upload release SBOM artifact
76
82
  if: ${{ hashFiles('sbom.cdx.json') != '' }}
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [1.4.0](https://github.com/dyphn1/Harness-everything/compare/v1.3.2...v1.4.0) (2026-11-29)
6
+
7
+ ### Features
8
+
9
+ * **system-one:** add colab launcher for the train stage ([e7e45fd](https://github.com/dyphn1/Harness-everything/commit/e7e45fd47447259b608eedb56be5fc411f9a1cbb)), closes [#563](https://github.com/dyphn1/Harness-everything/issues/563)
10
+ * **system-one:** add trainer device selection for gpu training ([a5bafd1](https://github.com/dyphn1/Harness-everything/commit/a5bafd1b5404dcd0510d81cc7b1d2f1efcb57244)), closes [#563](https://github.com/dyphn1/Harness-everything/issues/563)
11
+
12
+ ### Bug Fixes
13
+
14
+ * **system-one:** lift colab exec silence limit for training stages ([573c451](https://github.com/dyphn1/Harness-everything/commit/573c4512c93ead714092bd0cc35205bb3118a035))
15
+ * **system-one:** publish colab stages atomically and bind remote status ([47f29df](https://github.com/dyphn1/Harness-everything/commit/47f29dfc7b4f58f0a9a07bc115c55e8589b3425f)), closes [#563](https://github.com/dyphn1/Harness-everything/issues/563)
16
+ * **system-one:** verify colab stage success from downloaded status ([8fd8baa](https://github.com/dyphn1/Harness-everything/commit/8fd8baa5d1d95c83bfba46588f20ce1d77050b39)), closes [#563](https://github.com/dyphn1/Harness-everything/issues/563)
17
+
5
18
  ## [1.3.2](https://github.com/dyphn1/Harness-everything/compare/v1.3.1...v1.3.2) (2026-11-28)
6
19
 
7
20
  ### Bug Fixes
@@ -304,6 +317,10 @@ Claude-Session: https://claude.ai/code/session_01RPz4xUrN12wGoL19istZUE
304
317
 
305
318
  ## [Unreleased]
306
319
 
320
+ ### System One training on Colab
321
+
322
+ * **system-one:** `scripts/system-one-train.py` accepts `--device cpu|cuda|auto` (default `cpu`, CPU outputs unchanged) and records `device` and `torch` in the checkpoint metadata and `train-report.json`. The new `scripts/system-one-colab.js` runs the cycle `train` stage on a Google Colab VM through `google-colab-cli`: it uploads only the built `training/v1*` files plus the public trainer and catalog fixtures under a sha256 manifest, accepts each stage only from a downloaded `remote-status.json` with per-file hashes, always stops the VM, and leaves a run dir that the unchanged local `evaluate` → `package` path accepts (#563).
323
+
307
324
  ### E1 pilot retirement
308
325
 
309
326
  * **e1:** the E1 doc-reconciliation pilot is retired (#553). Its runtime modules and the W6 `inventory`/`seal` CLI (`hooks/scripts/w6-state-operations.js`) have been removed, and every `HARNESS_DOC_RECONCILIATION_PILOT` value is now ignored. Finish in-flight E1 work on the previous release, or end it and open a new session to redo review and verification. Recorded evidence stays in place; `doc-check` and document governance are unchanged.
package/RELEASING.md CHANGED
@@ -44,6 +44,8 @@ A push to `main` runs the full reusable CI gate and then semantic-release. A man
44
44
 
45
45
  The SBOM is generated from the release `package.json`/`package-lock.json` as CycloneDX 1.7, the current 1.x format, to satisfy consumers and regulatory baselines requiring CycloneDX 1.6 or later. It is intentionally not committed to Git. The release publishes `sbom.cdx.json` in the npm tarball and as a GitHub Release asset, while the workflow also retains it as an Actions artifact.
46
46
 
47
+ The release commit and tag are pushed over SSH with the `RELEASE_DEPLOY_KEY` write deploy key, because ruleset `main-protected` requires status checks on `main` and a personal repository cannot list the GitHub Actions app as a bypass actor; the deploy key is the ruleset's only always-bypass actor besides PR-merge bypass for admins (#381). `GITHUB_TOKEN` stays in use for GitHub API calls (releases, comments).
48
+
47
49
  Release concurrency is serialized so two updates to `main` cannot publish competing versions.
48
50
 
49
51
  ## Version ownership
@@ -0,0 +1,450 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
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 { test } = require('node:test');
10
+ const { REPO } = require('../scripts/system-one-cycle/common');
11
+ const { TASKS, trainCycle } = require('../scripts/system-one-cycle/train');
12
+ const { remoteRunner } = require('../scripts/system-one-colab');
13
+
14
+ const skipNoColabCli = process.platform === 'win32' && 'google-colab-cli supports Linux and macOS only';
15
+ const launcher = path.join(REPO, 'scripts', 'system-one-colab.js');
16
+ const cycleCli = path.join(REPO, 'scripts', 'system-one-cycle.js');
17
+ const allowed = [
18
+ 'training/v1/prompts.jsonl', 'training/v1/labels.jsonl', 'training/v1/labels-intent.jsonl',
19
+ 'training/v1-validity/prompts.jsonl', 'training/v1-validity/labels.jsonl',
20
+ 'scripts/system-one-train.py',
21
+ 'benchmarks/fixtures/system-one-holdout.json',
22
+ 'benchmarks/fixtures/system-one-intent-holdout.json',
23
+ ];
24
+
25
+ function fixture(t) {
26
+ const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-colab-')));
27
+ const dataDir = path.join(root, 'private-cycle');
28
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
29
+ for (const relative of allowed.slice(0, 5)) {
30
+ const file = path.join(dataDir, relative);
31
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
32
+ const row = relative.endsWith('prompts.jsonl')
33
+ ? { id: 'synthetic-row', family: 'synthetic-family', source: 'observation', split: 'train', text: 'synthetic prompt' }
34
+ : relative.endsWith('labels-intent.jsonl')
35
+ ? { id: 'synthetic-row', gold: 'feature', secondary: [] }
36
+ : { id: 'synthetic-row', gold: 'tier2' };
37
+ fs.writeFileSync(file, `${JSON.stringify(row)}\n`, { mode: 0o600 });
38
+ }
39
+ for (const relative of ['training/observed/prompts-observed.jsonl', 'training/relabel-luna/labels.jsonl',
40
+ 'training/adjudication/consensus.jsonl', 'training/history.jsonl']) {
41
+ const file = path.join(dataDir, relative);
42
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
43
+ fs.writeFileSync(file, 'PRIVATE-SENTINEL\n', { mode: 0o600 });
44
+ }
45
+ const fakeRoot = path.join(root, 'fake-colab');
46
+ const log = path.join(root, 'colab.jsonl');
47
+ const bin = path.join(root, 'colab');
48
+ fs.writeFileSync(bin, `#!/usr/bin/env node
49
+ 'use strict';
50
+ const fs = require('node:fs');
51
+ const path = require('node:path');
52
+ const crypto = require('node:crypto');
53
+ const a = process.argv.slice(2);
54
+ const root = process.env.FAKE_COLAB_ROOT;
55
+ const log = process.env.FAKE_COLAB_LOG;
56
+ fs.mkdirSync(root, { recursive: true });
57
+ function record(extra = {}) { fs.appendFileSync(log, JSON.stringify({ argv: a, ...extra }) + '\\n'); }
58
+ function remotePath(value) { return path.join(root, value.replace(/^\\/content\\//, '')); }
59
+ if (a[0] === 'upload') {
60
+ record();
61
+ const source = a[3]; const target = remotePath(a[4]);
62
+ if (!fs.existsSync(path.dirname(target))) { console.error('[colab] Upload failed: 500 Server Error'); process.exit(1); }
63
+ fs.copyFileSync(source, target);
64
+ if (a[4] === '/content/bundle-manifest.json') record({ uploadedManifestSha256: crypto.createHash('sha256').update(fs.readFileSync(source)).digest('hex') });
65
+ if (process.env.FAKE_COLAB_CORRUPT_UPLOAD === '1' && a[4].endsWith('training/v1/prompts.jsonl')) fs.appendFileSync(target, 'tampered\\n');
66
+ } else if (a[0] === 'download') {
67
+ record(); if (process.env.FAKE_COLAB_FAIL_DOWNLOAD === a[3] || !fs.existsSync(remotePath(a[3]))) { console.error('[colab] Download failed: File or directory not found'); process.exit(1); } fs.mkdirSync(path.dirname(a[4]), { recursive: true }); fs.copyFileSync(remotePath(a[3]), a[4]);
68
+ } else if (a[0] === 'exec') {
69
+ const script = fs.readFileSync(a[4], 'utf8');
70
+ if (script.includes('os.makedirs')) {
71
+ const remotePaths = JSON.parse(script.match(/PATHS = (\\[[^\\n]+\\])/)[1]);
72
+ record({ task: 'prepare' });
73
+ for (const item of remotePaths) fs.mkdirSync(remotePath(item), { recursive: true });
74
+ process.exit(0);
75
+ }
76
+ if (!script.includes('hashlib.sha256')) { record(); process.exit(0); }
77
+ // Real colab exec gives up after 30 s without kernel output; the trainer subprocess emits none (s1-2026-11-29 run).
78
+ const timeoutAt = a.indexOf('--timeout');
79
+ if (timeoutAt < 0 || Number(a[timeoutAt + 1]) < 600) { record({ task: 'silence-timeout' }); console.error('TimeoutError: no message from the kernel for 30s'); process.exit(1); }
80
+ const manifestBytes = fs.readFileSync(path.join(root, 'bundle-manifest.json'));
81
+ const manifestSha256 = crypto.createHash('sha256').update(manifestBytes).digest('hex');
82
+ const expectedManifestSha256 = script.match(/EXPECTED_MANIFEST_SHA256 = ["']([^"']+)/)?.[1] || manifestSha256;
83
+ const invocationId = script.match(/INVOCATION_ID = ["']([^"']+)/)?.[1] || null;
84
+ if (manifestSha256 !== expectedManifestSha256) { record({ task: script.match(/TASK = ["']([^"']+)/)?.[1] }); console.error('bundle-manifest-mismatch'); process.exit(0); }
85
+ const manifest = JSON.parse(manifestBytes);
86
+ for (const entry of manifest.files) {
87
+ const actual = crypto.createHash('sha256').update(fs.readFileSync(remotePath('/content/' + entry.path))).digest('hex');
88
+ if (actual !== entry.sha256) { record({ task: script.match(/TASK = [\"']([^\"']+)/)?.[1] }); console.error('manifest-mismatch'); process.exit(0); }
89
+ }
90
+ const task = script.match(/TASK = [\"']([^\"']+)/)?.[1];
91
+ record({ task });
92
+ if (process.env.FAKE_COLAB_FAIL_TASK === task) { console.error('trainer-failed'); process.exit(0); }
93
+ const version = script.match(/VERSION = [\"']([^\"']+)/)?.[1];
94
+ const holdout = task === 'intent' ? 'benchmarks/fixtures/system-one-intent-holdout.json' : 'benchmarks/fixtures/system-one-holdout.json';
95
+ const catalog = task === 'validity' ? ['invalid'] : JSON.parse(fs.readFileSync(remotePath('/content/' + holdout), 'utf8')).cases[0].request.options.map(x => x.id).filter(id => task !== 'tier' || ['tier1','tier2','tier3'].includes(id));
96
+ const out = path.join(root, 'runs', version, task); fs.mkdirSync(out, { recursive: true });
97
+ const header = Buffer.from(JSON.stringify({ weight: { dtype: 'F32', shape: [1], data_offsets: [0, 4] } }));
98
+ const paddedHeader = Buffer.concat([header, Buffer.alloc((8 - header.length % 8) % 8, 0x20)]);
99
+ const headerLength = Buffer.alloc(8);
100
+ headerLength.writeBigUInt64LE(BigInt(paddedHeader.length));
101
+ fs.writeFileSync(path.join(out, 'harness-routing-v1.safetensors'), Buffer.concat([headerLength, paddedHeader, Buffer.alloc(4)]));
102
+ fs.writeFileSync(path.join(out, 'harness-routing-v1.json'), JSON.stringify({ metadata: { domain: 'harness-routing-v1', task, loss: 'binary_cross_entropy', catalog } }));
103
+ const validationGold = catalog[0];
104
+ fs.writeFileSync(path.join(out, 'val-scores.jsonl'), JSON.stringify({ id: 'synthetic-validation', gold: validationGold,
105
+ scores: Object.fromEntries(catalog.map(id => [id, id === validationGold ? 0.99 : 0.01])) }) + '\\n');
106
+ fs.writeFileSync(path.join(out, 'train-report.json'), process.env.FAKE_COLAB_BAD_CATALOG === task ? '{' : JSON.stringify({ task, catalog }));
107
+ const files = ['harness-routing-v1.safetensors','harness-routing-v1.json','val-scores.jsonl','train-report.json'];
108
+ const status = { schemaVersion: 1, ok: true, task, version, invocationId,
109
+ manifestSha256: process.env.FAKE_COLAB_STATUS_MANIFEST_SHA256 || expectedManifestSha256,
110
+ files: Object.fromEntries(files.map(file => [file, crypto.createHash('sha256').update(fs.readFileSync(path.join(out, file))).digest('hex')])) };
111
+ fs.writeFileSync(path.join(root, 'runs', version, task, 'remote-status.json'), JSON.stringify(status));
112
+ if (process.env.FAKE_COLAB_TAMPER_STAGE === task + '/harness-routing-v1.json') fs.appendFileSync(path.join(out, 'harness-routing-v1.json'), 'tampered');
113
+ } else if (a[0] === 'stop') {
114
+ record();
115
+ if (process.env.FAKE_COLAB_FAIL_STOP === '1') { console.error('injected-stop-failure'); process.exit(1); }
116
+ } else { record(); }
117
+ `, { mode: 0o700 });
118
+ const env = { ...process.env, FAKE_COLAB_ROOT: fakeRoot, FAKE_COLAB_LOG: log };
119
+ delete env.HARNESS_SYSTEM_ONE_MODE;
120
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
121
+ return { dataDir, fakeRoot, log, bin, env };
122
+ }
123
+
124
+ function run(f, extra = []) {
125
+ return spawnSync(process.execPath, [launcher, '--data-dir', f.dataDir, '--version', 'synthetic-v1',
126
+ '--colab', f.bin, ...extra], { cwd: REPO, encoding: 'utf8', env: f.env, stdio: ['ignore', 'pipe', 'pipe'] });
127
+ }
128
+
129
+ function logRows(f) {
130
+ return fs.readFileSync(f.log, 'utf8').trim().split(/\r?\n/).filter(Boolean).map(JSON.parse);
131
+ }
132
+
133
+ function stageDir(f, task) {
134
+ return path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', task);
135
+ }
136
+
137
+ async function assertIntentRetryReachesTrainCycle(f) {
138
+ const calls = [];
139
+ await assert.rejects(trainCycle({ dataDir: f.dataDir, version: 'synthetic-v1', run: async (_bin, args) => {
140
+ calls.push(args[args.indexOf('--task') + 1]);
141
+ throw new Error('stopped-before-training');
142
+ } }), /stopped-before-training/);
143
+ assert.deepEqual(calls, ['intent']);
144
+ }
145
+
146
+ function makePublicationFailure(f) {
147
+ const preload = path.join(path.dirname(f.bin), 'fail-publication.js');
148
+ fs.writeFileSync(preload, `const fs = require('node:fs');
149
+ const path = require('node:path');
150
+ const rename = fs.renameSync;
151
+ fs.renameSync = function (source, target, ...args) {
152
+ const name = path.basename(target);
153
+ if (process.env.FAKE_COLAB_FAIL_PUBLISH === '1' && target.includes('/training/runs/synthetic-v1/intent/') &&
154
+ ['harness-routing-v1.safetensors', 'harness-routing-v1.json'].includes(name)) {
155
+ fs.appendFileSync(process.env.FAKE_COLAB_PUBLISH_LOG, name + '\\n');
156
+ if (name === 'harness-routing-v1.json') throw new Error('injected-final-publication-failure');
157
+ }
158
+ return rename.call(this, source, target, ...args);
159
+ };
160
+ `);
161
+ f.env.FAKE_COLAB_FAIL_PUBLISH = '1';
162
+ f.env.FAKE_COLAB_PUBLISH_LOG = path.join(path.dirname(f.bin), 'publication.log');
163
+ f.env.NODE_OPTIONS = `${f.env.NODE_OPTIONS || ''} --require=${preload.replace(/\\/g, '/')}`.trim();
164
+ }
165
+
166
+ function evaluatePackageAndVerifyArtifacts(f) {
167
+ const scorerDir = path.join(path.dirname(f.bin), 'synthetic-scorer');
168
+ const scoreScript = path.join(REPO, 'scripts', 'system-one-cycle', 'score.py');
169
+ fs.mkdirSync(scorerDir, { recursive: true, mode: 0o700 });
170
+ fs.writeFileSync(path.join(scorerDir, 'sitecustomize.py'), `import json, os, sys
171
+ _SCORE_SCRIPT = ${JSON.stringify(scoreScript)}
172
+ if sys.argv and os.path.realpath(sys.argv[0]) == os.path.realpath(_SCORE_SCRIPT):
173
+ args = dict(zip(sys.argv[1::2], sys.argv[2::2]))
174
+ task = args['--task']
175
+ config = json.load(open(os.path.splitext(args['--weights'])[0] + '.json', encoding='utf-8'))
176
+ ids = config['metadata']['catalog']
177
+ holdout = json.load(open(args['--holdout'], encoding='utf-8'))
178
+ rows = []
179
+ for case in holdout['cases']:
180
+ gold = 'actionable' if task == 'validity' else case.get('gold')
181
+ if task == 'intent':
182
+ gold = gold if isinstance(gold, list) else [gold]
183
+ gold = [option for option in gold if option in ids]
184
+ if not gold:
185
+ continue
186
+ elif task == 'tier' and gold not in ids:
187
+ continue
188
+ positives = set(gold if isinstance(gold, list) else [gold])
189
+ scores = {option: (0.01 if option == 'invalid' else 0.99) if task == 'validity'
190
+ else (0.99 if option in positives else 0.01) for option in ids}
191
+ rows.append({'id': case['id'], 'gold': gold, 'scores': scores})
192
+ with open(args['--out'], 'w', encoding='utf-8') as output:
193
+ output.writelines(json.dumps(row, separators=(',', ':')) + '\\n' for row in rows)
194
+ sys.stdout.flush()
195
+ sys.stderr.flush()
196
+ os._exit(0)
197
+ `);
198
+ const env = { ...f.env, PYTHON: process.env.PYTHON || 'python3', PYTHONPATH: scorerDir,
199
+ PYTHONNOUSERSITE: '1', PYTHONDONTWRITEBYTECODE: '1' };
200
+ const history = path.join(path.dirname(f.bin), 'synthetic-history.jsonl');
201
+ for (const step of ['evaluate', 'package']) {
202
+ const args = [cycleCli, step, '--data-dir', f.dataDir, '--version', 'synthetic-v1'];
203
+ if (step === 'evaluate') args.push('--history', history);
204
+ const result = spawnSync(process.execPath, args,
205
+ { cwd: REPO, encoding: 'utf8', env });
206
+ assert.equal(result.status, 0, `${step}: ${result.stderr || result.stdout}`);
207
+ }
208
+ const versionDir = path.join(f.dataDir, 'training', 'versions', 'synthetic-v1');
209
+ const manifestFile = path.join(versionDir, 'manifest.json');
210
+ const verify = `import hashlib,json,sys\nsys.path.insert(0, ${JSON.stringify(path.join(REPO, 'harness-everything', 'scripts', 'system-one'))})\nfrom cua_adapter import verify_artifacts\nroot=${JSON.stringify(versionDir)}\nmanifest=json.load(open(sys.argv[1], encoding='utf-8'))\nfor stage in manifest['stages'].values():\n weights=__import__('pathlib').Path(root, stage['weights']).resolve()\n config=__import__('pathlib').Path(root, stage['config']).resolve()\n verify_artifacts({'checkpoint':str(weights),'config':str(config),'weightsSha256':stage['sha256'],'configSha256':hashlib.sha256(config.read_bytes()).hexdigest()})\nprint('verified three packaged stages')\n`;
211
+ const result = spawnSync(env.PYTHON, ['-c', verify, manifestFile], { cwd: REPO, encoding: 'utf8', env });
212
+ assert.equal(result.status, 0, result.stderr);
213
+ assert.match(result.stdout, /verified three packaged stages/);
214
+ }
215
+
216
+ test('Colab launcher uploads only allow-listed data and produces stages trainCycle reuses', { skip: skipNoColabCli }, async t => {
217
+ const f = fixture(t);
218
+ const result = run(f, ['--gpu', 'T4', '--session', 'fake-session']);
219
+ assert.equal(result.status, 0, result.stderr);
220
+ const rows = logRows(f);
221
+ const uploads = rows.filter(row => row.argv[0] === 'upload');
222
+ assert.deepEqual(uploads.map(row => row.argv[4].replace(/^\/content\//, '')).filter(remote => remote !== 'bundle-manifest.json').sort(), [...allowed].sort());
223
+ assert.ok(uploads.every(row => !/observed|relabel-luna|adjudication|history/.test(row.argv[4])));
224
+ assert.equal(rows.filter(row => row.argv[0] === 'exec').length, 4);
225
+ const manifestUpload = rows.find(row => row.uploadedManifestSha256);
226
+ assert.equal(JSON.parse(result.stdout).manifestSha256, manifestUpload.uploadedManifestSha256);
227
+ const execIndices = rows.map((row, index) => row.argv[0] === 'exec' && row.task !== 'prepare' ? index : -1).filter(index => index >= 0);
228
+ assert.ok(rows.findIndex(row => row.argv[0] === 'exec' && row.task === 'prepare') < rows.findIndex(row => row.argv[0] === 'upload'));
229
+ for (let i = 0; i < execIndices.length - 1; i++) {
230
+ const downloads = rows.slice(execIndices[i] + 1, execIndices[i + 1]).filter(row => row.argv[0] === 'download');
231
+ assert.equal(downloads.length, 5);
232
+ assert.match(downloads[0].argv[3], /remote-status\.json$/);
233
+ }
234
+ assert.equal(rows.at(-1).argv[0], 'stop');
235
+ for (const task of TASKS) {
236
+ const status = JSON.parse(fs.readFileSync(path.join(f.fakeRoot, 'runs', 'synthetic-v1', task, 'remote-status.json'), 'utf8'));
237
+ assert.match(status.invocationId, /^[0-9a-f-]{36}$/);
238
+ assert.equal(status.manifestSha256, manifestUpload.uploadedManifestSha256);
239
+ }
240
+ const skipped = await trainCycle({ dataDir: f.dataDir, version: 'synthetic-v1', run: () => { throw new Error('unexpected local training'); } });
241
+ assert.equal(skipped.skipped, 3);
242
+ for (const task of TASKS) {
243
+ const stage = path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', task);
244
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(stage, 'resource-guard.json'), 'utf8')).remote,
245
+ { provider: 'colab', gpu: 'T4', session: 'fake-session' });
246
+ }
247
+ assert.doesNotMatch(result.stdout, /synthetic"|PRIVATE-SENTINEL/);
248
+ });
249
+
250
+ test('manifest mismatch fails before training and still stops the session', { skip: skipNoColabCli }, t => {
251
+ const f = fixture(t);
252
+ f.env.FAKE_COLAB_CORRUPT_UPLOAD = '1';
253
+ const result = run(f);
254
+ assert.notEqual(result.status, 0);
255
+ const rows = logRows(f);
256
+ assert.equal(rows.filter(row => row.argv[0] === 'exec').length, 2);
257
+ assert.equal(rows.at(-1).argv[0], 'stop');
258
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', 'validity', 'train-report.json')), false);
259
+ });
260
+
261
+ test('failed intent stage has no status, keeps validity and writes no intent guard', { skip: skipNoColabCli }, t => {
262
+ const f = fixture(t);
263
+ f.env.FAKE_COLAB_FAIL_TASK = 'intent';
264
+ const failed = run(f);
265
+ assert.notEqual(failed.status, 0);
266
+ assert.match(failed.stderr, /remote-status-missing|remote-training-failed/);
267
+ assert.match(failed.stderr, /trainer-failed/);
268
+ const rows = logRows(f);
269
+ assert.equal(rows.at(-1).argv[0], 'stop');
270
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', 'validity', 'train-report.json')), true);
271
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', 'intent', 'train-report.json')), false);
272
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', 'intent', 'resource-guard.json')), false);
273
+ });
274
+
275
+ test('tampered downloaded stage file fails its remote hash check and stops the session', { skip: skipNoColabCli }, t => {
276
+ const f = fixture(t);
277
+ f.env.FAKE_COLAB_TAMPER_STAGE = 'validity/harness-routing-v1.json';
278
+ const result = run(f);
279
+ assert.notEqual(result.status, 0);
280
+ assert.match(result.stderr, /stage-hash-mismatch/);
281
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'training', 'runs', 'synthetic-v1', 'validity', 'resource-guard.json')), false);
282
+ assert.equal(logRows(f).at(-1).argv[0], 'stop');
283
+ });
284
+
285
+ test('tampered repair stays incomplete, retries intent, and reuses prior stages', { skip: skipNoColabCli }, async t => {
286
+ const f = fixture(t);
287
+ assert.equal(run(f, ['--session', 'fake-session']).status, 0);
288
+ const intent = stageDir(f, 'intent');
289
+ fs.rmSync(path.join(intent, 'harness-routing-v1.json'));
290
+ f.env.FAKE_COLAB_TAMPER_STAGE = 'intent/harness-routing-v1.json';
291
+
292
+ const failed = run(f, ['--session', 'fake-session']);
293
+ assert.notEqual(failed.status, 0);
294
+ assert.match(failed.stderr, /stage-hash-mismatch: intent\/harness-routing-v1\.json/);
295
+ assert.equal(fs.existsSync(path.join(intent, 'harness-routing-v1.json')), false);
296
+ assert.equal(fs.existsSync(path.join(intent, 'resource-guard.json')), true);
297
+ assert.equal(fs.existsSync(path.join(stageDir(f, 'validity'), 'resource-guard.json')), true);
298
+ await assertIntentRetryReachesTrainCycle(f);
299
+
300
+ delete f.env.FAKE_COLAB_TAMPER_STAGE;
301
+ const repaired = run(f, ['--session', 'fake-session']);
302
+ assert.equal(repaired.status, 0, repaired.stderr);
303
+ assert.match(repaired.stdout, /"trained":1,"skipped":2/);
304
+ assert.equal((await trainCycle({ dataDir: f.dataDir, version: 'synthetic-v1' })).skipped, 3);
305
+ evaluatePackageAndVerifyArtifacts(f);
306
+ });
307
+
308
+ test('calibration failure with stale calibration does not complete a damaged stage', { skip: skipNoColabCli }, async t => {
309
+ const f = fixture(t);
310
+ assert.equal(run(f, ['--session', 'fake-session']).status, 0);
311
+ const intent = stageDir(f, 'intent');
312
+ fs.rmSync(path.join(intent, 'harness-routing-v1.json'));
313
+ f.env.FAKE_COLAB_BAD_CATALOG = 'intent';
314
+
315
+ const failed = run(f, ['--session', 'fake-session']);
316
+ assert.notEqual(failed.status, 0);
317
+ assert.ok(failed.stderr.length);
318
+ assert.equal(fs.existsSync(path.join(intent, 'calibration.json')), true);
319
+ assert.equal(fs.existsSync(path.join(intent, 'harness-routing-v1.json')), false);
320
+ await assertIntentRetryReachesTrainCycle(f);
321
+
322
+ delete f.env.FAKE_COLAB_BAD_CATALOG;
323
+ const repaired = run(f, ['--session', 'fake-session']);
324
+ assert.equal(repaired.status, 0, repaired.stderr);
325
+ assert.match(repaired.stdout, /"trained":1,"skipped":2/);
326
+ assert.equal((await trainCycle({ dataDir: f.dataDir, version: 'synthetic-v1' })).skipped, 3);
327
+ });
328
+
329
+ test('stale remote status from a failed invocation is rejected despite matching old artifacts', { skip: skipNoColabCli }, t => {
330
+ const f = fixture(t);
331
+ const first = run(f, ['--session', 'fake-session']);
332
+ assert.equal(first.status, 0, first.stderr);
333
+ const statusFile = path.join(f.fakeRoot, 'runs', 'synthetic-v1', 'intent', 'remote-status.json');
334
+ const prior = JSON.parse(fs.readFileSync(statusFile, 'utf8'));
335
+ fs.rmSync(path.join(stageDir(f, 'intent'), 'harness-routing-v1.json'));
336
+ f.env.FAKE_COLAB_FAIL_TASK = 'intent';
337
+
338
+ const failed = run(f, ['--session', 'fake-session']);
339
+ assert.notEqual(failed.status, 0);
340
+ assert.match(failed.stderr, /status identity mismatch/);
341
+ assert.equal(JSON.parse(fs.readFileSync(statusFile, 'utf8')).invocationId, prior.invocationId);
342
+ });
343
+
344
+ test('current invocation with a mismatched status manifest digest is rejected', { skip: skipNoColabCli }, t => {
345
+ const f = fixture(t);
346
+ f.env.FAKE_COLAB_STATUS_MANIFEST_SHA256 = '0'.repeat(64);
347
+ const failed = run(f, ['--session', 'fake-session']);
348
+
349
+ assert.notEqual(failed.status, 0);
350
+ assert.match(failed.stderr, /status identity mismatch/);
351
+ const status = JSON.parse(fs.readFileSync(path.join(f.fakeRoot, 'runs', 'synthetic-v1', 'validity', 'remote-status.json'), 'utf8'));
352
+ const uploadedManifestSha256 = logRows(f).find(row => row.uploadedManifestSha256).uploadedManifestSha256;
353
+ assert.match(status.invocationId, /^[0-9a-f-]{36}$/);
354
+ assert.notEqual(status.manifestSha256, uploadedManifestSha256);
355
+ assert.equal(fs.existsSync(path.join(stageDir(f, 'validity'), 'resource-guard.json')), false);
356
+ });
357
+
358
+ test('remote runner rejects a self-consistent substituted manifest before starting training', { skip: skipNoColabCli }, t => {
359
+ const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-colab-runner-')));
360
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
361
+ const inputs = path.join(root, 'training', 'v1', 'prompts.jsonl');
362
+ fs.mkdirSync(path.dirname(inputs), { recursive: true });
363
+ fs.writeFileSync(inputs, 'substituted input\n');
364
+ const digest = body => crypto.createHash('sha256').update(body).digest('hex');
365
+ const original = { schemaVersion: 1, files: [{ path: 'training/v1/prompts.jsonl', sha256: digest('original input\n') }] };
366
+ const substituted = { schemaVersion: 1, files: [{ path: 'training/v1/prompts.jsonl', sha256: digest('substituted input\n') }] };
367
+ const expectedManifestSha256 = digest(`${JSON.stringify(original, null, 2)}\n`);
368
+ fs.writeFileSync(path.join(root, 'bundle-manifest.json'), `${JSON.stringify(substituted, null, 2)}\n`);
369
+ const trainer = path.join(root, 'trainer.py');
370
+ const marker = path.join(root, 'training-started');
371
+ fs.writeFileSync(trainer, `from pathlib import Path\nPath(${JSON.stringify(marker)}).write_text('started')\n`);
372
+ const script = remoteRunner({ version: 'synthetic-v1', task: 'intent', device: 'cpu', invocationId: 'new-call', expectedManifestSha256 })
373
+ .replace("pathlib.Path('/content')", `pathlib.Path(${JSON.stringify(root)})`)
374
+ .replace(JSON.stringify('/content/scripts/system-one-train.py'), JSON.stringify(trainer));
375
+ const runner = path.join(root, 'runner.py');
376
+ fs.writeFileSync(runner, script);
377
+
378
+ const result = spawnSync('python3', [runner], { encoding: 'utf8' });
379
+ assert.ifError(result.error);
380
+ assert.notEqual(result.status, 0);
381
+ assert.match(result.stderr, /bundle-manifest-mismatch/);
382
+ assert.equal(fs.existsSync(marker), false);
383
+ });
384
+
385
+ test('publication failure after replacement removes the stale success guard and permits retry', { skip: skipNoColabCli }, async t => {
386
+ const f = fixture(t);
387
+ assert.equal(run(f, ['--session', 'fake-session']).status, 0);
388
+ const intent = stageDir(f, 'intent');
389
+ fs.rmSync(path.join(intent, 'harness-routing-v1.json'));
390
+ makePublicationFailure(f);
391
+
392
+ const failed = run(f, ['--session', 'fake-session']);
393
+ assert.notEqual(failed.status, 0);
394
+ assert.match(failed.stderr, /injected-final-publication-failure/);
395
+ assert.deepEqual(fs.readFileSync(f.env.FAKE_COLAB_PUBLISH_LOG, 'utf8').trim().split(/\r?\n/),
396
+ ['harness-routing-v1.safetensors', 'harness-routing-v1.json']);
397
+ assert.equal(fs.existsSync(path.join(intent, 'resource-guard.json')), false);
398
+ assert.equal(fs.existsSync(path.join(stageDir(f, 'validity'), 'resource-guard.json')), true);
399
+ await assertIntentRetryReachesTrainCycle(f);
400
+
401
+ delete f.env.FAKE_COLAB_FAIL_PUBLISH;
402
+ const repaired = run(f, ['--session', 'fake-session']);
403
+ assert.equal(repaired.status, 0, repaired.stderr);
404
+ assert.match(repaired.stdout, /"trained":1,"skipped":2/);
405
+ assert.equal((await trainCycle({ dataDir: f.dataDir, version: 'synthetic-v1' })).skipped, 3);
406
+ });
407
+
408
+ test('download failure still stops the Colab session', { skip: skipNoColabCli }, t => {
409
+ const f = fixture(t);
410
+ f.env.FAKE_COLAB_FAIL_DOWNLOAD = '/content/runs/synthetic-v1/validity/harness-routing-v1.safetensors';
411
+ const result = run(f);
412
+ assert.notEqual(result.status, 0);
413
+ const rows = logRows(f);
414
+ assert.equal(rows.at(-1).argv[0], 'stop');
415
+ assert.equal(rows.filter(row => row.argv[0] === 'exec').length, 2);
416
+ });
417
+
418
+ test('trainer and stop failures both reach the CLI with an actionable manual stop command', { skip: skipNoColabCli }, t => {
419
+ const f = fixture(t);
420
+ f.env.FAKE_COLAB_FAIL_TASK = 'validity';
421
+ f.env.FAKE_COLAB_FAIL_STOP = '1';
422
+ const result = run(f, ['--session', 'session-563']);
423
+
424
+ assert.notEqual(result.status, 0);
425
+ assert.match(result.stderr, /trainer-failed/);
426
+ assert.match(result.stderr, /injected-stop-failure/);
427
+ assert.match(result.stderr, /session id: session-563/i);
428
+ assert.match(result.stderr, /colab stop -s session-563/);
429
+ assert.equal(logRows(f).at(-1).argv.join(' '), 'stop -s session-563');
430
+ });
431
+
432
+ test('allow-listed input symlinks cannot redirect private raw data to the Colab bundle', t => {
433
+ if (process.platform === 'win32') { t.skip('Windows symlink creation depends on host privileges'); return; }
434
+ const f = fixture(t);
435
+ const allowedPrompt = path.join(f.dataDir, 'training/v1/prompts.jsonl');
436
+ fs.rmSync(allowedPrompt);
437
+ fs.symlinkSync(path.join(f.dataDir, 'training/observed/prompts-observed.jsonl'), allowedPrompt);
438
+ const result = run(f);
439
+ assert.notEqual(result.status, 0);
440
+ assert.match(result.stderr, /invalid allow-listed file training\/v1\/prompts.jsonl/);
441
+ assert.equal(fs.existsSync(f.log), false);
442
+ });
443
+
444
+ test('invalid GPU input is rejected before contacting Colab', t => {
445
+ const f = fixture(t);
446
+ const result = run(f, ['--gpu', 'H100']);
447
+ assert.notEqual(result.status, 0);
448
+ assert.match(result.stderr, /--gpu must be T4, L4, or A100/);
449
+ assert.equal(fs.existsSync(f.log), false);
450
+ });
@@ -12,6 +12,32 @@ trainer = importlib.util.module_from_spec(spec)
12
12
  spec.loader.exec_module(trainer)
13
13
  assert 'torch' not in sys.modules, 'importing the trainer must not import torch'
14
14
 
15
+ device_cases = [
16
+ ('cpu', False, 'cpu'),
17
+ ('cpu', True, 'cpu'),
18
+ ('auto', True, 'cuda'),
19
+ ('auto', False, 'cpu'),
20
+ ('cuda', True, 'cuda'),
21
+ ]
22
+ for requested, cuda_available, expected in device_cases:
23
+ assert trainer.resolve_device(requested, cuda_available) == expected, (requested, cuda_available)
24
+ try:
25
+ trainer.resolve_device('cuda', False)
26
+ raise AssertionError('cuda without an available device must fail')
27
+ except ValueError as exc:
28
+ assert 'CUDA' in str(exc) and 'unavailable' in str(exc), exc
29
+ try:
30
+ trainer.resolve_device('unknown', False)
31
+ raise AssertionError('unknown device must fail')
32
+ except ValueError:
33
+ pass
34
+ try:
35
+ trainer.main(['--data-dir', 'unused', '--out', 'unused', '--device', 'unknown'])
36
+ raise AssertionError('argparse must reject an unknown device')
37
+ except SystemExit as exc:
38
+ assert exc.code == 2, exc.code
39
+ print('PASS device resolution: cpu, auto, cuda availability and invalid choices')
40
+
15
41
  tier_catalog = trainer.catalog_for('tier')
16
42
  intent_catalog = trainer.catalog_for('intent')
17
43
  validity_catalog = trainer.catalog_for('validity')
@@ -36,6 +36,16 @@ flowchart LR
36
36
 
37
37
  ¹ Durations are planning estimates, not measurements from this checkout. Model latency and dataset size vary.
38
38
 
39
+ ## Train on Colab
40
+
41
+ The owner can start the same ordered training stages on a Colab VM from the local private cycle directory:
42
+
43
+ ```sh
44
+ node scripts/system-one-colab.js --data-dir "<private-cycle-dir>" --version <version-id> [--gpu T4|L4|A100]
45
+ ```
46
+
47
+ CPU is the default. `--gpu` selects the Colab GPU and passes `--device cuda`; CUDA runs need not be bit-identical to CPU runs. The launcher creates the remote bundle directories, then uploads only the built `training/v1/` and `training/v1-validity/` trainer inputs, the public trainer, and the two public holdout catalogs. It sends a SHA-256 manifest and checks every uploaded file on the VM before each stage. After training, the VM writes a status record with hashes for that stage's outputs; the launcher downloads the record first and verifies each downloaded file against it. Raw observations, relabels, adjudication, history, and private holdouts stay local. Each finished stage is downloaded and calibrated locally before the next task starts. Completed stages are reused on the next invocation, including after a later task fails. The launcher always attempts to stop the VM; if stopping fails, its diagnostic, the session ID, and a manual stop command are included in the CLI error. Set `COLAB_BIN` or pass `--colab` to use a different CLI binary, and optionally pass `--session` to choose its session name.
48
+
39
49
  F6 extends per-stage manifest metadata with `referenceOnly`; it does not
40
50
  authorize an additional top-level `workflowPlan.systemOne` field. The routing
41
51
  guide records the separate H1b output enrichment and the unresolved output
@@ -176,10 +176,12 @@ prompts written by an agent, not by the owner. VS Code terminal notifications
176
176
  `labels-intent.jsonl` rows and the fixed intent catalog; its hard target is multi-hot for
177
177
  `gold` plus `secondary`. With `--target scores`, each intent's value from
178
178
  `labels-intent-scores.jsonl` is its soft target.
179
- - **Optimization**: per-option binary cross-entropy with logits, AdamW, a fixed seed and CPU.
179
+ - **Optimization**: per-option binary cross-entropy with logits, AdamW, a fixed seed and `--device {cpu,cuda,auto}` (default `cpu`).
180
180
  Validation applies sigmoid independently to each option; `val-scores.jsonl` stores rows as
181
181
  `{id, gold, scores: {option: probability}}`; option probabilities are independent and do
182
182
  not have to sum to one.
183
+ - `auto` selects CUDA when available; requesting unavailable CUDA exits with an error. The
184
+ resolved device and PyTorch version are recorded in checkpoint metadata and `train-report.json`.
183
185
  - The epoch with the lowest validation negative log-likelihood is kept.
184
186
  - The checkpoint metadata records the dataset hashes, the config and the validation metrics.
185
187
  - **Calibration**: `minConfidence` and `minMargin` are chosen on validation to maximize
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "1.3.2",
4
+ "version": "1.4.0",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "harness-everything",
4
- "version": "1.3.2",
4
+ "version": "1.4.0",
5
5
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
6
6
  "author": {
7
7
  "name": "Miya Daniel",
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:139b81da-ebff-5b43-a38a-a0c07d11060a",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-28T07:15:24.159Z",
8
+ "timestamp": "2026-11-29T16:25:49.796Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "1.3.2"
13
+ "version": "1.4.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.4.0",
19
19
  "name": "harness-everything",
20
- "version": "1.3.2",
21
- "purl": "pkg:npm/harness-everything@1.3.2"
20
+ "version": "1.4.0",
21
+ "purl": "pkg:npm/harness-everything@1.4.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.4.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,238 @@
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 } = 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
+ const guard = JSON.parse(fs.readFileSync(path.join(dir, 'resource-guard.json'), 'utf8'));
54
+ return guard.exitCode === 0 && !guard.killedForLimit && !guard.monitorFailed;
55
+ }
56
+
57
+ function writeJsonAtomic(file, value) {
58
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${crypto.randomUUID()}.tmp`);
59
+ try {
60
+ writeJson(temporary, value);
61
+ fs.renameSync(temporary, file);
62
+ } finally {
63
+ fs.rmSync(temporary, { force: true });
64
+ }
65
+ }
66
+
67
+ function outputTail(result) {
68
+ return `${result.stdout || ''}${result.stderr || ''}`.trim().split(/\r?\n/).slice(-20).join('\n');
69
+ }
70
+
71
+ function command(bin, args, { ignoreStatus = false } = {}) {
72
+ const result = spawnSync(bin, args, { cwd: REPO, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
73
+ if (result.error || (!ignoreStatus && result.status !== 0)) {
74
+ const tail = outputTail(result);
75
+ throw new Error(`colab ${args[0]} failed${tail ? `\n${tail}` : ''}`);
76
+ }
77
+ return result;
78
+ }
79
+
80
+ function remoteRunner({ version, task, device, invocationId, expectedManifestSha256 }) {
81
+ const trainer = '/content/scripts/system-one-train.py';
82
+ const source = task === 'validity' ? '/content/training/v1-validity' : '/content/training/v1';
83
+ const output = `/content/runs/${version}/${task}`;
84
+ const holdout = task === 'intent'
85
+ ? '/content/benchmarks/fixtures/system-one-intent-holdout.json'
86
+ : '/content/benchmarks/fixtures/system-one-holdout.json';
87
+ const holdoutArgs = task === 'validity' ? '' : `, '--holdout', ${JSON.stringify(holdout)}`;
88
+ 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`;
89
+ }
90
+
91
+ function prepareRunner(files, version) {
92
+ const dirs = [...new Set([
93
+ ...files.map(file => `/content/${path.posix.dirname(file)}`),
94
+ `/content/runs/${version}`,
95
+ ])];
96
+ return `import os\nPATHS = ${JSON.stringify(dirs)}\nfor item in PATHS:\n os.makedirs(item, exist_ok=True)\n`;
97
+ }
98
+
99
+ function main(argv) {
100
+ const flags = parseFlags(argv);
101
+ if (flag(flags, 'help') === true) { process.stdout.write(`${USAGE}\n`); return; }
102
+ const allowedFlags = new Set(['data-dir', 'version', 'gpu', 'session', 'colab']);
103
+ for (const key of Object.keys(flags)) if (!allowedFlags.has(key)) throw new Error(`unknown option --${key}`);
104
+ const dataDir = assertPrivateDataDir(path.resolve(required(flags, 'data-dir')));
105
+ const version = validateVersion(required(flags, 'version'));
106
+ const gpu = flag(flags, 'gpu');
107
+ if (gpu !== undefined && !['T4', 'L4', 'A100'].includes(gpu)) throw new Error('--gpu must be T4, L4, or A100');
108
+ const device = gpu ? 'cuda' : 'cpu';
109
+ const session = flag(flags, 'session', `system-one-${version}-${process.pid}`);
110
+ 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');
111
+ const colab = flag(flags, 'colab', process.env.COLAB_BIN || 'colab');
112
+ if (typeof colab !== 'string' || !colab.trim()) throw new Error('--colab must name a binary');
113
+ const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
114
+ const stageDirs = Object.fromEntries(TASKS.map(task => [task, dataPath(dataDir, 'training', 'runs', version, task)]));
115
+ const tasks = TASKS.filter(task => !completeStage(stageDirs[task]));
116
+ if (!tasks.length) {
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
+ runNode(calibrator, [path.join(staging, 'val-scores.jsonl'), path.join(staging, 'calibration.json'), '--task', task,
204
+ '--catalog', path.join(staging, 'train-report.json')]);
205
+ fs.mkdirSync(out, { recursive: true, mode: 0o700 });
206
+ fs.rmSync(path.join(out, 'resource-guard.json'), { force: true });
207
+ for (const file of PUBLISH_STAGE_FILES) fs.renameSync(path.join(staging, file), path.join(out, file));
208
+ writeJsonAtomic(path.join(out, 'resource-guard.json'), guard);
209
+ if (interrupted) throw new Error(`interrupted by ${interrupted}`);
210
+ } finally {
211
+ fs.rmSync(staging, { recursive: true, force: true });
212
+ }
213
+ }
214
+ } catch (error) {
215
+ failure = error;
216
+ } finally {
217
+ try { command(colab, ['stop', '-s', session]); }
218
+ catch (error) {
219
+ const cleanup = `Colab stop failed: ${error.message}\nSession ID: ${session}\nManual stop command: colab stop -s ${session}`;
220
+ failure = failure ? new Error(`${failure.message}\n${cleanup}`) : new Error(cleanup);
221
+ }
222
+ fs.rmSync(tempDir, { recursive: true, force: true });
223
+ for (const signal of ['SIGINT', 'SIGTERM']) {
224
+ process.removeListener(signal, signalHandlers[signal]);
225
+ }
226
+ }
227
+ if (failure) throw failure;
228
+ const hashes = manifest.files.map(({ path: file, sha256: hash }) => ({ path: file, sha256: hash }));
229
+ process.stdout.write(`${JSON.stringify({ version, trained: tasks.length, skipped: TASKS.length - tasks.length,
230
+ gpu: gpu || null, device, session, uploaded: files.length + 1, manifestSha256: manifestDigest, files: hashes })}\n`);
231
+ }
232
+
233
+ if (require.main === module) {
234
+ try { main(process.argv.slice(2)); }
235
+ catch (error) { process.stderr.write(`system-one-colab: ${error.message}\n`); process.exitCode = 1; }
236
+ }
237
+
238
+ module.exports = { main, remoteRunner, completeStage };
@@ -120,13 +120,33 @@ def make_batches(lengths, token_budget, n_options, option_tokens):
120
120
  return batches
121
121
 
122
122
 
123
+ def resolve_device(requested, cuda_available):
124
+ """Resolve a requested training device without importing torch."""
125
+ if requested == 'cpu':
126
+ return 'cpu'
127
+ if requested == 'auto':
128
+ return 'cuda' if cuda_available else 'cpu'
129
+ if requested == 'cuda':
130
+ if cuda_available:
131
+ return 'cuda'
132
+ raise ValueError('CUDA was requested but is unavailable')
133
+ raise ValueError(f'unknown device: {requested!r}')
134
+
135
+
123
136
  def train(args):
124
137
  import torch
125
138
  from cua_s1.model import ChoiceExample, make_system, save_checkpoint
126
139
 
140
+ try:
141
+ device = resolve_device(args.device, torch.cuda.is_available())
142
+ except ValueError as exc:
143
+ raise SystemExit(f'error: {exc}') from None
127
144
  random.seed(args.seed)
128
145
  torch.manual_seed(args.seed)
129
- torch.set_num_threads(max(1, args.threads))
146
+ if device == 'cuda':
147
+ torch.cuda.manual_seed_all(args.seed)
148
+ else:
149
+ torch.set_num_threads(max(1, args.threads))
130
150
  data_dir = Path(args.data_dir)
131
151
  catalog = catalog_for(args.task, args.holdout)
132
152
  labels_file = ('labels-intent-scores.jsonl' if args.target == 'scores' else 'labels-intent.jsonl') \
@@ -136,7 +156,10 @@ def train(args):
136
156
  split = {name: [e for e in examples if e['split'] == name] for name in ('train', 'validation')}
137
157
  config = {'encoder': 'tinyx', 'width': 128, 'rank': 128, 'layers': 2, 'heads': 4, 'dropout': 0.1,
138
158
  'context_tokens': args.context_tokens, 'option_tokens': OPTION_TOKENS}
139
- model, collator = make_system(config, 'cpu')
159
+ model, collator = make_system(config, device)
160
+
161
+ def collate(rows):
162
+ return {name: tensor.to(device) for name, tensor in collator(rows).items()}
140
163
 
141
164
  def to_examples(rows):
142
165
  examples = []
@@ -160,9 +183,9 @@ def train(args):
160
183
  nll, correct, probs = 0.0, 0, [None] * len(val_x)
161
184
  with torch.inference_mode():
162
185
  for batch in val_batches:
163
- tensors = collator([val_x[i] for i in batch])
186
+ tensors = collate([val_x[i] for i in batch])
164
187
  logits = model(tensors)
165
- targets = val_targets[batch]
188
+ targets = val_targets[batch].to(device)
166
189
  nll += torch.nn.functional.binary_cross_entropy_with_logits(logits, targets, reduction='sum').item()
167
190
  p = logits.sigmoid()
168
191
  correct += ((p >= 0.5) == targets.bool()).all(dim=-1).sum().item()
@@ -179,8 +202,9 @@ def train(args):
179
202
  total = 0.0
180
203
  for b in order:
181
204
  batch = train_batches[b]
182
- tensors = collator([train_x[i] for i in batch])
183
- loss = torch.nn.functional.binary_cross_entropy_with_logits(model(tensors), train_targets[batch])
205
+ tensors = collate([train_x[i] for i in batch])
206
+ targets = train_targets[batch].to(device)
207
+ loss = torch.nn.functional.binary_cross_entropy_with_logits(model(tensors), targets)
184
208
  optimizer.zero_grad()
185
209
  loss.backward()
186
210
  torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
@@ -191,7 +215,7 @@ def train(args):
191
215
  print(json.dumps(history[-1]), flush=True)
192
216
  if best is None or metrics['nll'] < best['metrics']['nll']:
193
217
  best = {'epoch': epoch, 'metrics': metrics, 'scores': probs,
194
- 'state': {k: v.detach().clone() for k, v in model.state_dict().items()}}
218
+ 'state': {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}}
195
219
 
196
220
  model.load_state_dict(best['state'])
197
221
  out = Path(args.out)
@@ -199,7 +223,8 @@ def train(args):
199
223
  datasets = {name: sha256_file(data_dir / name) for name in ('prompts.jsonl', labels_file)}
200
224
  metadata = {'domain': 'harness-routing-v1', 'bestEpoch': best['epoch'], 'validation': best['metrics'],
201
225
  'datasets': datasets, 'seed': args.seed, 'catalog': [o['id'] for o in catalog],
202
- 'task': args.task, 'target': args.target, 'loss': 'binary_cross_entropy'}
226
+ 'task': args.task, 'target': args.target, 'loss': 'binary_cross_entropy',
227
+ 'device': device, 'torch': torch.__version__}
203
228
  save_checkpoint(out / 'harness-routing-v1.safetensors', model, config, metadata)
204
229
  with (out / 'val-scores.jsonl').open('w', encoding='utf-8') as fh:
205
230
  for row, scores in zip(split['validation'], best['scores']):
@@ -207,7 +232,7 @@ def train(args):
207
232
  counts = {name: len(rows) for name, rows in split.items()}
208
233
  report = {'schemaVersion': 1, 'config': config, 'counts': counts, 'bestEpoch': best['epoch'], 'history': history,
209
234
  'datasets': datasets, 'seed': args.seed, 'task': args.task, 'target': args.target,
210
- 'catalog': [o['id'] for o in catalog]}
235
+ 'catalog': [o['id'] for o in catalog], 'device': device, 'torch': torch.__version__}
211
236
  (out / 'train-report.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
212
237
  print(json.dumps({'counts': counts, 'bestEpoch': best['epoch'], 'validation': best['metrics']}))
213
238
 
@@ -221,6 +246,8 @@ def main(argv=None):
221
246
  parser.add_argument('--lr', type=float, default=1e-3)
222
247
  parser.add_argument('--seed', type=int, default=7)
223
248
  parser.add_argument('--threads', type=int, default=4)
249
+ parser.add_argument('--device', choices=['cpu', 'cuda', 'auto'], default='cpu',
250
+ help='training device (auto selects CUDA when available)')
224
251
  parser.add_argument('--context-tokens', type=int, default=1024)
225
252
  parser.add_argument('--token-budget', type=int, default=TOKEN_BUDGET,
226
253
  help='whole-forward-pass tokens per batch (prompt plus every option)')