harness-everything 0.51.0 → 0.53.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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +23 -0
  4. package/CHANGELOG.md +54 -0
  5. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
  6. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
  7. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
  8. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
  9. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
  10. package/ci/mechanism-2am-observations-session-import.test.js +4 -1
  11. package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
  12. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
  13. package/ci/mechanism-338-opencode-async.test.js +20 -3
  14. package/ci/mechanism-34-observations.test.js +127 -23
  15. package/ci/mechanism-341-opencode-lane.test.js +7 -1
  16. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  17. package/ci/mechanism-397-cycle-import.test.js +399 -0
  18. package/ci/mechanism-397-host-acceptance.test.js +119 -0
  19. package/ci/mechanism-397-opencode-observations.test.js +1922 -0
  20. package/ci/mechanism-handoff-file.test.js +121 -0
  21. package/ci/mechanism-system-one-contract.test.js +9 -2
  22. package/ci/mechanism-system-one-curves.test.js +223 -0
  23. package/ci/mechanism-system-one-cycle.test.js +1204 -0
  24. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  25. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  26. package/ci/mechanism-system-one-install.test.js +202 -77
  27. package/ci/mechanism-system-one-live.test.js +361 -0
  28. package/ci/mechanism-system-one-relevance.test.js +11 -1
  29. package/ci/mechanism-system-one-train.test.js +136 -53
  30. package/ci/system-one-adapter-test.py +331 -0
  31. package/ci/system-one-train-test.py +116 -24
  32. package/docs/adr/EVID-001.md +123 -0
  33. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  34. package/docs/governed-index.md +2 -0
  35. package/docs/platform-capabilities.md +13 -6
  36. package/docs/routing.md +2 -2
  37. package/docs/system-one-cycle.md +77 -0
  38. package/docs/system-one-observations.md +43 -11
  39. package/docs/system-one-routing.md +163 -115
  40. package/docs/system-one-suggestion-gates.md +6 -8
  41. package/docs/system-one-training.md +44 -7
  42. package/docs/workflow-runtime.md +19 -0
  43. package/harness-everything/SKILL.md +1 -1
  44. package/harness-everything/scripts/kernel-router.js +2 -1
  45. package/harness-everything/scripts/system-one/contract.js +19 -15
  46. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  47. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  48. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  49. package/harness-everything/scripts/system-one/install.js +281 -113
  50. package/harness-everything/scripts/system-one/manifest.js +58 -0
  51. package/harness-everything/scripts/system-one/provider.js +96 -2
  52. package/harness-everything/scripts/system-one/resident.js +47 -1
  53. package/harness-everything/scripts/system-one/router.js +80 -1
  54. package/harness-everything/scripts/tier-router.js +21 -6
  55. package/hooks/scripts/lib/observations.js +48 -7
  56. package/opencode-plugin/README.md +22 -8
  57. package/opencode-plugin/index.mjs +424 -44
  58. package/opencode-plugin/plugin.json +1 -1
  59. package/package.json +1 -1
  60. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  61. package/plugins/harness-everything/hooks/scripts/lib/observations.js +48 -7
  62. package/plugins/harness-everything/plugin.json +1 -1
  63. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  64. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  65. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  66. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  67. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  68. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  69. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  70. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  71. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  72. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  73. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  74. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  75. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  76. package/sbom.cdx.json +7 -7
  77. package/scripts/ci-change-scope.js +59 -0
  78. package/scripts/handoff-file.js +223 -0
  79. package/scripts/sync-openai-plugin.js +4 -0
  80. package/scripts/system-one-calibrate.js +108 -41
  81. package/scripts/system-one-curves.js +472 -0
  82. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  83. package/scripts/system-one-cycle/build.js +165 -0
  84. package/scripts/system-one-cycle/collect.js +67 -0
  85. package/scripts/system-one-cycle/common.js +175 -0
  86. package/scripts/system-one-cycle/engines.js +62 -0
  87. package/scripts/system-one-cycle/evaluate.js +73 -0
  88. package/scripts/system-one-cycle/judge.js +106 -0
  89. package/scripts/system-one-cycle/label.js +59 -0
  90. package/scripts/system-one-cycle/package.js +173 -0
  91. package/scripts/system-one-cycle/score.py +111 -0
  92. package/scripts/system-one-cycle/train.js +136 -0
  93. package/scripts/system-one-cycle.js +136 -0
  94. package/scripts/system-one-observations-export.js +58 -6
  95. package/scripts/system-one-observations-import-store.js +128 -0
  96. package/scripts/system-one-observations-review.js +4 -5
  97. package/scripts/system-one-train.py +117 -61
