harness-everything 0.51.0 → 0.52.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 (83) 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 +34 -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/ci/mechanism-2am-observations-session-import.test.js +4 -1
  8. package/ci/mechanism-34-observations.test.js +127 -23
  9. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  10. package/ci/mechanism-handoff-file.test.js +121 -0
  11. package/ci/mechanism-system-one-contract.test.js +9 -2
  12. package/ci/mechanism-system-one-curves.test.js +206 -0
  13. package/ci/mechanism-system-one-cycle.test.js +585 -0
  14. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  15. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  16. package/ci/mechanism-system-one-install.test.js +202 -77
  17. package/ci/mechanism-system-one-live.test.js +361 -0
  18. package/ci/mechanism-system-one-relevance.test.js +11 -1
  19. package/ci/mechanism-system-one-train.test.js +136 -53
  20. package/ci/system-one-adapter-test.py +331 -0
  21. package/ci/system-one-train-test.py +116 -24
  22. package/docs/adr/EVID-001.md +123 -0
  23. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  24. package/docs/governed-index.md +2 -0
  25. package/docs/routing.md +2 -2
  26. package/docs/system-one-cycle.md +68 -0
  27. package/docs/system-one-observations.md +9 -8
  28. package/docs/system-one-routing.md +163 -115
  29. package/docs/system-one-suggestion-gates.md +6 -8
  30. package/docs/system-one-training.md +44 -7
  31. package/docs/workflow-runtime.md +19 -0
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +2 -1
  34. package/harness-everything/scripts/system-one/contract.js +19 -15
  35. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  36. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  37. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  38. package/harness-everything/scripts/system-one/install.js +281 -113
  39. package/harness-everything/scripts/system-one/manifest.js +58 -0
  40. package/harness-everything/scripts/system-one/provider.js +96 -2
  41. package/harness-everything/scripts/system-one/resident.js +47 -1
  42. package/harness-everything/scripts/system-one/router.js +80 -1
  43. package/harness-everything/scripts/tier-router.js +21 -6
  44. package/hooks/scripts/lib/observations.js +43 -4
  45. package/opencode-plugin/plugin.json +1 -1
  46. package/package.json +1 -1
  47. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  48. package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
  49. package/plugins/harness-everything/plugin.json +1 -1
  50. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  51. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  52. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  53. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  54. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  55. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  56. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  57. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  58. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  59. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  60. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  61. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  62. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  63. package/sbom.cdx.json +7 -7
  64. package/scripts/ci-change-scope.js +59 -0
  65. package/scripts/handoff-file.js +223 -0
  66. package/scripts/sync-openai-plugin.js +4 -0
  67. package/scripts/system-one-calibrate.js +108 -41
  68. package/scripts/system-one-curves.js +332 -0
  69. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  70. package/scripts/system-one-cycle/build.js +165 -0
  71. package/scripts/system-one-cycle/collect.js +50 -0
  72. package/scripts/system-one-cycle/common.js +137 -0
  73. package/scripts/system-one-cycle/engines.js +62 -0
  74. package/scripts/system-one-cycle/evaluate.js +70 -0
  75. package/scripts/system-one-cycle/judge.js +106 -0
  76. package/scripts/system-one-cycle/label.js +59 -0
  77. package/scripts/system-one-cycle/package.js +173 -0
  78. package/scripts/system-one-cycle/score.py +111 -0
  79. package/scripts/system-one-cycle/train.js +136 -0
  80. package/scripts/system-one-cycle.js +131 -0
  81. package/scripts/system-one-observations-export.js +29 -6
  82. package/scripts/system-one-observations-review.js +4 -5
  83. package/scripts/system-one-train.py +117 -61
