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
@@ -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
+ });
@@ -339,23 +339,39 @@ for (const prompt of [
339
339
  check(JSON.stringify(lookup.contract) === JSON.stringify(repeat.contract), `${prompt}: lookup contract is deterministic`);
340
340
  }
341
341
  }
342
+ // A profile lookup followed by an independent task must route exactly like the task alone.
343
+ for (const [prompt, taskOnly] of [
344
+ ['Explain fable on opus and then implement a repository-wide migration.', 'Implement a repository-wide migration.'],
345
+ ['Explain fable on sonnet and analyze the authentication design.', 'Analyze the authentication design.'],
346
+ ['Explain fable on sonnet; then send the findings to Slack.', 'Send the findings to Slack.'],
347
+ ['Explain fable on sonnet and update README.', 'Update README.'],
348
+ ['Explain fable on haiku, add a regression test.', 'Add a regression test.'],
349
+ ['Explain fable on opus and commit the documentation change.', 'Commit the documentation change.'],
350
+ ['說明 fable on sonnet 並更新 README。', '更新 README。'],
351
+ ['解釋 fable on haiku,新增回歸測試。', '新增回歸測試。'],
352
+ ['解析 fable on opus 並刪除過期文件。', '刪除過期文件。'],
353
+ ['Explain fable on sonnet before updating README.', 'updating README.'],
354
+ ['Explain fable on sonnet; return JSON after updating README.', 'after updating README.'],
355
+ ["Explain fable on sonnet before updating README.md to change 'Instalation' to 'Installation'.", "updating README.md to change 'Instalation' to 'Installation'."],
356
+ ['解釋 fable on sonnet 後更新 README。', '更新 README。'],
357
+ ]) {
358
+ const withMention = runTier(prompt);
359
+ const withoutMention = runTier(taskOnly);
360
+ if (validContract(withMention, 'profile mention plus independent task') &&
361
+ validContract(withoutMention, 'task without profile mention')) {
362
+ const actual = withMention.contract.workflowPlan;
363
+ const control = withoutMention.contract.workflowPlan;
364
+ check(!actual.reasonCodes.includes('fable-profile-lookup'), `${prompt}: mixed task is not a bounded lookup`);
365
+ check(actual.tier === control.tier, `${prompt}: tier matches the task-only real-entry control`);
366
+ check(actual.strategy === control.strategy, `${prompt}: strategy matches the task-only real-entry control`);
367
+ check(actual.requiredInvariants.includes('isolated-worktree-before-mutation') ===
368
+ control.requiredInvariants.includes('isolated-worktree-before-mutation'),
369
+ `${prompt}: isolation obligation matches the task-only real-entry control`);
370
+ }
371
+ }
372
+
373
+ // Mixed, unknown-continuation and negation-then-action inputs never become lookups.
342
374
  for (const prompt of [
343
- 'Use fable on sonnect to implement a multi-stage architecture migration.',
344
- 'Explain fable on opus and then implement a repository-wide migration.',
345
- 'Explain how to run fable-staged across all modules.',
346
- 'Explain fable on sonnet then run it to analyze security.',
347
- 'Explain fable on sonnet and analyze the authentication design.',
348
- 'Explain fable on sonnet; then send the findings to Slack.',
349
- 'Explain fable on sonnet and update README.',
350
- 'Explain fable on haiku, add a regression test.',
351
- 'Explain fable on opus and commit the documentation change.',
352
- '說明 fable on sonnet 並更新 README。',
353
- '解釋 fable on haiku,新增回歸測試。',
354
- '解析 fable on opus 並刪除過期文件。',
355
- 'Explain fable on sonnet before updating README.',
356
- 'Explain fable on sonnet; return JSON after updating README.',
357
- "Explain fable on sonnet before updating README.md to change 'Instalation' to 'Installation'.",
358
- '解釋 fable on sonnet 後更新 README。',
359
375
  'Explain fable on sonnet; no delegation before deleting stale files.',
360
376
  'Explain fable on sonnet; return JSON with requestedProfile, update README.',
361
377
  'Explain fable on sonnet; output JSON with requestedProfile and then publish the result.',
@@ -364,7 +380,6 @@ for (const prompt of [
364
380
  'Explain fable on sonnet; provide a profile result while running the tests.',
365
381
  'Explain fable on sonnet; return JSON with unknownField.',
366
382
  'Explain fable on sonnet; some unknown continuation.',
367
- // A negation scopes only its own noun list; affirmative actions after it execute.
368
383
  'Explain fable on sonnet; no delegation, do execution.',
369
384
  'Explain fable on sonnet; no delegation, switch model.',
370
385
  'Explain fable on sonnet; no delegation and stage execution.',
@@ -374,13 +389,38 @@ for (const prompt of [
374
389
  '解釋 fable on sonnet,不要委派,切換模型。',
375
390
  ]) {
376
391
  const execution = runTier(prompt);
377
- if (validContract(execution, 'Fable execution boundary')) {
378
- check(execution.contract.workflowPlan.strategy === 'fable-staged', 'execution/macro scope preserves staged topology');
379
- check(!execution.contract.workflowPlan.reasonCodes.includes('fable-profile-lookup'), 'mixed execution never records the bounded lookup reason');
380
- check(execution.contract.workflowPlan.requiredInvariants.includes('isolated-worktree-before-mutation'), 'execution retains isolation obligation');
392
+ if (validContract(execution, 'mixed Fable lookup/action boundary')) {
393
+ check(!execution.contract.workflowPlan.reasonCodes.includes('fable-profile-lookup'),
394
+ `${prompt}: mixed action is not a bounded lookup`);
381
395
  }
382
396
  }
383
397
 
398
+ // Explicit Fable, structural Tier 3 and the one unambiguous linked continuation keep staged routing.
399
+ for (const prompt of [
400
+ 'Use fable on sonnect to implement a multi-stage architecture migration.',
401
+ 'Explain how to run fable-staged across all modules.',
402
+ 'Explain fable on sonnet then run it to analyze security.',
403
+ ]) {
404
+ const execution = runTier(prompt);
405
+ if (validContract(execution, 'true Fable execution boundary')) {
406
+ check(execution.contract.workflowPlan.strategy === 'fable-staged', `${prompt}: staged topology remains`);
407
+ check(!execution.contract.workflowPlan.reasonCodes.includes('fable-profile-lookup'), `${prompt}: execution is not a lookup`);
408
+ check(execution.contract.workflowPlan.requiredInvariants.includes('isolated-worktree-before-mutation'),
409
+ `${prompt}: execution retains isolation obligation`);
410
+ if (prompt === 'Explain fable on sonnet then run it to analyze security.') {
411
+ check(execution.result.stdout.includes('REQUESTED FABLE PROFILE: sonnet'),
412
+ 'profile-linked continuation preserves the selected sonnet profile');
413
+ }
414
+ }
415
+ }
416
+ const ambiguousLinkedProfile = runTier('Explain fable on opus or sonnet then run it to analyze security.');
417
+ if (validContract(ambiguousLinkedProfile, 'ambiguous profile continuation')) {
418
+ check(ambiguousLinkedProfile.contract.workflowPlan.strategy !== 'fable-staged',
419
+ 'ambiguous profile continuation follows normal routing');
420
+ check(!ambiguousLinkedProfile.result.stdout.includes('REQUESTED FABLE PROFILE'),
421
+ 'ambiguous profile continuation does not choose a profile');
422
+ }
423
+
384
424
  const explicitOverride = runTier('Use iterative-single to audit the entire repository architecture.');
385
425
  if (validContract(explicitOverride, 'explicit strategy override')) {
386
426
  check(explicitOverride.contract.workflowPlan.strategy === 'iterative-single', 'explicit user strategy overrides derived Tier 3 topology');
@@ -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')