@@ -0,0 +1,361 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const crypto = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const test = require('node:test');
8
+ const provider = require('../harness-everything/scripts/system-one/provider');
9
+ const { createRequest } = require('../harness-everything/scripts/system-one/contract');
10
+ const router = require('../harness-everything/scripts/system-one/router');
11
+ const { INTENT_OPTIONS } = require('../harness-everything/scripts/system-one/catalogs');
12
+
13
+ const idHash = value => crypto.createHash('sha256').update(value).digest('hex');
14
+ const stages = {
15
+ validity: {
16
+ options: ['invalid'],
17
+ thresholds: { invalid: 0.55 },
18
+ },
19
+ intent: {
20
+ options: INTENT_OPTIONS.map(option => option.id),
21
+ thresholds: Object.fromEntries(INTENT_OPTIONS.map(option => [option.id, option.id === 'unclassified' ? 1 : 0.55])),
22
+ referenceOnly: ['unclassified'],
23
+ },
24
+ tier: {
25
+ options: ['tier1', 'tier2', 'tier3'],
26
+ thresholds: { tier1: 0.6, tier2: 0.65, tier3: 0.7 },
27
+ },
28
+ };
29
+ const intentScores = () => Object.fromEntries(stages.intent.options
30
+ .map(id => [id, id === 'unclassified' ? 0.99 : ({ feature: 0.91, fix: 0.8, docs: 0.72 })[id] || 0.1]));
31
+ // A packaged checkpoint may omit the non-selectable unclassified intent option (cycle/package.js legacyOptions).
32
+ const trainedIntentIds = INTENT_OPTIONS.map(option => option.id).filter(id => id !== 'unclassified');
33
+
34
+ function activeFixture() {
35
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-live-'));
36
+ const dir = path.join(root, 'v1');
37
+ fs.mkdirSync(dir);
38
+ const manifestStages = {};
39
+ for (const [stage, data] of Object.entries(stages)) {
40
+ const weights = `${stage}.safetensors`;
41
+ const config = `${stage}.json`;
42
+ const weightsBytes = Buffer.from(`${stage}-weights`);
43
+ const configBytes = Buffer.from(JSON.stringify({ stage }));
44
+ fs.writeFileSync(path.join(dir, weights), weightsBytes);
45
+ fs.writeFileSync(path.join(dir, config), configBytes);
46
+ manifestStages[stage] = {
47
+ weights,
48
+ config,
49
+ sha256: idHash(weightsBytes),
50
+ options: data.options,
51
+ thresholds: data.thresholds,
52
+ ...(data.referenceOnly ? { referenceOnly: data.referenceOnly } : {}),
53
+ };
54
+ }
55
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({
56
+ schemaVersion: 1,
57
+ version: 'v1',
58
+ createdAt: '2026-11-14T00:00:00.000Z',
59
+ stages: manifestStages,
60
+ evaluation: null,
61
+ }));
62
+ fs.writeFileSync(path.join(root, 'active.json'), JSON.stringify({
63
+ schemaVersion: 1,
64
+ version: 'v1',
65
+ dir,
66
+ previous: null,
67
+ activatedAt: '2026-11-14T00:00:00.000Z',
68
+ }));
69
+ return { root, dir, env: { HARNESS_SYSTEM_ONE_HOME: root } };
70
+ }
71
+
72
+ // The same active home, but the packaged intent stage predates the unclassified option.
73
+ function trainedIntentFixture() {
74
+ const fixture = activeFixture();
75
+ const manifestFile = path.join(fixture.dir, 'manifest.json');
76
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
77
+ manifest.stages.intent.options = trainedIntentIds;
78
+ manifest.stages.intent.thresholds = Object.fromEntries(trainedIntentIds.map(id => [id, 0.55]));
79
+ delete manifest.stages.intent.referenceOnly;
80
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest));
81
+ return fixture;
82
+ }
83
+
84
+ function response(request, probabilities) {
85
+ return {
86
+ schemaVersion: 1,
87
+ requestHash: request.requestHash,
88
+ catalogHash: request.catalogHash,
89
+ model: { id: 'v1', revision: 'v1', domain: 'harness-routing-v1' },
90
+ scores: request.options.map((option, i) => ({ id: option.id, probability: probabilities[i] })),
91
+ };
92
+ }
93
+
94
+ test('S1-L01 reads the active pointer and rejects a stage that escapes its version directory', () => {
95
+ const fixture = activeFixture();
96
+ try {
97
+ const active = provider.readActive(fixture.env);
98
+ assert.equal(active.version, 'v1');
99
+ assert.equal(active.dir, fixture.dir);
100
+ assert.deepEqual(Object.keys(active.stages), ['validity', 'intent', 'tier']);
101
+ const resident = require('../harness-everything/scripts/system-one/resident');
102
+ const [python, args] = resident.defaultActiveCommand(active);
103
+ assert.equal(python, active.python);
104
+ assert.deepEqual(args.slice(1), ['--serve-active']);
105
+ const manifestPath = path.join(fixture.dir, 'manifest.json');
106
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
107
+ manifest.stages.intent.weights = '../outside.safetensors';
108
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));
109
+ assert.equal(provider.readActive(fixture.env), null);
110
+ } finally {
111
+ fs.rmSync(fixture.root, { recursive: true, force: true });
112
+ }
113
+ });
114
+
115
+ test('S1-L02 scores validity, intent, tier in order with independent probabilities and stops on invalid', async () => {
116
+ const fixture = activeFixture();
117
+ try {
118
+ const calls = [];
119
+ const liveEnv = { ...fixture.env, HARNESS_SYSTEM_ONE_MODE: 'live' };
120
+ const runWithFake = async (stage, request) => {
121
+ calls.push(stage);
122
+ const values = stage === 'validity' ? [0.18]
123
+ : stage === 'intent' ? request.options.map(option => ({ feature: 0.91, fix: 0.8, docs: 0.72 })[option.id] || 0.1)
124
+ : [0.2, 0.76, 0.9, 0.1];
125
+ return { status: 'scored', response: response(request, values) };
126
+ };
127
+ const result = await router.prescoreLive('fixture context', liveEnv,
128
+ (prompt, env, options) => provider.scoreLive(prompt, env, options, runWithFake));
129
+ assert.deepEqual(calls, ['validity', 'intent', 'tier']);
130
+ assert.deepEqual(result.stageScores.validity, { invalid: 0.18 });
131
+ assert.equal(result.stageScores.intent.feature, 0.91);
132
+ assert.equal(result.stageScores.tier.tier3, 0.9);
133
+ assert.equal(result.sha256, activeFixtureHash(fixture));
134
+
135
+ calls.length = 0;
136
+ const repeated = await router.prescoreLive('fixture context', liveEnv,
137
+ (prompt, env, options) => provider.scoreLive(prompt, env, options, runWithFake));
138
+ assert.deepEqual(repeated, result);
139
+ assert.deepEqual(calls, ['validity', 'intent', 'tier']);
140
+ calls.length = 0;
141
+ const invalid = await router.prescoreLive('fixture context', liveEnv, (prompt, env, options) => provider.scoreLive(prompt, env, options, async (stage, request) => {
142
+ calls.push(stage);
143
+ return { status: 'scored', response: response(request, [0.9]) };
144
+ }));
145
+ assert.deepEqual(calls, ['validity']);
146
+ assert.deepEqual(invalid.stageScores, { validity: { invalid: 0.9 }, intent: null, tier: null });
147
+ } finally {
148
+ fs.rmSync(fixture.root, { recursive: true, force: true });
149
+ }
150
+ });
151
+
152
+ test('reference-only validity reports its score and abstains without scoring later stages', async () => {
153
+ const fixture = activeFixture();
154
+ try {
155
+ const manifestFile = path.join(fixture.dir, 'manifest.json');
156
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
157
+ manifest.stages.validity.thresholds.invalid = 1;
158
+ manifest.stages.validity.referenceOnly = ['invalid'];
159
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest));
160
+ const calls = [];
161
+ const result = await provider.scoreLive('fixture context', fixture.env, {
162
+ validity: router.VALIDITY_OPTIONS,
163
+ intent: require('../harness-everything/scripts/system-one/catalogs').INTENT_OPTIONS,
164
+ tier: router.TIER_OPTIONS,
165
+ }, async (stage, request) => {
166
+ calls.push(stage);
167
+ return { status: 'scored', response: response(request, [1]) };
168
+ });
169
+ assert.deepEqual(calls, ['validity']);
170
+ assert.equal(result.stageScores.validity.invalid, 1);
171
+ const routed = router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, result);
172
+ assert.equal(routed.systemOne.decision.validity, 'abstain');
173
+ assert.deepEqual(routed.reference.referenceOnlyOptions, [{ stage: 'validity', id: 'invalid', probability: 1 }]);
174
+ } finally {
175
+ fs.rmSync(fixture.root, { recursive: true, force: true });
176
+ }
177
+ });
178
+
179
+ function activeFixtureHash(fixture) {
180
+ return JSON.parse(fs.readFileSync(path.join(fixture.dir, 'manifest.json'), 'utf8')).stages.tier.sha256.slice(0, 16);
181
+ }
182
+
183
+ test('F1 provider keeps adapter vectors and projects live sigmoid stages to option keys', async () => {
184
+ const { validateResponse } = require('../harness-everything/scripts/system-one/contract');
185
+ const fixture = activeFixture();
186
+ try {
187
+ const catalogs = {
188
+ validity: router.VALIDITY_OPTIONS,
189
+ intent: require('../harness-everything/scripts/system-one/catalogs').INTENT_OPTIONS,
190
+ tier: router.TIER_OPTIONS,
191
+ };
192
+ const adapterResponses = [];
193
+ const result = await provider.scoreLive('fixture context', fixture.env, catalogs, async (stage, request) => {
194
+ const values = stage === 'validity' ? [0.1]
195
+ : stage === 'intent' ? request.options.map(option => ({ fix: 0.9, test: 0.8 })[option.id] || 0.1)
196
+ : [0.2, 0.76, 0.9, 0.1];
197
+ const scored = response(request, values);
198
+ adapterResponses.push({ request, scored });
199
+ return { status: 'scored', response: scored };
200
+ });
201
+
202
+ assert.ok(adapterResponses.every(({ request, scored }) => Array.isArray(scored.scores) && validateResponse(request, scored)));
203
+ assert.deepEqual(result.stageScores.validity, { invalid: 0.1 });
204
+ assert.equal(result.stageScores.intent.fix, 0.9);
205
+ assert.equal(result.stageScores.intent.test, 0.8);
206
+ assert.equal(result.stageScores.intent.unclassified, 0.1);
207
+ assert.deepEqual(result.stageScores.tier, { tier1: 0.2, tier2: 0.76, tier3: 0.9 });
208
+ assert.ok(Object.values(result.stageScores.tier).reduce((sum, score) => sum + score, 0) > 1);
209
+ } finally {
210
+ fs.rmSync(fixture.root, { recursive: true, force: true });
211
+ }
212
+ });
213
+
214
+ test('F1 router keeps legacy simplex selection separate from live keyed sigmoid routing', () => {
215
+ const legacy = router.selectTier({ tier: 'Tier 3 (Macro Task)', prompt: 'fixture context', floor: null, explicit: false },
216
+ { HARNESS_SYSTEM_ONE_MODE: 'prefer' }, request => ({ status: 'scored', response: response(request, [0.95, 0.03, 0.01, 0.01]) }));
217
+ assert.equal(legacy.tier, 'Tier 1 (Trivial)');
218
+
219
+ const live = router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, {
220
+ version: 'v1', sha256: '0123456789abcdef',
221
+ stageScores: { validity: { invalid: 0.1 }, intent: intentScores(), tier: { tier1: 0.2, tier2: 0.76, tier3: 0.9 } },
222
+ thresholds: { validity: { invalid: 0.55 }, intent: stages.intent.thresholds, tier: stages.tier.thresholds },
223
+ });
224
+ assert.equal(live.tier, 'Tier 3 (Macro Task)');
225
+ assert.equal(live.systemOne.decision.tier, 'tier3');
226
+ });
227
+
228
+ test('S1-L03 precedence keeps explicit choices and the structural floor, otherwise applies a scored tier', () => {
229
+ const result = {
230
+ version: 'v1', sha256: '0123456789abcdef',
231
+ stageScores: {
232
+ validity: { invalid: 0.1 },
233
+ intent: intentScores(),
234
+ tier: { tier1: 0.2, tier2: 0.76, tier3: 0.9 },
235
+ },
236
+ thresholds: { validity: { invalid: 0.55 }, intent: stages.intent.thresholds, tier: stages.tier.thresholds },
237
+ };
238
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, result).tier, 'Tier 3 (Macro Task)');
239
+ const lowerThanLexical = { ...result, stageScores: { ...result.stageScores, tier: { tier1: 0.2, tier2: 0.9, tier3: 0.4 } } };
240
+ assert.equal(router.routeLive({ tier: 'Tier 3 (Macro Task)', floor: null, explicit: false }, lowerThanLexical).tier, 'Tier 2 (Standard Task)');
241
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: 'tier3', explicit: false }, result).tier, 'Tier 3 (Macro Task)');
242
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: 'tier2', explicit: false }, result).tier, 'Tier 3 (Macro Task)');
243
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: true }, result).tier, 'Tier 2 (Standard Task)');
244
+ const belowThreshold = { ...result, stageScores: { ...result.stageScores, tier: { tier1: 0.2, tier2: 0.3, tier3: 0.4 } } };
245
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, belowThreshold).tier, 'Tier 2 (Standard Task)');
246
+ const bestBelowThreshold = { ...result,
247
+ stageScores: { ...result.stageScores, tier: { tier1: 0.2, tier2: 0.76, tier3: 0.8 } },
248
+ thresholds: { ...result.thresholds, tier: { tier1: 0.6, tier2: 0.65, tier3: 0.9 } },
249
+ };
250
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, bestBelowThreshold).tier, 'Tier 2 (Standard Task)');
251
+ const tiedBest = { ...result, stageScores: { ...result.stageScores, tier: { tier1: 0.2, tier2: 0.9, tier3: 0.9 } } };
252
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, tiedBest).systemOne.decision.tier, null);
253
+ const invalid = { ...result, stageScores: { validity: { invalid: 0.9 }, intent: null, tier: null } };
254
+ const invalidRoute = router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, invalid);
255
+ assert.equal(invalidRoute.tier, 'Tier 2 (Standard Task)');
256
+ assert.deepEqual(invalidRoute.systemOne.decision, { validity: 'invalid', intents: [], tier: null });
257
+ assert.equal(router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, null).systemOne, undefined);
258
+ });
259
+
260
+ test('S1-L04 workflow plan carries the fixed object and user output labels scores as reference confidence', () => {
261
+ const { run } = require('../harness-everything/scripts/tier-router');
262
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-live-router-'));
263
+ const env = process.env;
264
+ const prior = { mode: env.HARNESS_SYSTEM_ONE_MODE, contract: env.HARNESS_ROUTER_CONTRACT_PATH };
265
+ const lines = [];
266
+ const log = console.log;
267
+ try {
268
+ env.HARNESS_SYSTEM_ONE_MODE = 'live';
269
+ env.HARNESS_ROUTER_CONTRACT_PATH = path.join(temp, 'router-contract.json');
270
+ console.log = value => lines.push(String(value));
271
+ const result = {
272
+ version: 'v1', sha256: '0123456789abcdef',
273
+ stageScores: { validity: { invalid: 0.1 }, intent: intentScores(), tier: { tier1: 0.2, tier2: 0.76, tier3: 0.9 } },
274
+ thresholds: { validity: { invalid: 0.55 }, intent: stages.intent.thresholds, tier: stages.tier.thresholds },
275
+ };
276
+ const contract = run('fixture request with clear scope', null, { systemOneResult: result });
277
+ assert.deepEqual(Object.keys(contract.workflowPlan.systemOne), ['version', 'sha256', 'mode', 'inputEnrichment', 'referenceOnly', 'validity', 'intents', 'tier', 'decision']);
278
+ assert.deepEqual(contract.workflowPlan.systemOne.inputEnrichment, { handoffFiles: 0 });
279
+ assert.deepEqual(contract.workflowPlan.systemOne.decision, { validity: 'actionable', intents: ['feature', 'fix', 'docs'], tier: 'tier3' });
280
+ assert.deepEqual(JSON.parse(fs.readFileSync(env.HARNESS_ROUTER_CONTRACT_PATH, 'utf8')).workflowPlan.systemOne, contract.workflowPlan.systemOne);
281
+ const output = lines.join('\n');
282
+ assert.match(output, /SYSTEM ONE REFERENCE CONFIDENCE/);
283
+ assert.match(output, /0\.91/);
284
+ assert.match(output, /not a verdict/);
285
+ assert.doesNotMatch(output, /selected a tier/i);
286
+ } finally {
287
+ console.log = log;
288
+ if (prior.mode === undefined) delete env.HARNESS_SYSTEM_ONE_MODE; else env.HARNESS_SYSTEM_ONE_MODE = prior.mode;
289
+ if (prior.contract === undefined) delete env.HARNESS_ROUTER_CONTRACT_PATH; else env.HARNESS_ROUTER_CONTRACT_PATH = prior.contract;
290
+ fs.rmSync(temp, { recursive: true, force: true });
291
+ }
292
+ });
293
+
294
+ test('S1-L05 explicit off is byte-identical to the historical default and omits System One', () => {
295
+ const { run } = require('../harness-everything/scripts/tier-router');
296
+ const env = process.env;
297
+ const prior = env.HARNESS_SYSTEM_ONE_MODE;
298
+ const capture = mode => {
299
+ if (mode === undefined) delete env.HARNESS_SYSTEM_ONE_MODE;
300
+ else env.HARNESS_SYSTEM_ONE_MODE = mode;
301
+ const lines = [];
302
+ const log = console.log;
303
+ try {
304
+ console.log = value => lines.push(String(value));
305
+ return { contract: run('fixture request with clear scope'), output: lines.join('\n') };
306
+ } finally { console.log = log; }
307
+ };
308
+ try {
309
+ const historicalDefault = capture(undefined);
310
+ const explicitOff = capture('off');
311
+ assert.equal(explicitOff.output, historicalDefault.output);
312
+ assert.deepEqual(explicitOff.contract, historicalDefault.contract);
313
+ assert.equal(Object.hasOwn(explicitOff.contract.workflowPlan, 'systemOne'), false);
314
+ } finally {
315
+ if (prior === undefined) delete env.HARNESS_SYSTEM_ONE_MODE; else env.HARNESS_SYSTEM_ONE_MODE = prior;
316
+ }
317
+ });
318
+
319
+ test('S1-L06 a packaged intent catalog without the unclassified option still scores live and routes', async () => {
320
+ const fixture = trainedIntentFixture();
321
+ try {
322
+ const liveCatalogs = { validity: router.VALIDITY_OPTIONS, intent: INTENT_OPTIONS, tier: router.TIER_OPTIONS };
323
+ const runWithFake = async (stage, request) => {
324
+ const values = stage === 'validity' ? [0.18]
325
+ : stage === 'intent' ? request.options.map(option => ({ feature: 0.91, fix: 0.8, docs: 0.72 })[option.id] || 0.1)
326
+ : [0.2, 0.76, 0.9, 0.1];
327
+ return { status: 'scored', response: response(request, values) };
328
+ };
329
+ const result = await provider.scoreLive('fixture context', fixture.env, liveCatalogs, runWithFake);
330
+ assert.ok(result, 'a packaged 12-option intent catalog must still score');
331
+ assert.deepEqual(Object.keys(result.stageScores.intent), trainedIntentIds);
332
+ assert.deepEqual(result.stageScores.tier, { tier1: 0.2, tier2: 0.76, tier3: 0.9 });
333
+ const routed = router.routeLive({ tier: 'Tier 2 (Standard Task)', floor: null, explicit: false }, result);
334
+ assert.deepEqual(Object.keys(routed.systemOne.intents), trainedIntentIds);
335
+ assert.deepEqual(routed.systemOne.decision, { validity: 'actionable', intents: ['feature', 'fix', 'docs'], tier: 'tier3' });
336
+ } finally {
337
+ fs.rmSync(fixture.root, { recursive: true, force: true });
338
+ }
339
+ });
340
+
341
+ test('S1-L07 a different intent id set stays null and invalid validity still stops the live path', async () => {
342
+ const fixture = trainedIntentFixture();
343
+ try {
344
+ const liveCatalogs = { validity: router.VALIDITY_OPTIONS, intent: INTENT_OPTIONS, tier: router.TIER_OPTIONS };
345
+ const stopOnInvalid = async (stage, request) => ({ status: 'scored', response: response(request, [0.9]) });
346
+ const stopped = await provider.scoreLive('fixture context', fixture.env, liveCatalogs, stopOnInvalid);
347
+ assert.deepEqual(stopped.stageScores, { validity: { invalid: 0.9 }, intent: null, tier: null });
348
+
349
+ const manifestFile = path.join(fixture.dir, 'manifest.json');
350
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
351
+ const renamed = ['explain2', ...trainedIntentIds.slice(1)];
352
+ manifest.stages.intent.options = renamed;
353
+ manifest.stages.intent.thresholds = Object.fromEntries(renamed.map(id => [id, 0.55]));
354
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest));
355
+ const actionable = async (stage, request) => ({ status: 'scored', response: response(request,
356
+ stage === 'validity' ? [0.18] : request.options.map(() => 0.5)) });
357
+ assert.equal(await provider.scoreLive('fixture context', fixture.env, liveCatalogs, actionable), null);
358
+ } finally {
359
+ fs.rmSync(fixture.root, { recursive: true, force: true });
360
+ }
361
+ });
@@ -44,6 +44,16 @@ test('S1-R03 the simplex rule does not apply to relevance vectors', () => {
44
44
  assert.equal(decide(request, res, {}).status, 'invalid-output', 'single-winner still demands the simplex');
45
45
  });