@@ -0,0 +1,585 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawnSync } = require('node:child_process');
8
+ const { test } = require('node:test');
9
+ const { buildDataset } = require('../scripts/system-one-cycle/build');
10
+ const { collect } = require('../scripts/system-one-cycle/collect');
11
+ const { judgeRows } = require('../scripts/system-one-cycle/judge');
12
+ const { runGuarded, processTreeRssMb } = require('../scripts/system-one-cycle/train');
13
+ const { buildVersion, trainerCatalogs } = require('../scripts/system-one-cycle/package');
14
+ const install = require('../harness-everything/scripts/system-one/install');
15
+ const provider = require('../harness-everything/scripts/system-one/provider');
16
+ const router = require('../harness-everything/scripts/system-one/router');
17
+ const { CATALOGS } = require('../harness-everything/scripts/system-one/catalogs');
18
+
19
+ const root = fs.realpathSync.native(path.resolve(__dirname, '..'));
20
+
21
+ function writeJsonl(file, rows) {
22
+ fs.mkdirSync(path.dirname(file), { recursive: true });
23
+ fs.writeFileSync(file, rows.map(row => JSON.stringify(row)).join('\n') + (rows.length ? '\n' : ''));
24
+ }
25
+
26
+ function syntheticCycle(dir) {
27
+ const training = path.join(dir, 'training');
28
+ const prompts = [
29
+ { id: 'agent-dispatch', family: 'family-agent', source: 'agent-dispatch', split: 'train', text: 'synthetic-agent-dispatch-case', previous: 'synthetic-previous-field' },
30
+ { id: 'agrees', family: 'family-agrees', source: 'observation', split: 'train', text: 'synthetic-agreement-case', previous: 'synthetic-previous-field' },
31
+ { id: 'legacy-intent-shape', family: 'family-legacy-intent', source: 'observation', split: 'train', text: 'synthetic-legacy-intent-case' },
32
+ { id: 'intent-majority', family: 'family-intent-majority', source: 'observation', split: 'train', text: 'synthetic-intent-majority-case' },
33
+ { id: 'intent-no-majority', family: 'family-intent-no-majority', source: 'observation', split: 'train', text: 'synthetic-intent-no-majority-case' },
34
+ { id: 'tier-only', family: 'family-tier-only', source: 'observation', split: 'train', text: 'synthetic-tier-only-case' },
35
+ { id: 'writes', family: 'family-writes', source: 'observation', split: 'train', text: 'synthetic-write-evidence-case' },
36
+ { id: 'vote', family: 'family-vote', source: 'observation', split: 'train', text: 'synthetic-majority-vote-case' },
37
+ { id: 'null-vote', family: 'family-null-vote', source: 'observation', split: 'train', text: 'synthetic-null-consensus-case' },
38
+ { id: 'validity-conflict', family: 'family-validity-conflict', source: 'observation', split: 'train', text: 'synthetic-validity-conflict-case' },
39
+ { id: 'split-train', family: 'family-split-train', source: 'observation', split: 'train', text: 'same normalized synthetic phrase' },
40
+ { id: 'split-validation', family: 'family-split-validation', source: 'observation', split: 'validation', text: 'Same, normalized synthetic phrase!' },
41
+ { id: 'no-majority', family: 'family-no-majority', source: 'observation', split: 'train', text: 'synthetic-no-majority-case' },
42
+ { id: 'no-vote', family: 'family-no-vote', source: 'observation', split: 'train', text: 'synthetic-missing-vote-case' },
43
+ { id: 'holdout-copy', family: 'family-holdout', source: 'observation', split: 'train', text: 'holdout only synthetic sentinel' },
44
+ { id: 'invalid', family: 'family-invalid', source: 'observation', split: 'train', text: 'synthetic-context-dependent-case' },
45
+ ];
46
+ writeJsonl(path.join(training, 'observed/prompts-observed.jsonl'), prompts);
47
+ writeJsonl(path.join(training, 'observed/labels-observed.jsonl'), [
48
+ { id: 'agrees', tier: 'tier2', intents: ['feature'], contextDependent: true, contradictions: [], behaviorEvidence: 'unobserved' },
49
+ { id: 'legacy-intent-shape', tier: 'tier2', contradictions: [], behaviorEvidence: 'unobserved' },
50
+ { id: 'intent-majority', tier: 'tier2', intents: ['fix'], contradictions: [], behaviorEvidence: 'unobserved' },
51
+ { id: 'intent-no-majority', tier: 'tier2', intents: ['edit'], contradictions: [], behaviorEvidence: 'unobserved' },
52
+ { id: 'tier-only', tier: 'tier1', intents: ['review'], contradictions: [], behaviorEvidence: 'unobserved' },
53
+ { id: 'writes', tier: 'tier1', intents: ['feature'], contextDependent: true, contradictions: ['tier1-with-writes'], behaviorEvidence: 'observed' },
54
+ { id: 'vote', tier: 'tier1', intents: ['feature'], contextDependent: true, contradictions: [], behaviorEvidence: 'unobserved' },
55
+ { id: 'null-vote', tier: 'tier2', intents: ['feature'], contextDependent: false, contradictions: [], behaviorEvidence: 'unobserved' },
56
+ { id: 'validity-conflict', tier: 'tier2', intents: [], contextDependent: true, contradictions: [], behaviorEvidence: 'unobserved' },
57
+ { id: 'split-train', tier: 'tier2', intents: ['feature'], contextDependent: false, contradictions: [], behaviorEvidence: 'observed' },
58
+ { id: 'split-validation', tier: 'tier2', intents: ['feature'], contextDependent: false, contradictions: [], behaviorEvidence: 'observed' },
59
+ { id: 'no-majority', tier: 'tier1', intents: ['feature'], contextDependent: false, contradictions: [], behaviorEvidence: 'observed' },
60
+ { id: 'no-vote', tier: 'tier1', intents: ['feature'], contextDependent: false, contradictions: [], behaviorEvidence: 'observed' },
61
+ { id: 'invalid', tier: null, intents: [], contextDependent: true, contradictions: [], behaviorEvidence: 'unobserved' },
62
+ ]);
63
+ writeJsonl(path.join(training, 'relabel-luna/labels.jsonl'), [
64
+ ...['agent-dispatch', 'agrees', 'legacy-intent-shape', 'intent-majority', 'intent-no-majority', 'writes', 'split-train', 'split-validation'].map(id => ({ id, gold: id === 'writes' ? 'tier1' : id === 'agrees' || id === 'legacy-intent-shape' || id.startsWith('intent-') || id.startsWith('split') ? 'tier2' : 'tier3' })),
65
+ { id: 'tier-only', gold: 'tier2' },
66
+ { id: 'vote', gold: 'tier2' }, { id: 'null-vote', gold: 'tier1' }, { id: 'validity-conflict', gold: null },
67
+ { id: 'no-majority', gold: 'tier2' }, { id: 'no-vote', gold: 'tier2' },
68
+ { id: 'holdout-copy', gold: 'tier2' }, { id: 'invalid', gold: null },
69
+ ]);
70
+ writeJsonl(path.join(training, 'relabel-luna/labels-intent.jsonl'), prompts.map(row => ({
71
+ id: row.id,
72
+ gold: row.id === 'invalid' || row.id === 'holdout-copy' || row.id === 'validity-conflict' ? null
73
+ : row.id === 'intent-no-majority' ? 'explain' : row.id === 'tier-only' ? 'review'
74
+ : row.id === 'legacy-intent-shape' ? 'explain' : 'feature',
75
+ secondary: [],
76
+ })));
77
+ writeJsonl(path.join(training, 'adjudication/consensus.jsonl'), [
78
+ { id: 'vote', status: 'majority', consensus: 'tier3', votes: [{ judge: 'luna', tier: 'tier3' }, { judge: 'opencode', tier: 'tier3' }] },
79
+ { id: 'intent-majority', status: 'majority', consensus: 'tier2', intentStatus: 'majority', intentConsensus: 'fix',
80
+ votes: [{ judge: 'luna', tier: 'tier2', intent: 'fix' }, { judge: 'opencode', tier: 'tier2', intent: 'fix' }] },
81
+ { id: 'intent-no-majority', status: 'majority', consensus: 'tier2', intentStatus: 'no-majority', intentConsensus: null,
82
+ votes: [{ judge: 'luna', tier: 'tier2', intent: 'edit' }, { judge: 'opencode', tier: 'tier2', intent: 'feature' }] },
83
+ { id: 'tier-only', status: 'majority', consensus: 'tier3',
84
+ votes: [{ judge: 'luna', tier: 'tier3' }, { judge: 'opencode', tier: 'tier3' }] },
85
+ { id: 'null-vote', status: 'unanimous', consensus: null, votes: [{ judge: 'luna', tier: null }, { judge: 'opencode', tier: null }] },
86
+ { id: 'validity-conflict', status: 'majority', consensus: 'tier2', votes: [{ judge: 'luna', tier: 'tier2' }, { judge: 'opencode', tier: 'tier2' }] },
87
+ { id: 'no-majority', status: 'no-majority', consensus: null, votes: [{ judge: 'luna', tier: 'tier2' }, { judge: 'opencode', tier: 'tier3' }] },
88
+ ]);
89
+ const holdout = path.join(dir, 'holdout.json');
90
+ fs.writeFileSync(holdout, JSON.stringify({ schemaVersion: 1, cases: [{ request: { context: 'holdout-only synthetic sentinel' } }] }));
91
+ return { training, holdout };
92
+ }
93
+
94
+ function assertNoDatasetOutputs(...dirs) {
95
+ for (const dir of dirs) {
96
+ for (const file of ['prompts.jsonl', 'labels.jsonl', 'labels-intent.jsonl', 'report.json']) {
97
+ assert.equal(fs.existsSync(path.join(dir, file)), false, `unexpected dataset output ${file}`);
98
+ }
99
+ }
100
+ }
101
+
102
+ test('cycle dataset uses text-only labels, consensus, behavior evidence, holdout fields, and private prompt elision', t => {
103
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-build-'));
104
+ try {
105
+ const fixture = syntheticCycle(dir);
106
+ const report = buildDataset({ dataDir: dir, holdoutFiles: [fixture.holdout] });
107
+ const output = path.join(fixture.training, 'v1');
108
+ const prompts = fs.readFileSync(path.join(output, 'prompts.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
109
+ const labels = new Map(fs.readFileSync(path.join(output, 'labels.jsonl'), 'utf8').trim().split('\n').map(JSON.parse).map(row => [row.id, row.gold]));
110
+ const validityLabels = new Map(fs.readFileSync(path.join(fixture.training, 'v1-validity/labels.jsonl'), 'utf8').trim().split('\n').map(JSON.parse).map(row => [row.id, row.gold]));
111
+ const intents = new Map(fs.readFileSync(path.join(output, 'labels-intent.jsonl'), 'utf8').trim().split('\n').map(JSON.parse).map(row => [row.id, row]));
112
+ const ids = new Set(prompts.map(row => row.id));
113
+
114
+ assert.equal(ids.has('agent-dispatch'), true);
115
+ assert.equal(labels.get('agrees'), 'tier2');
116
+ assert.equal(intents.get('agrees').gold, 'feature');
117
+ assert.equal(intents.get('legacy-intent-shape').gold, 'explain');
118
+ assert.equal(labels.get('vote'), 'tier3');
119
+ assert.equal(labels.get('null-vote'), null);
120
+ assert.equal(labels.get('validity-conflict'), 'tier2');
121
+ assert.equal(validityLabels.get('validity-conflict'), null);
122
+ assert.equal(labels.has('intent-no-majority'), true);
123
+ assert.equal(validityLabels.get('intent-no-majority'), 'tier2');
124
+ assert.equal(labels.get('tier-only'), 'tier3');
125
+ assert.equal(labels.get('writes'), 'tier2');
126
+ assert.equal(labels.has('no-majority'), false);
127
+ assert.equal(labels.has('no-vote'), false);
128
+ assert.equal(labels.has('holdout-copy'), false);
129
+ assert.equal(labels.has('split-train'), false);
130
+ assert.equal(labels.has('split-validation'), true);
131
+ assert.equal(labels.get('invalid'), null);
132
+ assert.deepEqual(intents.get('invalid'), { id: 'invalid', gold: null, secondary: [] });
133
+ assert.equal(intents.get('intent-majority').gold, 'fix');
134
+ assert.equal(intents.has('intent-no-majority'), false);
135
+ assert.equal(intents.get('tier-only').gold, 'review');
136
+ assert.ok(prompts.every(row => Object.keys(row).sort().join(',') === 'family,id,source,split,text'));
137
+ assert.equal(fs.readFileSync(path.join(output, 'report.json'), 'utf8').includes('synthetic-'), false);
138
+ assert.equal(report.droppedByReason['no-majority'], 1);
139
+ assert.equal(report.droppedByReason['intent-no-majority'], 1);
140
+ assert.equal(report.droppedByReason['no-vote'], 1);
141
+ } finally {
142
+ fs.rmSync(dir, { recursive: true, force: true });
143
+ }
144
+ });
145
+
146
+ test('collect preserves self-reported intents from the actual session export shape', t => {
147
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-collect-'));
148
+ const sessions = path.join(dir, 'sessions');
149
+ try {
150
+ fs.mkdirSync(sessions, { recursive: true });
151
+ const startedAt = new Date(Date.now() - 60_000).toISOString();
152
+ const completedAt = new Date(Date.now() - 30_000).toISOString();
153
+ const label = { v: 1, validity: 'actionable', tier: 'tier2', intents: ['fix', 'explain'], workflow: null, skills: [] };
154
+ const session = [
155
+ { type: 'session_meta', payload: { session_id: 'synthetic-collect-session' } },
156
+ { type: 'event_msg', timestamp: startedAt, payload: { type: 'task_started', turn_id: 'synthetic-turn', started_at: startedAt } },
157
+ { type: 'response_item', timestamp: startedAt, payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'synthetic collect intent case' }] } },
158
+ { type: 'event_msg', timestamp: completedAt, payload: { type: 'task_complete', turn_id: 'synthetic-turn', completed_at: completedAt,
159
+ last_agent_message: `Synthetic response\n<!-- harness-label ${JSON.stringify(label)} -->` } },
160
+ ];
161
+ fs.writeFileSync(path.join(sessions, 'synthetic.jsonl'), session.map(row => JSON.stringify(row)).join('\n') + '\n');
162
+ const since = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10);
163
+ const dataDir = path.join(dir, 'cycle');
164
+
165
+ collect({ dataDir, since, sessionsDir: sessions });
166
+
167
+ const labels = fs.readFileSync(path.join(dataDir, 'training/observed/labels-observed.jsonl'), 'utf8')
168
+ .trim().split('\n').map(JSON.parse);
169
+ assert.equal(labels.length, 1);
170
+ assert.deepEqual(labels[0].intents, ['fix', 'explain']);
171
+ } finally {
172
+ fs.rmSync(dir, { recursive: true, force: true });
173
+ }
174
+ });
175
+
176
+ test('cycle dataset rejects direct, aliased, and unresolved checkout destinations before writing either output', t => {
177
+ for (const aliasKind of ['direct', 'ancestor', 'leaf', 'unresolved']) {
178
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-private-destination-'));
179
+ const forbidden = fs.mkdtempSync(path.join(root, 'ci', '.s1-f9-forbidden-'));
180
+ let alias;
181
+ try {
182
+ const fixture = syntheticCycle(dir);
183
+ let validityOutDir = forbidden;
184
+ if (aliasKind !== 'direct') {
185
+ alias = path.join(dir, `forbidden-${aliasKind}`);
186
+ try { fs.symlinkSync(aliasKind === 'unresolved' ? path.join(forbidden, 'missing-target') : forbidden, alias, 'dir'); }
187
+ catch (error) {
188
+ if (['EACCES', 'EPERM', 'ENOSYS', 'ENOTSUP'].includes(error.code)) {
189
+ t.skip(`directory symlinks unavailable: ${error.code}`);
190
+ return;
191
+ }
192
+ throw error;
193
+ }
194
+ validityOutDir = aliasKind === 'leaf' ? alias : path.join(alias, 'missing', 'validity');
195
+ }
196
+
197
+ const safeOutput = path.join(dir, 'safe-output');
198
+ if (aliasKind === 'unresolved') {
199
+ assert.throws(() => buildDataset({ dataDir: dir, holdoutFiles: [fixture.holdout],
200
+ outDir: safeOutput, validityOutDir }), error => error.code === 'ENOENT');
201
+ } else {
202
+ assert.throws(() => buildDataset({ dataDir: dir, holdoutFiles: [fixture.holdout],
203
+ outDir: safeOutput, validityOutDir }), /outside the repository/);
204
+ }
205
+ assertNoDatasetOutputs(safeOutput, forbidden);
206
+ } finally {
207
+ if (alias) fs.rmSync(alias, { recursive: true, force: true });
208
+ fs.rmSync(forbidden, { recursive: true, force: true });
209
+ fs.rmSync(dir, { recursive: true, force: true });
210
+ }
211
+ }
212
+ });
213
+
214
+ test('cycle dataset accepts an external data directory through an external symlink alias', t => {
215
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-external-alias-'));
216
+ const dataDir = path.join(dir, 'data');
217
+ const alias = path.join(dir, 'data-alias');
218
+ try {
219
+ const fixture = syntheticCycle(dataDir);
220
+ try { fs.symlinkSync(dataDir, alias, 'dir'); }
221
+ catch (error) {
222
+ if (['EACCES', 'EPERM', 'ENOSYS', 'ENOTSUP'].includes(error.code)) {
223
+ t.skip(`directory symlinks unavailable: ${error.code}`);
224
+ return;
225
+ }
226
+ throw error;
227
+ }
228
+
229
+ buildDataset({ dataDir: alias, holdoutFiles: [fixture.holdout] });
230
+ assert.equal(fs.existsSync(path.join(dataDir, 'training', 'v1', 'prompts.jsonl')), true);
231
+ } finally {
232
+ fs.rmSync(dir, { recursive: true, force: true });
233
+ }
234
+ });
235
+
236
+ test('cycle dataset keeps the .s1-work exception tied to the canonical synthetic destination', t => {
237
+ const base = path.join(root, '.s1-work');
238
+ fs.mkdirSync(base, { recursive: true });
239
+ const dataDir = fs.mkdtempSync(path.join(base, 'f9-canonical-exception-'));
240
+ const alias = path.join(os.tmpdir(), `system-one-cycle-s1-work-alias-${process.pid}`);
241
+ try {
242
+ const fixture = syntheticCycle(dataDir);
243
+ const promptFile = path.join(fixture.training, 'observed', 'prompts-observed.jsonl');
244
+ const prompts = fs.readFileSync(promptFile, 'utf8').trim().split('\n').map(JSON.parse)
245
+ .map(row => ({ ...row, text: 'agent request without the fixture marker' }));
246
+ writeJsonl(promptFile, prompts);
247
+ try { fs.symlinkSync(dataDir, alias, 'dir'); }
248
+ catch (error) {
249
+ if (['EACCES', 'EPERM', 'ENOSYS', 'ENOTSUP'].includes(error.code)) {
250
+ t.skip(`directory symlinks unavailable: ${error.code}`);
251
+ return;
252
+ }
253
+ throw error;
254
+ }
255
+
256
+ assert.throws(() => buildDataset({ dataDir: alias, holdoutFiles: [fixture.holdout] }), /synthetic fixture rows/);
257
+ assertNoDatasetOutputs(path.join(dataDir, 'training', 'v1'), path.join(dataDir, 'training', 'v1-validity'));
258
+ } finally {
259
+ fs.rmSync(alias, { recursive: true, force: true });
260
+ fs.rmSync(dataDir, { recursive: true, force: true });
261
+ }
262
+ });
263
+
264
+ test('cycle dataset requires the real holdout request.context field', t => {
265
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-holdout-'));
266
+ try {
267
+ const fixture = syntheticCycle(dir);
268
+ fs.writeFileSync(fixture.holdout, JSON.stringify({ schemaVersion: 1, cases: [{ request: { task: 'tier' } }] }));
269
+ assert.throws(() => buildDataset({ dataDir: dir, holdoutFiles: [fixture.holdout] }), /request\.context/);
270
+ } finally {
271
+ fs.rmSync(dir, { recursive: true, force: true });
272
+ }
273
+ });
274
+
275
+ test('cycle dataset rejects duplicate observed prompt ids', t => {
276
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-duplicate-'));
277
+ try {
278
+ const fixture = syntheticCycle(dir);
279
+ const promptsFile = path.join(fixture.training, 'observed/prompts-observed.jsonl');
280
+ const prompts = fs.readFileSync(promptsFile, 'utf8').trim().split('\n').map(JSON.parse);
281
+ writeJsonl(promptsFile, [...prompts, { ...prompts[0], text: 'synthetic-duplicate-id-case' }]);
282
+ assert.throws(() => buildDataset({ dataDir: dir, holdoutFiles: [fixture.holdout] }), /duplicate prompt id/);
283
+ } finally {
284
+ fs.rmSync(dir, { recursive: true, force: true });
285
+ }
286
+ });
287
+
288
+ test('judge resumes completed rows and records no-majority without prompt text', async t => {
289
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-judge-'));
290
+ try {
291
+ const training = path.join(dir, 'training');
292
+ writeJsonl(path.join(training, 'observed/prompts-observed.jsonl'), [
293
+ { id: 'done', family: 'f1', source: 'observation', split: 'train', text: 'synthetic-completed-case', previous: 'synthetic-private-context' },
294
+ { id: 'todo', family: 'f2', source: 'observation', split: 'train', text: 'synthetic-pending-case', previous: 'synthetic-private-context' },
295
+ { id: 'intent-only', family: 'f3', source: 'observation', split: 'train', text: 'synthetic-intent-disagreement-case' },
296
+ { id: 'tier-only-no-intent-label', family: 'f4', source: 'observation', split: 'train', text: 'synthetic-tier-disagreement-case' },
297
+ ]);
298
+ writeJsonl(path.join(training, 'observed/labels-observed.jsonl'), [
299
+ { id: 'done', tier: 'tier1', intents: ['feature'] }, { id: 'todo', tier: 'tier1', intents: ['feature'] },
300
+ { id: 'intent-only', tier: 'tier2', intents: ['fix'] },
301
+ { id: 'tier-only-no-intent-label', tier: 'tier1', intents: ['feature'] },
302
+ ]);
303
+ writeJsonl(path.join(training, 'relabel-luna/labels.jsonl'), [
304
+ { id: 'done', gold: 'tier2' }, { id: 'todo', gold: 'tier2' }, { id: 'intent-only', gold: 'tier2' },
305
+ { id: 'tier-only-no-intent-label', gold: 'tier2' },
306
+ ]);
307
+ writeJsonl(path.join(training, 'relabel-luna/labels-intent.jsonl'), [
308
+ { id: 'done', gold: 'feature', secondary: [] }, { id: 'todo', gold: 'feature', secondary: [] },
309
+ { id: 'intent-only', gold: 'feature', secondary: [] },
310
+ ]);
311
+ writeJsonl(path.join(training, 'adjudication/consensus.jsonl'), [
312
+ { id: 'done', status: 'majority', consensus: 'tier2', votes: [{ judge: 'luna', tier: 'tier2' }, { judge: 'opencode', tier: 'tier2' }] },
313
+ ]);
314
+ const calls = [];
315
+ const report = await judgeRows({ dataDir: dir, runJudge: async (engine, batch) => {
316
+ calls.push(engine);
317
+ assert.deepEqual(batch.map(row => row.id), ['todo', 'intent-only', 'tier-only-no-intent-label']);
318
+ return batch.map((row, i) => ({ i,
319
+ tier: row.id === 'intent-only' ? 'tier2' : (engine === 'luna' ? 'tier2' : 'tier3'),
320
+ ...(row.selfIntent === undefined ? {} : { intent: 'fix' }),
321
+ }));
322
+ } });
323
+ const saved = fs.readFileSync(path.join(training, 'adjudication/consensus.jsonl'), 'utf8');
324
+ const rows = saved.trim().split('\n').map(JSON.parse);
325
+ const input = fs.readFileSync(path.join(training, 'adjudication/input.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
326
+
327
+ assert.deepEqual(calls, ['luna', 'opencode']);
328
+ assert.equal(report.voted, 3);
329
+ assert.equal(rows.find(row => row.id === 'todo').status, 'no-majority');
330
+ assert.equal(rows.find(row => row.id === 'intent-only').intentStatus, 'majority');
331
+ assert.equal(rows.find(row => row.id === 'intent-only').intentConsensus, 'fix');
332
+ assert.equal(saved.includes('synthetic-'), false);
333
+ assert.deepEqual(input.map(row => row.id), ['done', 'todo', 'intent-only', 'tier-only-no-intent-label']);
334
+ assert.equal(new Set(input.map(row => row.id)).size, input.length);
335
+ assert.deepEqual(Object.keys(input[0]).sort(), ['id', 'lunaTier', 'selfTier', 'text']);
336
+ assert.deepEqual(Object.keys(input.find(row => row.id === 'intent-only')).sort(),
337
+ ['id', 'lunaIntent', 'lunaTier', 'selfIntent', 'selfTier', 'text']);
338
+ assert.deepEqual(Object.keys(input.find(row => row.id === 'tier-only-no-intent-label')).sort(),
339
+ ['id', 'lunaTier', 'selfTier', 'text']);
340
+ } finally {
341
+ fs.rmSync(dir, { recursive: true, force: true });
342
+ }
343
+ });
344
+
345
+ test('resource guard kills an over-limit child and records peak RSS', async () => {
346
+ let samples = 0;
347
+ let rssReader;
348
+ try { processTreeRssMb(process.pid); rssReader = processTreeRssMb; }
349
+ catch { rssReader = () => (++samples === 1 ? 48 : 128); }
350
+ const result = await runGuarded(process.execPath, ['-e', 'const b=Buffer.allocUnsafe(160*1024*1024); for(let i=0;i<b.length;i+=4096)b[i]=1; const {spawn}=require("node:child_process"); spawn(process.execPath,["-e","setInterval(()=>{},1000)"],{stdio:"ignore"}); setInterval(()=>{},1000);'], {
351
+ maxRssMb: 96, threads: 4, pollMs: 100, rssReader,
352
+ });
353
+ assert.equal(result.killedForLimit, true);
354
+ assert.ok(result.peakRssMb > 96);
355
+ assert.equal(result.monitorFailed, false);
356
+ });
357
+
358
+ test('package writes the contract B manifest and carries evaluation into the private version directory', t => {
359
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-package-'));
360
+ try {
361
+ const version = 'synthetic-v1';
362
+ const runs = path.join(dir, 'training', 'runs', version);
363
+ const catalogs = trainerCatalogs();
364
+ const thresholds = Object.fromEntries(Object.entries(catalogs).map(([task, options]) => [task,
365
+ Object.fromEntries(options.map(id => [id, id === 'unclassified' ? null : 0.5]))]));
366
+ for (const [task, values] of Object.entries(thresholds)) {
367
+ const stage = path.join(runs, task);
368
+ fs.mkdirSync(stage, { recursive: true });
369
+ fs.writeFileSync(path.join(stage, 'harness-routing-v1.safetensors'), `${task}-weights`);
370
+ fs.writeFileSync(path.join(stage, 'harness-routing-v1.json'), JSON.stringify({ context_tokens: 1024 }));
371
+ fs.writeFileSync(path.join(stage, 'calibration.json'), JSON.stringify({ thresholds: values }));
372
+ }
373
+ const candidate = path.join(dir, 'training', 'candidates', version);
374
+ buildVersion({ dataDir: dir, version, sourceDir: runs, versionDir: candidate });
375
+ fs.mkdirSync(path.join(candidate, 'evaluation'), { recursive: true });
376
+ fs.writeFileSync(path.join(candidate, 'evaluation', 'curves.json'), '{}\n');
377
+ fs.writeFileSync(path.join(candidate, 'evaluation', 'trend.json'), '{}\n');
378
+
379
+ const output = path.join(dir, 'training', 'versions', version);
380
+ buildVersion({ dataDir: dir, version, sourceDir: candidate, versionDir: output });
381
+ const manifest = JSON.parse(fs.readFileSync(path.join(output, 'manifest.json'), 'utf8'));
382
+
383
+ assert.deepEqual(Object.keys(manifest).sort(), ['createdAt', 'evaluation', 'schemaVersion', 'stages', 'version']);
384
+ assert.equal(manifest.schemaVersion, 1);
385
+ assert.equal(manifest.version, version);
386
+ assert.equal(manifest.evaluation, 'evaluation/curves.json');
387
+ assert.deepEqual(manifest.stages.validity.options, catalogs.validity);
388
+ assert.deepEqual(manifest.stages.intent.options, catalogs.intent);
389
+ assert.ok(manifest.stages.intent.options.includes('unclassified'));
390
+ assert.deepEqual(Object.keys(manifest.stages.intent.thresholds), catalogs.intent);
391
+ assert.equal(manifest.stages.intent.thresholds.unclassified, 1);
392
+ assert.ok(manifest.stages.intent.referenceOnly.includes('unclassified'));
393
+ assert.deepEqual(manifest.stages.tier.thresholds, thresholds.tier);
394
+ assert.deepEqual(Object.keys(manifest.stages.tier.thresholds), catalogs.tier);
395
+ assert.match(manifest.stages.intent.sha256, /^[0-9a-f]{64}$/);
396
+ assert.equal(fs.existsSync(path.join(output, 'evaluation', 'trend.json')), true);
397
+ assert.equal('referenceOnly' in manifest.stages.validity, false);
398
+ } finally {
399
+ fs.rmSync(dir, { recursive: true, force: true });
400
+ }
401
+ });
402
+
403
+ function writePackageRuns(dir, version, calibrationByTask) {
404
+ const runs = path.join(dir, 'training', 'runs', version);
405
+ for (const [task, values] of Object.entries(calibrationByTask)) {
406
+ const stage = path.join(runs, task);
407
+ fs.mkdirSync(stage, { recursive: true });
408
+ fs.writeFileSync(path.join(stage, 'harness-routing-v1.safetensors'), `${task}-weights`);
409
+ fs.writeFileSync(path.join(stage, 'harness-routing-v1.json'), JSON.stringify({ context_tokens: 1024 }));
410
+ fs.writeFileSync(path.join(stage, 'calibration.json'), JSON.stringify({ thresholds: values }));
411
+ }
412
+ return runs;
413
+ }
414
+
415
+ function trainerThresholds(value = 0.5) {
416
+ return Object.fromEntries(Object.entries(trainerCatalogs()).map(([task, options]) => [task,
417
+ Object.fromEntries(options.map(id => [id, id === 'unclassified' ? null : value]))]));
418
+ }
419
+
420
+ test('package turns a null calibration threshold into 1 and carries referenceOnly through repackaging', t => {
421
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-package-null-'));
422
+ try {
423
+ const version = 'synthetic-null-v1';
424
+ const thresholds = trainerThresholds();
425
+ thresholds.tier.tier2 = null;
426
+ const runs = writePackageRuns(dir, version, thresholds);
427
+ const candidate = path.join(dir, 'training', 'candidates', version);
428
+ buildVersion({ dataDir: dir, version, sourceDir: runs, versionDir: candidate });
429
+ const candidateManifest = JSON.parse(fs.readFileSync(path.join(candidate, 'manifest.json'), 'utf8'));
430
+ assert.equal(candidateManifest.stages.tier.thresholds.tier2, 1);
431
+ assert.deepEqual(candidateManifest.stages.tier.referenceOnly, ['tier2']);
432
+
433
+ const output = path.join(dir, 'training', 'versions', version);
434
+ buildVersion({ dataDir: dir, version, sourceDir: candidate, versionDir: output });
435
+ const manifest = JSON.parse(fs.readFileSync(path.join(output, 'manifest.json'), 'utf8'));
436
+ assert.equal(manifest.stages.tier.thresholds.tier2, 1);
437
+ assert.deepEqual(manifest.stages.tier.referenceOnly, ['tier2']);
438
+ assert.equal('referenceOnly' in manifest.stages.validity, false);
439
+ } finally {
440
+ fs.rmSync(dir, { recursive: true, force: true });
441
+ }
442
+ });
443
+
444
+ test('package restores omitted unclassified metadata from a prior candidate without retraining', t => {
445
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-package-legacy-catalog-'));
446
+ try {
447
+ const version = 'synthetic-legacy-catalog-v1';
448
+ const thresholds = trainerThresholds();
449
+ const runs = writePackageRuns(dir, version, thresholds);
450
+ const candidate = path.join(dir, 'training', 'candidates', version);
451
+ buildVersion({ dataDir: dir, version, sourceDir: runs, versionDir: candidate });
452
+
453
+ const manifestFile = path.join(candidate, 'manifest.json');
454
+ const oldManifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
455
+ oldManifest.stages.intent.options = oldManifest.stages.intent.options.filter(id => id !== 'unclassified');
456
+ delete oldManifest.stages.intent.thresholds.unclassified;
457
+ oldManifest.stages.intent.referenceOnly = oldManifest.stages.intent.referenceOnly.filter(id => id !== 'unclassified');
458
+ if (!oldManifest.stages.intent.referenceOnly.length) delete oldManifest.stages.intent.referenceOnly;
459
+ fs.writeFileSync(manifestFile, JSON.stringify(oldManifest));
460
+
461
+ const output = path.join(dir, 'training', 'versions', version);
462
+ buildVersion({ dataDir: dir, version, sourceDir: candidate, versionDir: output });
463
+ const manifest = JSON.parse(fs.readFileSync(path.join(output, 'manifest.json'), 'utf8'));
464
+ assert.ok(manifest.stages.intent.options.includes('unclassified'));
465
+ assert.equal(manifest.stages.intent.thresholds.unclassified, 1);
466
+ assert.ok(manifest.stages.intent.referenceOnly.includes('unclassified'));
467
+ assert.deepEqual(Object.keys(manifest.stages.intent.thresholds), manifest.stages.intent.options);
468
+ } finally {
469
+ fs.rmSync(dir, { recursive: true, force: true });
470
+ }
471
+ });
472
+
473
+ test('package still rejects a non-null non-finite threshold', t => {
474
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-package-nan-'));
475
+ try {
476
+ const version = 'synthetic-nan-v1';
477
+ const thresholds = trainerThresholds();
478
+ const runs = writePackageRuns(dir, version, thresholds);
479
+ // 1e999 overflows to Infinity, the non-null non-finite value JSON can carry.
480
+ const calibration = path.join(runs, 'tier', 'calibration.json');
481
+ const serialized = JSON.stringify({ thresholds: thresholds.tier });
482
+ const keyValue = `${JSON.stringify('tier2')}:${thresholds.tier.tier2}`;
483
+ fs.writeFileSync(calibration, serialized.replace(keyValue, `${JSON.stringify('tier2')}:1e999`));
484
+ assert.throws(() => buildVersion({ dataDir: dir, version, sourceDir: runs,
485
+ versionDir: path.join(dir, 'training', 'versions', version) }), /finite per-option thresholds/);
486
+ } finally {
487
+ fs.rmSync(dir, { recursive: true, force: true });
488
+ }
489
+ });
490
+
491
+ test('package publishes a trainer-catalog version that installs, activates, and reports reference-only scores', async t => {
492
+ const dir = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-roundtrip-')));
493
+ const home = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'system-one-cycle-home-')));
494
+ try {
495
+ const version = 'synthetic-roundtrip-v1';
496
+ const catalogs = trainerCatalogs();
497
+ const thresholds = Object.fromEntries(Object.entries(catalogs).map(([task, options]) => [task,
498
+ Object.fromEntries(options.map(id => [id, id === 'unclassified' ? null : 0.5]))]));
499
+ thresholds.intent.fix = null;
500
+ thresholds.tier.tier3 = null;
501
+ const runs = writePackageRuns(dir, version, thresholds);
502
+ const versionDir = path.join(dir, 'training', 'versions', version);
503
+ buildVersion({ dataDir: dir, version, sourceDir: runs, versionDir });
504
+ const packaged = JSON.parse(fs.readFileSync(path.join(versionDir, 'manifest.json'), 'utf8'));
505
+ for (const [stage, ids] of Object.entries(catalogs)) {
506
+ assert.deepEqual(packaged.stages[stage].options, ids);
507
+ assert.deepEqual(Object.keys(packaged.stages[stage].thresholds), ids);
508
+ }
509
+ assert.deepEqual(packaged.stages.intent.referenceOnly, ['fix', 'unclassified']);
510
+ const scoreScript = path.join(root, 'scripts/system-one-cycle/score.py');
511
+ const pythonCode = "import importlib.util,json,sys; spec=importlib.util.spec_from_file_location('score',sys.argv[1]); module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module); print(json.dumps([o['id'] for o in module.trained_catalog(sys.argv[2],'intent',sys.argv[3])]))";
512
+ const scoredCatalog = spawnSync(process.env.PYTHON || 'python3', ['-c', pythonCode, scoreScript,
513
+ path.join(versionDir, 'intent.safetensors'), path.join(root, 'benchmarks/fixtures/system-one-intent-holdout.json')],
514
+ { cwd: root, encoding: 'utf8' });
515
+ assert.equal(scoredCatalog.status, 0, scoredCatalog.stderr);
516
+ assert.deepEqual(JSON.parse(scoredCatalog.stdout), catalogs.intent);
517
+
518
+ const publishCommand = spawnSync(process.execPath, [path.join(root, 'scripts/system-one-cycle.js'), 'publish',
519
+ '--data-dir', dir, '--version', version], { cwd: root, encoding: 'utf8' });
520
+ assert.equal(publishCommand.status, 0, publishCommand.stderr);
521
+ const published = JSON.parse(publishCommand.stdout).steps[0];
522
+ assert.equal(published.publishedPath, path.join(dir, 'models', 'cua-s1', version));
523
+
524
+ install.installVersion(dir, version, home);
525
+ install.activate(version, home);
526
+ const env = { HARNESS_SYSTEM_ONE_HOME: home };
527
+ const active = provider.readActive(env);
528
+ assert.equal(active.version, version);
529
+ const liveCatalogs = {
530
+ validity: router.VALIDITY_OPTIONS,
531
+ intent: CATALOGS.intent,
532
+ tier: router.TIER_OPTIONS,
533
+ };
534
+ const result = await provider.scoreLive('synthetic request', env, liveCatalogs, async (_stage, request) => ({
535
+ status: 'scored',
536
+ response: {
537
+ schemaVersion: 1, requestHash: request.requestHash, catalogHash: request.catalogHash,
538
+ model: { id: version, revision: version, domain: 'harness-routing-v1' },
539
+ scores: request.options.map(option => ({ id: option.id,
540
+ probability: option.id === 'fix' || option.id === 'tier3' ? 0.99 : option.id === 'tier2' ? 0.8 : 0.1 })),
541
+ },
542
+ }));
543
+ assert.deepEqual(result.referenceOnly, { validity: [], intent: ['fix', 'unclassified'], tier: ['tier3'] });
544
+ assert.equal(result.stageScores.intent.fix, 0.99);
545
+ assert.equal(result.stageScores.intent.unclassified, 0.1);
546
+ assert.equal(result.stageScores.tier.tier3, 0.99);
547
+ const routed = router.routeLive({ tier: 'Tier 1 (Trivial)', floor: null, explicit: false }, result);
548
+ assert.equal(routed.systemOne.intents.fix, 0.99);
549
+ assert.equal(Object.hasOwn(routed.systemOne.intents, 'unclassified'), false);
550
+ assert.equal(routed.systemOne.decision.intents.includes('fix'), false);
551
+ assert.equal(routed.systemOne.decision.tier, 'tier2');
552
+ assert.deepEqual(routed.reference.referenceOnlyOptions, [
553
+ { stage: 'intent', id: 'fix', probability: 0.99 }, { stage: 'intent', id: 'unclassified', probability: 0.1 },
554
+ { stage: 'tier', id: 'tier3', probability: 0.99 },
555
+ ]);
556
+ } finally {
557
+ fs.rmSync(dir, { recursive: true, force: true });
558
+ fs.rmSync(home, { recursive: true, force: true });
559
+ }
560
+ });
561
+
562
+ test('all --until build uses prepared synthetic stages and stops before training', t => {
563
+ const base = path.join(root, '.s1-work');
564
+ fs.mkdirSync(base, { recursive: true });
565
+ const dir = fs.mkdtempSync(path.join(base, 'cycle-until-build-'));
566
+ try {
567
+ const fixture = syntheticCycle(dir);
568
+ fs.writeFileSync(path.join(dir, 'cycle-state.json'), JSON.stringify({ schemaVersion: 1, steps: {
569
+ collect: { completedAt: '2026-11-14T00:00:00.000Z' },
570
+ label: { completedAt: '2026-11-14T00:00:00.000Z' },
571
+ judge: { completedAt: '2026-11-14T00:00:00.000Z' },
572
+ } }));
573
+ const result = spawnSync(process.execPath, [path.join(root, 'scripts/system-one-cycle.js'), 'all', '--until', 'build', '--data-dir', dir, '--holdout', fixture.holdout], {
574
+ cwd: root, encoding: 'utf8',
575
+ });
576
+ assert.equal(result.status, 0, result.stderr);
577
+ assert.equal(result.stdout.includes('synthetic-'), false);
578
+ const state = JSON.parse(fs.readFileSync(path.join(dir, 'cycle-state.json'), 'utf8'));
579
+ assert.ok(state.steps.build.completedAt);
580
+ assert.equal(state.steps.train, undefined);
581
+ assert.equal(fs.existsSync(path.join(dir, 'training/runs')), false);
582
+ } finally {
583
+ fs.rmSync(dir, { recursive: true, force: true });
584
+ }
585
+ });