harness-everything 1.3.1 → 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.
Files changed (109) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/release.yml +7 -1
  4. package/AGENTS.md +1 -1
  5. package/CHANGELOG.md +25 -0
  6. package/RELEASING.md +2 -0
  7. package/behavioral-evals/ledger-pairs/README.md +53 -0
  8. package/behavioral-evals/ledger-pairs/arm.js +359 -0
  9. package/behavioral-evals/ledger-pairs/fixture.js +138 -0
  10. package/behavioral-evals/ledger-pairs/preflight.js +96 -0
  11. package/behavioral-evals/ledger-pairs/score.js +155 -0
  12. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/README.md +108 -0
  13. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-plan.json +14 -0
  14. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-result.json +35 -0
  15. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-plan.json +14 -0
  16. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-result.json +35 -0
  17. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-plan.json +14 -0
  18. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-result.json +35 -0
  19. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-plan.json +14 -0
  20. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-result.json +35 -0
  21. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-plan.json +14 -0
  22. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-result.json +35 -0
  23. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-plan.json +14 -0
  24. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-result.json +35 -0
  25. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-plan.json +14 -0
  26. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-result.json +28 -0
  27. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-plan.json +14 -0
  28. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-result.json +35 -0
  29. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-plan.json +13 -0
  30. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-result.json +56 -0
  31. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-plan.json +13 -0
  32. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-result.json +56 -0
  33. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-plan.json +13 -0
  34. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-result.json +56 -0
  35. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-plan.json +13 -0
  36. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-result.json +56 -0
  37. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-plan.json +13 -0
  38. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-result.json +49 -0
  39. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-plan.json +13 -0
  40. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-result.json +49 -0
  41. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-plan.json +13 -0
  42. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-result.json +49 -0
  43. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-plan.json +13 -0
  44. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-result.json +56 -0
  45. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-plan.json +14 -0
  46. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-result.json +44 -0
  47. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/receipt.jsonl +17 -0
  48. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-plan.json +14 -0
  49. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-result.json +41 -0
  50. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/receipt.jsonl +58 -0
  51. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-plan.json +14 -0
  52. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-result.json +50 -0
  53. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/receipt.jsonl +101 -0
  54. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-plan.json +14 -0
  55. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-result.json +44 -0
  56. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/receipt.jsonl +29 -0
  57. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-plan.json +14 -0
  58. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-result.json +44 -0
  59. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/receipt.jsonl +23 -0
  60. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-plan.json +14 -0
  61. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-result.json +34 -0
  62. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/receipt.jsonl +24 -0
  63. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-plan.json +14 -0
  64. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-result.json +47 -0
  65. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/receipt.jsonl +69 -0
  66. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-plan.json +14 -0
  67. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-result.json +44 -0
  68. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/receipt.jsonl +65 -0
  69. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/run-order.sh +18 -0
  70. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/score.json +1032 -0
  71. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/README.md +50 -0
  72. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/collect-rerun.txt +3 -0
  73. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/export-report.json +22 -0
  74. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/host-version.txt +1 -0
  75. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-1.json +18 -0
  76. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-2.json +18 -0
  77. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/labels-observed-excerpt.jsonl +2 -0
  78. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/observations-index-excerpt.json +26 -0
  79. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/plugin-load-lines.txt +1 -0
  80. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/README.md +46 -0
  81. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/observations-index-excerpt.json +16 -0
  82. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/plugin-load-lines.txt +2 -0
  83. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/run-marks.txt +6 -0
  84. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-probe.js +16 -0
  85. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-trace.jsonl +167 -0
  86. package/ci/mechanism-332-fable-directive.test.js +180 -0
  87. package/ci/mechanism-552-ledger-pairs.test.js +159 -0
  88. package/ci/mechanism-system-one-colab.test.js +450 -0
  89. package/ci/router-workflow-plan.test.js +61 -21
  90. package/ci/system-one-train-test.py +26 -0
  91. package/docs/platform-capabilities.md +28 -11
  92. package/docs/platform-compatibility.json +5 -5
  93. package/docs/system-one-cycle.md +10 -0
  94. package/docs/system-one-training.md +3 -1
  95. package/harness-everything/SKILL.md +1 -1
  96. package/harness-everything/scripts/routing-keywords.json +0 -2
  97. package/harness-everything/scripts/tier-router.js +105 -11
  98. package/opencode-plugin/plugin.json +1 -1
  99. package/package.json +1 -1
  100. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  101. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  102. package/plugins/harness-everything/plugin.json +1 -1
  103. package/plugins/harness-everything/rules/AGENTS.md +1 -1
  104. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  105. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +0 -2
  106. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +105 -11
  107. package/sbom.cdx.json +7 -7
  108. package/scripts/system-one-colab.js +238 -0
  109. package/scripts/system-one-train.py +36 -9
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:4f2e0546-4270-5672-87de-db09e81f50a4",
5
+ "serialNumber": "urn:uuid:139b81da-ebff-5b43-a38a-a0c07d11060a",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-28T01:10:17.078Z",
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.1"
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.1",
18
+ "bom-ref": "pkg:npm/harness-everything@1.4.0",
19
19
  "name": "harness-everything",
20
- "version": "1.3.1",
21
- "purl": "pkg:npm/harness-everything@1.3.1"
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.1",
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)')