46
46
 
47
+ test('F1 single-winner and relevance decisions keep separate score contracts', () => {
48
+ const simplex = responseFor(Object.fromEntries(IDS.map(id => [id, id === 'fix' ? 0.9 : id === 'test' ? 0.1 : 0])));
49
+ assert.equal(decide(request, simplex).status, 'accepted');
50
+
51
+ const relevance = responseFor({ fix: 0.9, test: 0.8, docs: 0.7 });
52
+ assert.ok(relevance.scores.reduce((sum, score) => sum + score.probability, 0) > 1);
53
+ assert.equal(decide(request, relevance).status, 'invalid-output');
54
+ assert.equal(decideIntents(request, relevance, { thresholds: thresholds() }).status, 'accepted');
55
+ });
56
+
47
57
  test('S1-R04 malformed relevance inputs fail closed', () => {
48
58
  const good = responseFor({ fix: 0.9 });
49
59
  const tau = thresholds();
@@ -86,7 +96,7 @@ const goodEvidence = () => ({ family: { gold: { rate: 0.8 }, model: { rate: 0.85
86
96
 
87
97
  test('S1-R06 relevance gates follow the reviewed promotion contract', () => {
88
98
  const pass = relevanceGates(goodMulti(), goodEvidence());
89
- assert.ok(pass.rolloutReady === false, 'policy/live-host evidence keeps rollout red pre-production');
99
+ assert.equal(Object.hasOwn(pass, 'rolloutReady'), false, 'gate metrics stay report-only for the opt-in launch');
90
100
  for (const k of ['microF1', 'macroF1', 'perIntentFloors', 'weakPrecision', 'cardinality',
91
101
  'abstainRate', 'familyConsistency', 'repeatability', 'warmLatency', 'structuralControls']) {
92
102
  assert.equal(pass[k], true, k);
@@ -5,7 +5,8 @@ const fs = require('node:fs');
5
5
  const os = require('node:os');
6
6
  const path = require('node:path');
7
7
  const { spawnSync } = require('node:child_process');
8
- const { calibrate, decideRow } = require('../scripts/system-one-calibrate');
8
+ const { calibrate } = require('../scripts/system-one-calibrate');
9
+ const { CATALOGS } = require('../harness-everything/scripts/system-one/catalogs');
9
10
  const root = path.resolve(__dirname, '..');
10
11
  const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
11
12
 
@@ -15,80 +16,162 @@ test('S1-T01 trainer data handling is exercised without torch', () => {
15
16
  assert.match(r.stdout, /trainer data tests passed/);
16
17
  });
17
18
 
18
- const row = (gold, probs) => ({ gold, probs });
19
- test('S1-T02 a validation row is accepted only above both thresholds and never as unclassified', () => {
20
- assert.deepEqual(decideRow([0.95, 0.03, 0.01, 0.01], { minConfidence: 0.9, minMargin: 0.2 }), 'tier1');
21
- assert.equal(decideRow([0.85, 0.1, 0.03, 0.02], { minConfidence: 0.9, minMargin: 0.2 }), null);
22
- assert.equal(decideRow([0.55, 0.45, 0, 0], { minConfidence: 0.5, minMargin: 0.2 }), null);
23
- assert.equal(decideRow([0.01, 0.01, 0.01, 0.97], { minConfidence: 0.5, minMargin: 0 }), null);
19
+ const TIER_IDS = ['tier1', 'tier2', 'tier3'];
20
+ const scoreRow = (gold, scores) => ({ gold, scores });
21
+ const tierRows = (count = 20) => TIER_IDS.flatMap(gold => Array.from({ length: count }, () => scoreRow(gold,
22
+ Object.fromEntries(TIER_IDS.map(id => [id, id === gold ? 0.95 : 0.8])))));
23
+
24
+ test('S1-T02 per-option sigmoid thresholds maximize coverage at the precision target', () => {
25
+ const rows = tierRows();
26
+ const c = calibrate(rows, { minPrecision: 0.98, task: 'tier' });
27
+ assert.equal(c.feasible, true);
28
+ assert.equal(c.rows, 60);
29
+ assert.deepEqual(Object.keys(c.thresholds), TIER_IDS);
30
+ for (const id of TIER_IDS) {
31
+ assert.equal(c.thresholds[id], 0.95);
32
+ assert.equal(c.options[id].accepted, 20);
33
+ assert.equal(c.options[id].precision, 1);
34
+ }
35
+ assert.deepEqual(calibrate(rows, { minPrecision: 0.98, task: 'tier' }), c, 'deterministic');
24
36
  });
25
37
 
26
- test('S1-T03 calibration maximizes coverage subject to accepted precision on validation only', () => {
27
- const rows = [
28
- ...Array.from({ length: 90 }, () => row('tier1', [0.97, 0.01, 0.01, 0.01])),
29
- ...Array.from({ length: 5 }, () => row('tier2', [0.8, 0.15, 0.03, 0.02])),
30
- ...Array.from({ length: 5 }, () => row('tier2', [0.1, 0.85, 0.03, 0.02])),
31
- ];
32
- const c = calibrate(rows, { minPrecision: 0.98 });
33
- assert.ok(c.precision >= 0.98, JSON.stringify(c));
34
- assert.equal(c.coverage, 0.95, JSON.stringify(c));
35
- // Either threshold may separate the rows; the chosen pair must reject the wrong ones and keep the right ones.
36
- assert.equal(decideRow([0.8, 0.15, 0.03, 0.02], c), null, JSON.stringify(c));
37
- assert.equal(decideRow([0.1, 0.85, 0.03, 0.02], c), 'tier2', JSON.stringify(c));
38
- const none = calibrate([row('tier1', [0.3, 0.7, 0, 0])], { minPrecision: 0.98 });
38
+ test('S1-T03 calibrator accepts legacy probability vectors and marks unsupported options infeasible', () => {
39
+ const rows = tierRows(10).map(({ gold, scores }) => ({ gold,
40
+ probs: [...TIER_IDS.map(id => scores[id]), 0.01] }));
41
+ const legacy = calibrate(rows, { minPrecision: 0.98, task: 'tier' });
42
+ assert.equal(legacy.feasible, true);
43
+ assert.deepEqual(legacy.thresholds, { tier1: 0.95, tier2: 0.95, tier3: 0.95 });
44
+ const none = calibrate([scoreRow('tier1', { tier1: 0.3, tier2: 0.7, tier3: 0.1 })], { minPrecision: 0.98, task: 'tier' });
39
45
  assert.equal(none.feasible, false);
40
- assert.equal(none.coverage, 0);
41
- assert.deepEqual(calibrate(rows, { minPrecision: 0.98 }), c, 'deterministic');
46
+ assert.equal(none.thresholds.tier2, null);
47
+ assert.throws(() => calibrate([{ gold: 'tier1', probs: [0.9, 0.1, 0.1, 1.1] }], { task: 'tier' }));
48
+ assert.throws(() => calibrate([{ gold: 'tier1', split: 'holdout', scores: { tier1: 0.9, tier2: 0.1, tier3: 0.1 } }], { task: 'tier' }));
49
+ });
50
+
51
+ test('S1-T07 validity and intent use the task-specific option catalogs', () => {
52
+ const validity = calibrate([
53
+ { gold: 'invalid', scores: { invalid: 0.9 } },
54
+ { gold: 'actionable', scores: { invalid: 0.1 } },
55
+ ], { task: 'validity' });
56
+ assert.deepEqual(validity.thresholds, { invalid: 0.9 });
57
+ const intentIds = CATALOGS.intent.map(o => o.id);
58
+ const rows = intentIds.filter(id => id !== 'unclassified').map(gold => ({ gold,
59
+ scores: Object.fromEntries(intentIds.map(id => [id, id === gold ? 0.95 : 0.1])) }));
60
+ const intent = calibrate(rows, { task: 'intent' });
61
+ assert.equal(intent.feasible, true);
62
+ assert.deepEqual(Object.keys(intent.thresholds), intentIds);
63
+ assert.ok(Object.values(intent.thresholds).filter(threshold => threshold !== null).every(threshold => threshold === 0.95));
64
+ assert.equal(intent.thresholds.unclassified, null);
65
+ assert.throws(() => calibrate([...rows, { gold: 'fix', scores: Object.fromEntries(intentIds
66
+ .filter(id => id !== 'unclassified').map(id => [id, id === 'fix' ? 0.95 : 0.1])) }], { task: 'intent' }), /invalid-scores/);
67
+ });
68
+
69
+ test('F1 calibration keeps legacy simplex rows separate from sigmoid option scores', () => {
70
+ const intentIds = CATALOGS.intent.map(option => option.id);
71
+ const legacyProbs = masses => {
72
+ const rest = (1 - Object.values(masses).reduce((sum, value) => sum + value, 0))
73
+ / (intentIds.length - Object.keys(masses).length);
74
+ return intentIds.map(id => Object.hasOwn(masses, id) ? masses[id] : rest);
75
+ };
76
+ const legacy = calibrate([
77
+ { gold: 'fix', secondary: ['test'], probs: legacyProbs({ fix: 0.6, test: 0.3 }) },
78
+ { gold: 'test', secondary: ['fix'], probs: legacyProbs({ fix: 0.55, test: 0.35 }) },
79
+ { gold: 'docs', secondary: [], probs: legacyProbs({ git: 0.4, docs: 0.35 }) },
80
+ ], { task: 'intent' });
81
+ assert.deepEqual([legacy.secondaryThreshold, legacy.minConfidence, legacy.minMargin], [0.05, 0.5, 0.25]);
82
+
83
+ const sigmoid = calibrate([
84
+ { gold: 'fix', scores: Object.fromEntries(intentIds.map(id => [id, id === 'fix' ? 0.95 : 0.1])) },
85
+ { gold: 'docs', scores: Object.fromEntries(intentIds.map(id => [id, id === 'docs' ? 0.95 : 0.1])) },
86
+ ], { task: 'intent' });
87
+ assert.equal(sigmoid.thresholds.fix, 0.95);
88
+ assert.equal(sigmoid.thresholds.docs, 0.95);
89
+ assert.equal(sigmoid.secondaryThreshold, undefined);
42
90
  });
43
91
 
44
92
  test('S1-T06 the default calibration target is the owner advisory 85%', () => {
45
- const rows = [
46
- ...Array.from({ length: 86 }, () => row('tier1', [0.9, 0.05, 0.03, 0.02])),
47
- ...Array.from({ length: 14 }, () => row('tier2', [0.9, 0.05, 0.03, 0.02])),
48
- ];
49
- const c = calibrate(rows);
93
+ const c = calibrate(tierRows(10), { task: 'tier' });
50
94
  assert.equal(c.minPrecision, 0.85);
51
95
  assert.equal(c.feasible, true);
52
- assert.equal(c.coverage, 1);
53
- assert.equal(calibrate(rows, { minPrecision: 0.9 }).feasible, false);
54
96
  });
55
97
 
56
- test('S1-T04 calibration CLI reads validation scores and writes thresholds', () => {
98
+ test('S1-T04 calibration CLI reads validation sigmoid scores and writes per-option thresholds', () => {
57
99
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-cal-'));
58
100
  try {
59
101
  const input = path.join(dir, 'val-scores.jsonl');
60
- fs.writeFileSync(input, Array.from({ length: 50 }, (_, i) => JSON.stringify({ id: `v${i}`, gold: 'tier2', probs: [0.02, 0.95, 0.02, 0.01] })).join('\n') + '\n');
102
+ fs.writeFileSync(input, tierRows(10).map((r, i) => JSON.stringify({ id: `v${i}`, ...r })).join('\n') + '\n');
61
103
  const out = path.join(dir, 'calibration.json');
62
104
  const r = spawnSync(process.execPath, [path.join(root, 'scripts/system-one-calibrate.js'), input, out], { encoding: 'utf8' });
63
105
  assert.equal(r.status, 0, r.stderr);
64
106
  const c = JSON.parse(fs.readFileSync(out, 'utf8'));
65
- assert.equal(c.feasible, true); assert.equal(c.coverage, 1); assert.equal(c.rows, 50);
107
+ assert.equal(c.feasible, true); assert.equal(c.rows, 30);
108
+ assert.deepEqual(c.thresholds, { tier1: 0.95, tier2: 0.95, tier3: 0.95 });
66
109
  assert.equal(spawnSync(process.execPath, [path.join(root, 'scripts/system-one-calibrate.js')], { encoding: 'utf8' }).status, 1);
67
110
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
68
111
  });
69
112
 
70
- test('S1-T05 a real tiny training run produces a checkpoint the adapter loads (skipped without torch)', t => {
71
- const probe = spawnSync(python, ['-c', 'import torch, cua_s1'], { encoding: 'utf8' });
72
- if (probe.status !== 0) { t.skip('torch/cua_s1 not installed; mechanism tests above still run'); return; }
113
+ test('calibration uses the trainer report catalog, including the unclassified score key', () => {
114
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-cal-catalog-'));
115
+ try {
116
+ const intentIds = CATALOGS.intent.map(option => option.id);
117
+ const rows = intentIds.filter(id => id !== 'unclassified').map((gold, i) => ({ id: `i${i}`, gold,
118
+ scores: Object.fromEntries(intentIds.map(id => [id, id === gold ? 0.95 : 0.1])) }));
119
+ const input = path.join(dir, 'val-scores.jsonl');
120
+ const catalog = path.join(dir, 'train-report.json');
121
+ const output = path.join(dir, 'calibration.json');
122
+ fs.writeFileSync(input, rows.map(row => JSON.stringify(row)).join('\n') + '\n');
123
+ fs.writeFileSync(catalog, JSON.stringify({ task: 'intent', catalog: intentIds }));
124
+ const result = spawnSync(process.execPath, [path.join(root, 'scripts/system-one-calibrate.js'), input, output,
125
+ '--task', 'intent', '--catalog', catalog], { encoding: 'utf8' });
126
+ assert.equal(result.status, 0, result.stderr);
127
+ const calibrated = JSON.parse(fs.readFileSync(output, 'utf8'));
128
+ assert.deepEqual(Object.keys(calibrated.thresholds), intentIds);
129
+ assert.equal(calibrated.thresholds.unclassified, null);
130
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
131
+ });
132
+
133
+ test('S1-T05 real tiny training runs write option-keyed sigmoid scores and load checkpoints (skipped without torch)', t => {
134
+ const probe = spawnSync(python, ['-c', 'import torch'], { encoding: 'utf8' });
135
+ if (probe.status !== 0) { t.skip('skipped without torch'); return; }
73
136
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-train-'));
74
137
  try {
75
- const data = path.join(dir, 'data'); fs.mkdirSync(data);
76
- const texts = ['commit all changes', 'push and open a pr', 'add a flag with tests', 'migrate every service', 'go', 'yes'];
77
- const golds = ['tier1', 'tier1', 'tier3', 'tier3', null, null];
78
- const prompts = []; const labels = [];
79
- for (let k = 0; k < 8; k++) texts.forEach((t, i) => { const id = `p${k}-${i}`; prompts.push({ id, family: `f${k}`, source: 'claude', split: k < 6 ? 'train' : 'validation', text: `${t} ${k}` }); labels.push({ id, gold: golds[i] }); });
80
- fs.writeFileSync(path.join(data, 'prompts.jsonl'), prompts.map(p => JSON.stringify(p)).join('\n') + '\n');
81
- fs.writeFileSync(path.join(data, 'labels.jsonl'), labels.map(p => JSON.stringify(p)).join('\n') + '\n');
82
- const out = path.join(dir, 'model');
83
- const r = spawnSync(python, [path.join(root, 'scripts/system-one-train.py'), '--data-dir', data, '--out', out, '--epochs', '2', '--context-tokens', '64'], { encoding: 'utf8' });
84
- assert.equal(r.status, 0, r.stdout + r.stderr);
85
- const report = JSON.parse(fs.readFileSync(path.join(out, 'train-report.json'), 'utf8'));
86
- assert.equal(report.counts.train, 36); assert.equal(report.counts.validation, 12);
87
- const scores = fs.readFileSync(path.join(out, 'val-scores.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
88
- assert.equal(scores.length, 12);
89
- assert.ok(scores.every(s => s.probs.length === 4 && Math.abs(s.probs.reduce((a, b) => a + b, 0) - 1) < 1e-5));
90
- const load = spawnSync(python, ['-c', `from cua_s1.model import load_checkpoint; m,c,cfg=load_checkpoint(r'${path.join(out, 'harness-routing-v1.safetensors')}','cpu'); print(cfg['context_tokens'])`], { encoding: 'utf8' });
91
- assert.equal(load.status, 0, load.stderr);
92
- assert.equal(load.stdout.trim(), '64');
138
+ const texts = ['commit all changes', 'push and open a pr', 'add a flag with tests', 'migrate every service', 'go', 'yes'];
139
+ const tierGolds = ['tier1', 'tier1', 'tier3', 'tier3', null, null];
140
+ const intentIds = CATALOGS.intent.map(o => o.id).filter(id => id !== 'unclassified');
141
+ const intentGolds = [intentIds[0], intentIds[0], intentIds[1], intentIds[1], null, null];
142
+ const tasks = [
143
+ { name: 'validity', golds: tierGolds, counts: { train: 36, validation: 12 }, options: ['invalid'] },
144
+ { name: 'intent', golds: intentGolds, counts: { train: 24, validation: 8 }, options: CATALOGS.intent.map(o => o.id) },
145
+ { name: 'tier', golds: tierGolds, counts: { train: 24, validation: 8 }, options: ['tier1', 'tier2', 'tier3'] },
146
+ ];
147
+ for (const task of tasks) {
148
+ const data = path.join(dir, task.name); fs.mkdirSync(data);
149
+ const prompts = []; const labels = []; const intentLabels = [];
150
+ for (let k = 0; k < 8; k++) texts.forEach((text, i) => {
151
+ const id = `${task.name}-${k}-${i}`;
152
+ prompts.push({ id, family: `${task.name}-f${k}`, source: 'synthetic', split: k < 6 ? 'train' : 'validation', text });
153
+ labels.push({ id, gold: tierGolds[i] });
154
+ intentLabels.push({ id, gold: intentGolds[i], secondary: [] });
155
+ });
156
+ fs.writeFileSync(path.join(data, 'prompts.jsonl'), prompts.map(p => JSON.stringify(p)).join('\n') + '\n');
157
+ fs.writeFileSync(path.join(data, 'labels.jsonl'), labels.map(p => JSON.stringify(p)).join('\n') + '\n');
158
+ fs.writeFileSync(path.join(data, 'labels-intent.jsonl'), intentLabels.map(p => JSON.stringify(p)).join('\n') + '\n');
159
+ const out = path.join(dir, `${task.name}-out`);
160
+ const r = spawnSync(python, [path.join(root, 'scripts/system-one-train.py'), '--data-dir', data, '--out', out, '--epochs', '2', '--threads', '1', '--context-tokens', '64', '--task', task.name], { encoding: 'utf8' });
161
+ assert.equal(r.status, 0, r.stdout + r.stderr);
162
+ const report = JSON.parse(fs.readFileSync(path.join(out, 'train-report.json'), 'utf8'));
163
+ assert.deepEqual(report.counts, task.counts);
164
+ assert.deepEqual(report.catalog, task.options);
165
+ const scores = fs.readFileSync(path.join(out, 'val-scores.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
166
+ assert.equal(scores.length, task.counts.validation);
167
+ for (const row of scores) {
168
+ assert.deepEqual(Object.keys(row.scores).sort(), [...task.options].sort());
169
+ assert.ok(Object.values(row.scores).every(p => Number.isFinite(p) && p >= 0 && p <= 1));
170
+ assert.equal(Object.hasOwn(row, 'probs'), false);
171
+ }
172
+ const load = spawnSync(python, ['-c', `from cua_s1.model import load_checkpoint; m,c,cfg=load_checkpoint(r'${path.join(out, 'harness-routing-v1.safetensors')}','cpu'); print(cfg['context_tokens'])`], { encoding: 'utf8' });
173
+ assert.equal(load.status, 0, load.stderr);
174
+ assert.equal(load.stdout.trim(), '64');
175
+ }
93
176
  } finally { fs.rmSync(dir, { recursive: true, force: true }); }
94
177
  });