harness-everything 0.29.0 → 0.30.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 (88) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +1 -0
  4. package/CHANGELOG.md +35 -0
  5. package/PRIVACY.md +9 -0
  6. package/benchmarks/fixtures/system-one-intent-holdout-draft.json +2228 -0
  7. package/benchmarks/fixtures/system-one-intent-holdout.json +16509 -0
  8. package/benchmarks/fixtures/system-one-intent-reviews.json +2723 -0
  9. package/benchmarks/results/system-one/intent-ngram-v1-2026-09-24/README.md +64 -0
  10. package/benchmarks/results/system-one/intent-ngram-v1-2026-09-24/report.json +15177 -0
  11. package/benchmarks/results/system-one/labeler-holdout-check-intent-2026-09-24/report.json +2976 -0
  12. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-005-steps.json +6125 -0
  13. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-haiku-sonnet-escalation.json +6344 -0
  14. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-scaled-margin-escalation.json +6206 -0
  15. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report.json +6103 -0
  16. package/benchmarks/results/system-one/laya-ft-2026-09-25/README.md +83 -0
  17. package/benchmarks/results/system-one/laya-ft-2026-09-25/report.json +71 -0
  18. package/benchmarks/results/system-one/laya-ft-2026-09-25/shadow-report.json +44 -0
  19. package/benchmarks/results/system-one/laya-zs-2026-09-25/README.md +68 -0
  20. package/benchmarks/results/system-one/laya-zs-2026-09-25/report.json +173 -0
  21. package/ci/mechanism-34-observations.test.js +550 -0
  22. package/ci/mechanism-system-one-collect.test.js +16 -0
  23. package/ci/mechanism-system-one-intent.test.js +406 -0
  24. package/ci/mechanism-system-one-laya.test.js +45 -0
  25. package/ci/mechanism-system-one-relevance.test.js +112 -0
  26. package/ci/mechanism-system-one-resident.test.js +16 -0
  27. package/ci/system-one-laya-calibrate-test.py +65 -0
  28. package/ci/system-one-laya-export-test.py +155 -0
  29. package/ci/system-one-laya-label-test.py +201 -0
  30. package/ci/system-one-laya-perintent-test.py +60 -0
  31. package/ci/system-one-laya-provider-test.py +115 -0
  32. package/ci/system-one-laya-train-test.py +93 -0
  33. package/docs/routing.md +25 -0
  34. package/docs/system-one-intent-gates.md +102 -0
  35. package/docs/system-one-intent.md +173 -0
  36. package/docs/system-one-laya-training.md +38 -0
  37. package/docs/system-one-observations.md +206 -0
  38. package/docs/system-one-routing.md +25 -10
  39. package/docs/system-one-suggestion-gates.md +292 -0
  40. package/docs/system-one-training.md +56 -6
  41. package/harness-everything/SKILL.md +1 -1
  42. package/harness-everything/scripts/kernel-router.js +10 -0
  43. package/harness-everything/scripts/system-one/catalogs.js +35 -0
  44. package/harness-everything/scripts/system-one/contract.js +45 -1
  45. package/harness-everything/scripts/system-one/evaluate.js +115 -19
  46. package/harness-everything/scripts/system-one/intent.js +22 -0
  47. package/harness-everything/scripts/system-one/laya_adapter.py +141 -0
  48. package/harness-everything/scripts/system-one/provider.js +10 -3
  49. package/harness-everything/scripts/system-one/resident.js +8 -3
  50. package/harness-everything/scripts/system-one/router.js +1 -1
  51. package/hooks/hooks.json +40 -0
  52. package/hooks/scripts/codex-user-prompt.js +39 -0
  53. package/hooks/scripts/lib/observations.js +581 -0
  54. package/hooks/scripts/observation-hook.js +25 -0
  55. package/opencode-plugin/plugin.json +1 -1
  56. package/package.json +1 -1
  57. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  58. package/plugins/harness-everything/hooks/hooks.json +35 -2
  59. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +39 -0
  60. package/plugins/harness-everything/hooks/scripts/lib/observations.js +581 -0
  61. package/plugins/harness-everything/hooks/scripts/observation-hook.js +25 -0
  62. package/plugins/harness-everything/plugin.json +1 -1
  63. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  64. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +10 -0
  65. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/catalogs.js +35 -0
  66. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +45 -1
  67. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +115 -19
  68. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/intent.js +22 -0
  69. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/laya_adapter.py +141 -0
  70. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +10 -3
  71. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +8 -3
  72. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +1 -1
  73. package/sbom.cdx.json +7 -7
  74. package/scripts/evaluate-system-one.js +17 -5
  75. package/scripts/system-one-calibrate-laya.py +165 -0
  76. package/scripts/system-one-calibrate.js +42 -13
  77. package/scripts/system-one-collect.js +7 -3
  78. package/scripts/system-one-compare-laya.py +156 -0
  79. package/scripts/system-one-corpus.js +22 -15
  80. package/scripts/system-one-eval-laya.js +112 -0
  81. package/scripts/system-one-export-laya.py +197 -0
  82. package/scripts/system-one-label-laya.py +243 -0
  83. package/scripts/system-one-label.js +163 -37
  84. package/scripts/system-one-observations-export.js +106 -0
  85. package/scripts/system-one-observations-review.js +86 -0
  86. package/scripts/system-one-perintent-laya.py +134 -0
  87. package/scripts/system-one-train-laya.py +344 -0
  88. package/scripts/system-one-train-ngram.py +66 -14
@@ -0,0 +1,406 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { createRequest } = require('../harness-everything/scripts/system-one/contract');
7
+ const { TIER_OPTIONS } = require('../harness-everything/scripts/system-one/router');
8
+ const { INTENT_OPTIONS, CATALOGS, goldLabels } = require('../harness-everything/scripts/system-one/catalogs');
9
+ const { validateCorpus, evaluate } = require('../harness-everything/scripts/system-one/evaluate');
10
+ const { gradedAgreement, familyConsistency } = require('../harness-everything/scripts/system-one/intent');
11
+ const { build, promptHash } = require('../scripts/system-one-corpus');
12
+ const label = require('../scripts/system-one-label');
13
+ const root = path.resolve(__dirname, '..');
14
+ const INTENTS = ['explain', 'discuss', 'git', 'fix', 'edit', 'feature', 'refactor', 'review', 'test', 'docs', 'plan', 'investigate'];
15
+
16
+ test('S1-I01 the intent catalog is the owner\'s fixed list, frozen, beside the tier catalog', () => {
17
+ assert.deepEqual(INTENT_OPTIONS.map(o => o.id), [...INTENTS, 'unclassified']);
18
+ assert.ok(Object.isFrozen(INTENT_OPTIONS) && INTENT_OPTIONS.every(o => Object.isFrozen(o) && o.text.length > 0));
19
+ assert.equal(CATALOGS.tier, TIER_OPTIONS);
20
+ assert.equal(CATALOGS.intent, INTENT_OPTIONS);
21
+ assert.deepEqual(goldLabels('intent'), [...INTENTS, null]);
22
+ assert.deepEqual(goldLabels('tier'), ['tier1', 'tier2', 'tier3', null]);
23
+ assert.throws(() => goldLabels('skills'));
24
+ assert.notEqual(createRequest('intent', 'fix it', INTENT_OPTIONS).catalogHash, createRequest('tier', 'fix it', TIER_OPTIONS).catalogHash);
25
+ });
26
+
27
+ const intentCase = (id, gold, language = 'en', secondary = []) => ({ id, family: `f-${id}`, split: 'holdout', language, source: 'human:fixture', reviewed: false,
28
+ request: createRequest('intent', `prompt ${id}`, INTENT_OPTIONS), gold, secondary });
29
+ const model = { id: 'fixture', revision: 'v1', domain: 'harness-routing-v1' };
30
+ const oneHot = id => INTENT_OPTIONS.map(o => (o.id === (id || 'unclassified') ? 1 : 0));
31
+ const run = id => ({ decision: { status: id ? 'accepted' : 'abstain', reason: id ? 'scored' : 'unclassified', selectedId: id, confidence: 1, margin: 1, model },
32
+ scores: oneHot(id), latencyMs: 1, coldStart: false });
33
+
34
+ test('S1-I02 the evaluator scores an intent corpus over the intent labels only', () => {
35
+ const corpus = { schemaVersion: 1, cases: [intentCase('a', 'fix'), intentCase('b', null, 'zh-TW')] };
36
+ assert.equal(validateCorpus(corpus), true);
37
+ const records = corpus.cases.map(c => ({ id: c.id, baseline: 'fix', runs: [run(c.gold), run(c.gold)] }));
38
+ const report = evaluate(corpus, records, null, { secondaryThreshold: 0.2 });
39
+ assert.equal(report.model.accuracy, 1);
40
+ assert.equal(report.model.coverage, 0.5);
41
+ assert.equal(report.model.macroF1, 2 / 13, 'thirteen intent labels, two of them present and perfect');
42
+ assert.equal(report.baseline.accuracy, 0.5);
43
+ assert.equal(validateCorpus({ schemaVersion: 1, cases: [intentCase('s', 'edit', 'en', ['test', 'docs'])] }), true);
44
+ const bad = [
45
+ c => { c.cases[0].gold = 'tier1'; },
46
+ c => { delete c.cases[0].secondary; },
47
+ c => { c.cases[0].secondary = ['fix']; },
48
+ c => { c.cases[0].secondary = ['test', 'test']; },
49
+ c => { c.cases[0].secondary = ['unclassified']; },
50
+ c => { c.cases[1].secondary = ['test']; },
51
+ c => { const { secondary, ...tierCase } = intentCase('t', 'tier1'); c.cases.push({ ...tierCase, request: createRequest('tier', 'prompt t', TIER_OPTIONS) }); },
52
+ c => { c.cases[0].request = createRequest('intent', 'prompt a', INTENT_OPTIONS.slice(0, 4)); },
53
+ ];
54
+ for (const mutate of bad) { const c = JSON.parse(JSON.stringify(corpus)); mutate(c); assert.throws(() => validateCorpus(c)); }
55
+ const shortScores = records.map(r => ({ ...r, runs: r.runs.map(x => ({ ...x, scores: x.scores.slice(0, 4) })) }));
56
+ assert.throws(() => evaluate(corpus, shortScores, null, { secondaryThreshold: 0.2 }), 'score vectors follow the intent catalog length');
57
+ const tierBaseline = records.map(r => ({ ...r, baseline: 'tier2' }));
58
+ assert.throws(() => evaluate(corpus, tierBaseline, null, { secondaryThreshold: 0.2 }));
59
+ });
60
+
61
+ test('S1-I03 the corpus assembler builds an intent holdout from its own draft and reviews', () => {
62
+ const draftCase = (id, proposedGold, prompt) => ({ id, family: `family-${id}`, language: 'en', source: 'synthetic:authored', prompt, proposedGold, rationale: 'fixture' });
63
+ const draft = { schemaVersion: 1, cases: [draftCase('a', 'git', 'commit and push'), draftCase('b', 'fix', 'the parser crashes, fix it'), draftCase('c', null, 'go')] };
64
+ const decisions = [
65
+ { id: 'a', promptHash: promptHash('commit and push'), decision: 'accept', gold: 'git', secondary: [], reviewer: 'human:repository-owner' },
66
+ { id: 'b', promptHash: promptHash('the parser crashes, fix it'), decision: 'relabel', gold: 'investigate', secondary: ['fix', 'test'], reviewer: 'human:repository-owner' },
67
+ ];
68
+ const { corpus, summary } = build(draft, { schemaVersion: 1, decisions }, 'intent');
69
+ assert.ok(corpus.cases.every(c => c.request.task === 'intent' && JSON.stringify(c.request.options) === JSON.stringify(INTENT_OPTIONS)));
70
+ assert.deepEqual(corpus.cases.map(c => [c.id, c.gold, c.secondary, c.reviewed]), [['a', 'git', [], true], ['b', 'investigate', ['fix', 'test'], true], ['c', null, [], false]]);
71
+ assert.equal(summary.byGold.git, 1); assert.equal(summary.byGold.investigate, 1); assert.equal(summary.byGold.unclassified, 1);
72
+ assert.equal(Object.keys(summary.byGold).length, 13);
73
+ assert.deepEqual(summary.bySecondary, { fix: 1, test: 1 });
74
+ for (const mutate of [d => { delete d.secondary; }, d => { d.secondary = ['investigate']; }, d => { d.secondary = ['fix', 'fix']; }, d => { d.secondary = ['tier1']; }, d => { d.secondary = 'fix'; }]) {
75
+ const bad = decisions.map(d => ({ ...d, secondary: [...d.secondary] })); mutate(bad[1]);
76
+ assert.throws(() => build(draft, { schemaVersion: 1, decisions: bad }, 'intent'));
77
+ }
78
+ assert.throws(() => build(draft, { schemaVersion: 1, decisions: [{ id: 'c', promptHash: promptHash('go'), decision: 'accept', gold: null, secondary: ['git'], reviewer: 'human:repository-owner' }] }, 'intent'), 'null has no secondary');
79
+ assert.throws(() => build({ schemaVersion: 1, cases: [draftCase('a', 'tier1', 'commit and push')] }, null, 'intent'));
80
+ assert.throws(() => build(draft, { schemaVersion: 1, decisions: [{ ...decisions[0], decision: 'relabel', gold: 'tier1' }] }, 'intent'));
81
+ assert.throws(() => build(draft, null, 'skills'));
82
+ assert.equal(build({ schemaVersion: 1, cases: [draftCase('a', 'tier1', 'commit and push')] }, null).corpus.cases[0].request.task, 'tier', 'tier stays the default');
83
+ });
84
+
85
+ test('S1-I04 the labeler labels intent from the intent document with the intent labels only', async () => {
86
+ const rules = label.rulesFromDoc(fs.readFileSync(path.join(root, 'docs/system-one-intent.md'), 'utf8'), 'intent');
87
+ assert.match(rules, /^## Intent labels/);
88
+ assert.match(rules, /\| `investigate` \|/);
89
+ assert.match(rules, /One primary intent/);
90
+ assert.doesNotMatch(rules, /## Holdout/);
91
+ assert.throws(() => label.rulesFromDoc('# nothing here', 'intent'));
92
+ const batch = [{ id: 'x', text: 'fix it' }, { id: 'y', text: 'go' }];
93
+ const prompt = label.buildPrompt(rules, batch, 'intent');
94
+ assert.match(prompt, /explain, discuss, git, fix, edit, feature, refactor, review, test, docs, plan, investigate, or null/);
95
+ assert.doesNotMatch(prompt, /tier1/);
96
+ assert.match(label.buildPrompt('r', batch), /tier1, tier2, tier3, or null/, 'tier stays the default');
97
+ assert.match(prompt, /secondary/, 'intent replies carry secondary intents');
98
+ const ok = { labels: [{ i: 0, gold: 'fix', secondary: ['test'] }, { i: 1, gold: 'null', secondary: [] }] };
99
+ assert.deepEqual(label.validateReply(batch, ok, 'intent'), [{ gold: 'fix', secondary: ['test'] }, { gold: null, secondary: [] }]);
100
+ for (const bad of [
101
+ { labels: [{ i: 0, gold: 'tier1', secondary: [] }, { i: 1, gold: 'null', secondary: [] }] },
102
+ { labels: [{ i: 0, gold: 'fix' }, { i: 1, gold: 'null', secondary: [] }] },
103
+ { labels: [{ i: 0, gold: 'fix', secondary: ['fix'] }, { i: 1, gold: 'null', secondary: [] }] },
104
+ { labels: [{ i: 0, gold: 'fix', secondary: [] }, { i: 1, gold: 'null', secondary: ['git'] }] },
105
+ ]) assert.equal(label.validateReply(batch, bad, 'intent'), null);
106
+ assert.equal(label.validateReply(batch, { labels: [{ i: 0, gold: 'fix' }, { i: 1, gold: 'null' }] }), null, 'tier replies reject intent labels');
107
+ assert.deepEqual(label.validateReply(batch, { labels: [{ i: 0, gold: 'tier1' }, { i: 1, gold: 'null' }] }), ['tier1', null], 'tier replies keep their shape');
108
+ const schema = JSON.parse(label.schemaFor('intent')).properties.labels.items;
109
+ assert.deepEqual(schema.properties.gold.enum, [...INTENTS, 'null']);
110
+ assert.deepEqual(schema.required, ['i', 'gold', 'secondary']);
111
+ assert.deepEqual(schema.properties.secondary.items.enum, INTENTS);
112
+ assert.deepEqual(JSON.parse(label.schemaFor('tier')).properties.labels.items.required, ['i', 'gold']);
113
+ const report = label.agreement([{ id: 'x', gold: 'fix', secondary: ['test'] }, { id: 'y', gold: 'docs', secondary: [] }],
114
+ { x: { gold: 'test', secondary: ['fix'] }, y: { gold: 'git', secondary: [] } }, 'intent');
115
+ assert.deepEqual(Object.keys(report.recall), [...INTENTS, 'unclassified']);
116
+ assert.equal(report.agreement, 0);
117
+ assert.equal(report.graded, 0.3, '(0.6 swapped + 0 unrelated) / 2');
118
+ assert.deepEqual(report.confusion, { 'fix->test': 1, 'docs->git': 1 });
119
+ const seen = [];
120
+ const out = await label.labelAll(batch, { rules, task: 'intent', run: async p => { seen.push(p); return ok; } });
121
+ assert.deepEqual(out.labeled, [{ id: 'x', gold: 'fix', secondary: ['test'] }, { id: 'y', gold: null, secondary: [] }]);
122
+ assert.match(seen[0], /investigate, or null/);
123
+ });
124
+
125
+ test('S1-I05 graded agreement follows the owner\'s grades and is symmetric', () => {
126
+ const l = (gold, secondary = []) => ({ gold, secondary });
127
+ const cases = [
128
+ [l('fix', ['test']), l('fix', ['docs', 'review']), 1],
129
+ [l('fix', ['test']), l('test', ['fix']), 0.6],
130
+ [l('fix', ['test', 'docs', 'review', 'plan']), l('test', ['fix']), 0.3],
131
+ [l('fix', ['test', 'docs', 'review']), l('test', ['fix']), 0.6],
132
+ [l('fix', ['test']), l('test'), 0.3],
133
+ [l('fix'), l('docs', ['review']), 0],
134
+ [l(null), l(null), 1],
135
+ [l(null), l('fix'), 0],
136
+ ];
137
+ for (const [a, b, want] of cases) {
138
+ assert.equal(gradedAgreement(a, b), want, JSON.stringify([a, b]));
139
+ assert.equal(gradedAgreement(b, a), want, 'symmetric');
140
+ }
141
+ });
142
+
143
+ const IDS = [...INTENTS, 'unclassified'];
144
+ // A probability vector with the given masses; the rest is spread evenly over the other options.
145
+ const probs = masses => { const rest = (1 - Object.values(masses).reduce((s, v) => s + v, 0)) / (IDS.length - Object.keys(masses).length);
146
+ return IDS.map(id => (Object.hasOwn(masses, id) ? masses[id] : rest)); };
147
+
148
+ test('S1-I07 intent calibration uses graded precision and picks a secondary threshold on validation', () => {
149
+ const { calibrate } = require('../scripts/system-one-calibrate');
150
+ const rows = [
151
+ { id: 'a', gold: 'fix', secondary: ['test'], probs: probs({ fix: 0.6, test: 0.3 }) },
152
+ { id: 'b', gold: 'test', secondary: ['fix'], probs: probs({ fix: 0.55, test: 0.35 }) },
153
+ { id: 'c', gold: 'docs', secondary: [], probs: probs({ git: 0.4, docs: 0.35 }) },
154
+ ];
155
+ const c = calibrate(rows, { task: 'intent' });
156
+ assert.equal(c.secondaryThreshold, 0.05, 'lowest threshold with the best secondary micro-F1');
157
+ assert.deepEqual([c.feasible, c.minConfidence, c.minMargin, c.accepted, c.precision], [true, 0.5, 0.25, 1, 1]);
158
+ const loose = calibrate(rows, { task: 'intent', minPrecision: 0.8 });
159
+ assert.deepEqual([loose.minConfidence, loose.minMargin, loose.accepted], [0.5, 0, 2]);
160
+ assert.equal(loose.precision, 0.8, 'graded: (1 + 0.6) / 2');
161
+ assert.equal(loose.exactPrecision, 0.5);
162
+ assert.equal(calibrate([{ id: 'x', gold: 'tier1', probs: [0.9, 0.05, 0.05, 0] }]).secondaryThreshold, undefined, 'tier calibration is unchanged');
163
+ });
164
+
165
+ test('S1-I08 the ngram trainer trains the intent stage with soft targets (skipped without torch)', t => {
166
+ const { spawnSync } = require('node:child_process');
167
+ const os = require('node:os');
168
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
169
+ if (spawnSync(python, ['-c', 'import torch'], { encoding: 'utf8' }).status !== 0) { t.skip('torch not installed'); return; }
170
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-intent-'));
171
+ try {
172
+ const data = path.join(dir, 'data'); fs.mkdirSync(data);
173
+ const texts = [['commit and push', 'git', []], ['fix the crash and add a test', 'fix', ['test']], ['explain this flag', 'explain', []], ['go', null, []]];
174
+ const prompts = []; const labels = [];
175
+ for (let k = 0; k < 10; k++) texts.forEach(([x, g, s], i) => { const id = `p${k}-${i}`; prompts.push({ id, family: `f${k}`, source: 'claude', split: k < 8 ? 'train' : 'validation', text: `${x} ${k}` }); labels.push({ id, gold: g, secondary: s }); });
176
+ fs.writeFileSync(path.join(data, 'prompts.jsonl'), prompts.map(x => JSON.stringify(x)).join('\n') + '\n');
177
+ fs.writeFileSync(path.join(data, 'labels-intent.jsonl'), labels.map(x => JSON.stringify(x)).join('\n') + '\n');
178
+ fs.writeFileSync(path.join(data, 'owner-overrides-intent.jsonl'), `${JSON.stringify({ id: 'p9-2', gold: 'docs', secondary: ['explain'] })}\n`);
179
+ fs.writeFileSync(path.join(data, 'labels.jsonl'), `${JSON.stringify({ id: 'p0-0', gold: 'tier1' })}\n`);
180
+ const out = path.join(dir, 'model');
181
+ const r = spawnSync(python, [path.join(root, 'scripts/system-one-train-ngram.py'), '--task', 'intent', '--data-dir', data, '--out', out, '--dim', '4096', '--epochs', '40'], { encoding: 'utf8' });
182
+ assert.equal(r.status, 0, r.stdout + r.stderr);
183
+ const side = JSON.parse(fs.readFileSync(path.join(out, 'harness-routing-v1.json'), 'utf8'));
184
+ assert.deepEqual(side.catalog, IDS);
185
+ assert.equal(side.metadata.task, 'intent');
186
+ const scores = fs.readFileSync(path.join(out, 'val-scores.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
187
+ assert.equal(scores.length, 8);
188
+ assert.ok(scores.every(s => s.probs.length === IDS.length && Array.isArray(s.secondary)));
189
+ assert.deepEqual(scores.find(s => s.id === 'p9-2'), { ...scores.find(s => s.id === 'p9-2'), gold: 'docs', secondary: ['explain'] }, 'owner intent override applies');
190
+ const fixRow = scores.find(s => s.id === 'p8-1');
191
+ assert.ok(fixRow.probs[IDS.indexOf('fix')] > fixRow.probs[IDS.indexOf('test')] && fixRow.probs[IDS.indexOf('test')] > fixRow.probs[IDS.indexOf('git')], 'soft targets rank the primary, then the secondary');
192
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
193
+ });
194
+
195
+ test('S1-I09 the manifest carries an optional secondary threshold that decide never sees', () => {
196
+ const provider = require('../harness-everything/scripts/system-one/provider');
197
+ const { decide } = require('../harness-everything/scripts/system-one/contract');
198
+ const base = { schemaVersion: 1, transport: 'ngram', checkpoint: path.join(root, 'x.bin'), weightsSha256: 'a'.repeat(64), configSha256: 'b'.repeat(64),
199
+ modelId: 'fixture/intent', revision: 'v1', domain: 'harness-routing-v1' };
200
+ assert.equal(provider.validateManifest({ ...base, acceptance: { minConfidence: 0.5, minMargin: 0, secondaryThreshold: 0.2 } }), true);
201
+ for (const s of [0.01, 0.6, '0.2']) assert.throws(() => provider.validateManifest({ ...base, acceptance: { minConfidence: 0.5, minMargin: 0, secondaryThreshold: s } }));
202
+ assert.equal(provider.decisionPolicy({ minConfidence: 0.5, minMargin: 0.1, secondaryThreshold: 0.2 }).secondaryThreshold, undefined);
203
+ assert.deepEqual(provider.decisionPolicy({ minConfidence: 0.5, minMargin: 0.1, secondaryThreshold: 0.2 }), { minConfidence: 0.5, minMargin: 0.1 });
204
+ assert.deepEqual(provider.decisionPolicy(undefined), {});
205
+ const request = createRequest('intent', 'fix it', INTENT_OPTIONS);
206
+ const response = { schemaVersion: 1, requestHash: request.requestHash, catalogHash: request.catalogHash, model: { id: 'm', revision: 'v1', domain: 'harness-routing-v1' },
207
+ scores: INTENT_OPTIONS.map(o => ({ id: o.id, probability: o.id === 'fix' ? 0.88 : 0.01 })) };
208
+ assert.equal(decide(request, response, provider.decisionPolicy({ minConfidence: 0.5, minMargin: 0, secondaryThreshold: 0.2 })).selectedId, 'fix');
209
+ });
210
+
211
+ test('S1-I10 the evaluator grades accepted intent predictions and reports family consistency', () => {
212
+ const s = masses => probs(masses);
213
+ const corpus = { schemaVersion: 1, cases: [
214
+ { ...intentCase('a', 'fix', 'en', ['test']), family: 'f' },
215
+ { ...intentCase('b', 'test', 'zh-TW', ['fix']), family: 'f' },
216
+ ] };
217
+ const predict = scores => { const top = Math.max(...scores); const id = IDS[scores.indexOf(top)]; const second = [...scores].sort((x, y) => y - x)[1];
218
+ return { decision: { status: 'accepted', reason: 'scored', selectedId: id, confidence: top, margin: top - second, model }, scores, latencyMs: 1, coldStart: false }; };
219
+ const records = corpus.cases.map(c => ({ id: c.id, baseline: 'fix', runs: [predict(s({ fix: 0.6, test: 0.3 })), predict(s({ fix: 0.6, test: 0.3 }))] }));
220
+ const report = evaluate(corpus, records, null, { secondaryThreshold: 0.2 });
221
+ assert.equal(report.model.acceptedPrecision, 0.8, 'graded: (1 + 0.6) / 2');
222
+ assert.equal(report.model.exactPrecision, 0.5);
223
+ assert.equal(report.gates.acceptedPrecision, false);
224
+ assert.deepEqual(report.familyConsistency, { gold: { families: 1, consistent: 0, rate: 0 }, model: { families: 1, consistent: 1, rate: 1 } });
225
+ assert.throws(() => evaluate(corpus, records), 'an intent evaluation needs its secondary threshold');
226
+ const tier = { schemaVersion: 1, cases: [{ id: 't', family: 't', split: 'holdout', language: 'en', source: 'human:fixture', reviewed: false, request: createRequest('tier', 'commit', TIER_OPTIONS), gold: 'tier1' }] };
227
+ const tierRun = { decision: { status: 'accepted', reason: 'scored', selectedId: 'tier1', confidence: 1, margin: 1, model }, scores: [1, 0, 0, 0], latencyMs: 1, coldStart: false };
228
+ const tierReport = evaluate(tier, [{ id: 't', baseline: 'tier1', runs: [tierRun, tierRun] }]);
229
+ assert.equal(tierReport.model.exactPrecision, undefined, 'tier reports keep their shape');
230
+ assert.equal(tierReport.familyConsistency, undefined);
231
+ });
232
+
233
+ test('S1-I11 the evaluation CLI scores an intent holdout with a majority-class baseline', () => {
234
+ const os = require('node:os'); const { spawnSync } = require('node:child_process'); const { createHash } = require('node:crypto');
235
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-intent-eval-'));
236
+ try {
237
+ const sha = f => createHash('sha256').update(fs.readFileSync(f)).digest('hex');
238
+ const bin = path.join(dir, 'intent.bin'); const json = path.join(dir, 'intent.json');
239
+ fs.writeFileSync(bin, Buffer.from(new Float32Array(1024 * IDS.length).buffer));
240
+ fs.writeFileSync(json, JSON.stringify({ format: 'harness-ngram', formatVersion: 1, dim: 1024, nmax: 2, hash: 'fnv1a32', catalog: IDS,
241
+ bias: IDS.map(id => (id === 'fix' ? 3 : 0)), metadata: { task: 'intent' } }));
242
+ const manifest = path.join(dir, 'manifest.json');
243
+ fs.writeFileSync(manifest, JSON.stringify({ schemaVersion: 1, transport: 'ngram', checkpoint: bin, weightsSha256: sha(bin), configSha256: sha(json),
244
+ modelId: 'fixture/intent', revision: 'v1', domain: 'harness-routing-v1', acceptance: { minConfidence: 0.5, minMargin: 0, secondaryThreshold: 0.2 } }));
245
+ const corpus = path.join(dir, 'corpus.json');
246
+ fs.writeFileSync(corpus, JSON.stringify({ schemaVersion: 1, cases: [intentCase('a', 'fix', 'en', ['test']), intentCase('b', 'test', 'zh-TW', ['fix'])] }));
247
+ const out = path.join(dir, 'report.json');
248
+ const r = spawnSync(process.execPath, [path.join(root, 'scripts/evaluate-system-one.js'), corpus, manifest, out], { encoding: 'utf8', cwd: root });
249
+ assert.equal(r.status, 0, r.stderr);
250
+ const report = JSON.parse(fs.readFileSync(out, 'utf8'));
251
+ assert.equal(report.model.coverage, 1);
252
+ assert.equal(report.model.acceptedPrecision, 0.65, 'graded: (1 + 0.3) / 2');
253
+ assert.equal(report.model.exactPrecision, 0.5);
254
+ assert.ok(report.records.every(x => x.baseline === 'fix'), 'majority gold, ties broken by catalog order');
255
+ assert.equal(report.evidence.secondaryThreshold, 0.2);
256
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
257
+ });
258
+
259
+ test('S1-I06 family consistency counts families of two or more that share one primary', () => {
260
+ const rows = [
261
+ { family: 'a', primary: 'fix' }, { family: 'a', primary: 'fix' },
262
+ { family: 'b', primary: 'fix' }, { family: 'b', primary: 'feature' },
263
+ { family: 'c', primary: 'git' },
264
+ ];
265
+ assert.deepEqual(familyConsistency(rows), { families: 2, consistent: 1, rate: 0.5 });
266
+ assert.deepEqual(familyConsistency([{ family: 'c', primary: 'git' }]), { families: 0, consistent: 0, rate: null });
267
+ });
268
+
269
+ const LEVELS = Array.from({ length: 21 }, (_, k) => Number((k / 20).toFixed(2)));
270
+ // Scores for every intent: the given levels, 0 elsewhere.
271
+ const scored = levels => Object.fromEntries(INTENTS.map(id => [id, Object.hasOwn(levels, id) ? levels[id] : 0]));
272
+
273
+ test('S1-I12 the labeler asks for tie-free relevance scores and derives the bands from them', async () => {
274
+ const rules = label.rulesFromDoc(fs.readFileSync(path.join(root, 'docs/system-one-intent.md'), 'utf8'), 'intent');
275
+ assert.match(rules, /### Relevance scores/, 'the band table reaches the labeler');
276
+ const opts = { scores: true };
277
+ const schema = JSON.parse(label.schemaFor('intent', opts)).properties.labels.items;
278
+ assert.deepEqual(schema.required, ['i', 'primary', 'scores']);
279
+ assert.deepEqual(schema.properties.primary.enum, [...INTENTS, 'null']);
280
+ assert.deepEqual(schema.properties.scores.required, INTENTS);
281
+ assert.equal(schema.properties.scores.additionalProperties, false);
282
+ assert.ok(INTENTS.every(id => JSON.stringify(schema.properties.scores.properties[id].enum) === JSON.stringify(LEVELS)), '0 to 1 in steps of 0.05');
283
+ assert.throws(() => label.schemaFor('tier', opts), 'only the intent stage has scores');
284
+ const batch = [{ id: 'x', text: 'fix the crash, update the docs and add a test' }, { id: 'y', text: 'go' }];
285
+ const prompt = label.buildPrompt(rules, batch, 'intent', opts);
286
+ assert.match(prompt, /steps of 0\.05/);
287
+ assert.match(prompt, /no two intents share a score above 0/i);
288
+ assert.match(prompt, /primary/);
289
+ assert.doesNotMatch(prompt, /Also return secondary/, 'the secondary intents come from the bands');
290
+ const x = scored({ fix: 0.8, docs: 0.65, test: 0.45, review: 0.3, investigate: 0.1, plan: 0.05 });
291
+ const y = scored({ explain: 0.2, investigate: 0.15, discuss: 0.1, plan: 0.05 });
292
+ const ok = { labels: [{ i: 0, primary: 'fix', scores: x }, { i: 1, primary: 'null', scores: y }] };
293
+ assert.deepEqual(label.validateReply(batch, ok, 'intent', opts), [
294
+ { gold: 'fix', secondary: ['docs', 'test'], scores: x },
295
+ { gold: null, secondary: [], scores: y },
296
+ ], 'secondary: every other intent at 0.4 or more, highest first');
297
+ const second = { i: 1, primary: 'null', scores: y };
298
+ for (const first of [
299
+ { i: 0, primary: 'fix', scores: { ...x, test: 0.65 } },
300
+ { i: 0, primary: 'fix', scores: scored({ fix: 0.8, docs: 0.4, test: 0.2 }) },
301
+ { i: 0, primary: 'fix', scores: { ...x, test: 0.33 } },
302
+ { i: 0, primary: 'fix', scores: { ...x, fix: 1.05 } },
303
+ { i: 0, primary: 'docs', scores: x },
304
+ { i: 0, primary: 'fix', scores: { ...x, fix: 0.55, docs: 0.5 } },
305
+ { i: 0, primary: 'fix', scores: (({ docs, ...rest }) => rest)(x) },
306
+ { i: 0, primary: 'fix', scores: { ...x, unclassified: 0 } },
307
+ { i: 0, primary: 'unclassified', scores: x },
308
+ { i: 0, primary: 'fix', gold: 'fix', scores: x },
309
+ ]) assert.equal(label.validateReply(batch, { labels: [first, second] }, 'intent', opts), null, JSON.stringify(first));
310
+ assert.equal(label.validateReply(batch, { labels: [{ i: 0, primary: 'fix', scores: x }, { i: 1, primary: 'null', scores: { ...y, explain: 0.25 } }] }, 'intent', opts), null,
311
+ 'a null primary leaves no intent above 0.2');
312
+ assert.deepEqual(label.validateReply(batch, { labels: [{ i: 0, primary: 'fix', scores: { ...x, fix: 1 } }, second] }, 'intent', opts)[0].gold, 'fix', '1 is on the scale');
313
+ const out = await label.labelAll(batch, { rules, task: 'intent', scores: true, run: async () => ok });
314
+ assert.deepEqual(out.labeled[0], { id: 'x', gold: 'fix', secondary: ['docs', 'test'], scores: x });
315
+ const report = label.agreement([{ id: 'x', gold: 'fix', secondary: ['test', 'docs', 'review'] }, { id: 'y', gold: null, secondary: [] }],
316
+ { x: out.labeled[0], y: out.labeled[1] }, 'intent');
317
+ assert.equal(report.graded, 1);
318
+ assert.deepEqual(report.bands, { goldSecondary: 1.5, secondary: 1, related: 1 }, 'means per case: owner secondary, labeler 0.4+ and 0.2 to 0.35 bands');
319
+ assert.equal(label.agreement([{ id: 'x', gold: 'fix', secondary: [] }], { x: { gold: 'fix', secondary: [] } }, 'intent').bands, undefined, 'unscored labels keep their report');
320
+ });
321
+
322
+ test('S1-I13 the ngram trainer learns scored intent labels as per-intent targets (skipped without torch)', t => {
323
+ const { spawnSync } = require('node:child_process');
324
+ const os = require('node:os');
325
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
326
+ if (spawnSync(python, ['-c', 'import torch'], { encoding: 'utf8' }).status !== 0) { t.skip('torch not installed'); return; }
327
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-scores-'));
328
+ try {
329
+ const data = path.join(dir, 'data'); fs.mkdirSync(data);
330
+ const texts = [['commit and push', 'git', { git: 0.6 }], ['fix the crash, add a test', 'fix', { fix: 0.6, test: 0.4, docs: 0.2 }],
331
+ ['explain this flag', 'explain', { explain: 0.6, investigate: 0.2 }], ['go', null, {}]];
332
+ const prompts = []; const labels = [];
333
+ for (let k = 0; k < 10; k++) texts.forEach(([x, g, s], i) => {
334
+ const id = `p${k}-${i}`; const scores = scored(s);
335
+ prompts.push({ id, family: `f${k}`, source: 'claude', split: k < 8 ? 'train' : 'validation', text: `${x} ${k}` });
336
+ labels.push({ id, gold: g, secondary: INTENTS.filter(x2 => x2 !== g && scores[x2] >= 0.4), scores });
337
+ });
338
+ fs.writeFileSync(path.join(data, 'prompts.jsonl'), prompts.map(x => JSON.stringify(x)).join('\n') + '\n');
339
+ fs.writeFileSync(path.join(data, 'labels-intent-scores.jsonl'), labels.map(x => JSON.stringify(x)).join('\n') + '\n');
340
+ fs.writeFileSync(path.join(data, 'owner-overrides-intent.jsonl'), `${JSON.stringify({ id: 'p9-2', gold: 'docs', secondary: ['explain'] })}\n`);
341
+ const out = path.join(dir, 'model');
342
+ const args = [path.join(root, 'scripts/system-one-train-ngram.py'), '--task', 'intent', '--target', 'scores', '--data-dir', data, '--out', out, '--dim', '4096', '--epochs', '60', '--lr', '0.05'];
343
+ const r = spawnSync(python, args, { encoding: 'utf8' });
344
+ assert.equal(r.status, 0, r.stdout + r.stderr);
345
+ const side = JSON.parse(fs.readFileSync(path.join(out, 'harness-routing-v1.json'), 'utf8'));
346
+ assert.deepEqual(side.catalog, IDS);
347
+ assert.deepEqual([side.metadata.task, side.metadata.target, side.metadata.loss], ['intent', 'scores', 'bce']);
348
+ assert.ok(Object.hasOwn(side.metadata.datasets, 'labels-intent-scores.jsonl'));
349
+ const rows = fs.readFileSync(path.join(out, 'val-scores.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
350
+ assert.equal(rows.length, 8);
351
+ assert.ok(rows.every(s => s.probs.length === IDS.length && Math.abs(s.probs.reduce((a, b) => a + b, 0) - 1) < 1e-5), 'the provider still sees a probability vector');
352
+ assert.deepEqual([rows.find(s => s.id === 'p9-2').gold, rows.find(s => s.id === 'p9-2').secondary], ['docs', ['explain']], 'an owner override applies');
353
+ const p = rows.find(s => s.id === 'p8-1').probs; const at = id => p[IDS.indexOf(id)];
354
+ assert.ok(at('fix') > at('test') && at('test') > at('docs') && at('docs') > at('git'), 'primary, secondary, related, unrelated');
355
+ assert.equal(IDS[rows.find(s => s.id === 'p8-3').probs.indexOf(Math.max(...rows.find(s => s.id === 'p8-3').probs))], 'unclassified', 'a null primary trains unclassified');
356
+ fs.rmSync(path.join(data, 'labels-intent-scores.jsonl'));
357
+ assert.notEqual(spawnSync(python, args, { encoding: 'utf8' }).status, 0, 'scored training needs scored labels');
358
+ assert.notEqual(spawnSync(python, [...args.slice(0, 1), '--target', 'scores', '--data-dir', data, '--out', out], { encoding: 'utf8' }).status, 0, 'scores are an intent target only');
359
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
360
+ });
361
+
362
+ test('S1-I14 low-scoring labels go to a second model, which replaces them unless it fails', async () => {
363
+ const rules = label.rulesFromDoc(fs.readFileSync(path.join(root, 'docs/system-one-intent.md'), 'utf8'), 'intent');
364
+ const high = scored({ git: 0.95, docs: 0.3, review: 0.2, test: 0.1 });
365
+ const low = scored({ fix: 0.75, test: 0.5, docs: 0.25, review: 0.1 });
366
+ const rows = [{ id: 'a', gold: 'git', secondary: [], scores: high }, { id: 'b', gold: 'fix', secondary: ['test'], scores: low },
367
+ { id: 'c', gold: 'fix', secondary: ['test'], scores: low }];
368
+ const items = [{ id: 'a', text: 'commit' }, { id: 'b', text: 'fix it' }, { id: 'c', text: 'fix that' }];
369
+ const better = scored({ fix: 0.9, test: 0.7, docs: 0.3, review: 0.1 });
370
+ const seen = [];
371
+ const run = async (prompt, batch) => { seen.push(batch.map(x => x.id)); if (batch[0].id === 'c') return null;
372
+ return { labels: batch.map((_, i) => ({ i, primary: 'fix', scores: better })) }; };
373
+ const out = await label.escalate(rows, items, { run, rules, below: 0.8, batchSize: 1, retryDelayMs: 0 });
374
+ assert.deepEqual(seen.flat().sort(), ['b', 'c', 'c'], 'only labels whose top score is below 0.8, the failed one retried once');
375
+ assert.deepEqual(out.rows.map(r => [r.id, r.scores.fix || r.scores.git]), [['a', 0.95], ['b', 0.9], ['c', 0.75]], 'a failed escalation keeps the first label');
376
+ assert.deepEqual(out.escalated, ['b']);
377
+ assert.deepEqual(out.failed, ['c']);
378
+ assert.deepEqual((await label.escalate(rows, items, { run, rules, below: 0.7 })).escalated, [], 'nothing below the bar, nothing escalated');
379
+ });
380
+
381
+ test('S1-I15 scaled labels read the scores relative to the top, and only lagging margins escalate', async () => {
382
+ const rules = label.rulesFromDoc(fs.readFileSync(path.join(root, 'docs/system-one-intent.md'), 'utf8'), 'intent');
383
+ const raw = scored({ fix: 0.6, docs: 0.45, test: 0.3, review: 0.25 });
384
+ const nul = scored({ explain: 0.2, investigate: 0.15, discuss: 0.1, plan: 0.05 });
385
+ const batch = [{ id: 'x', text: 'fix it' }, { id: 'y', text: 'go' }];
386
+ const run = async () => ({ labels: [{ i: 0, primary: 'fix', scores: raw }, { i: 1, primary: 'null', scores: nul }] });
387
+ const out = await label.labelAll(batch, { rules, task: 'intent', scores: true, scale: true, run });
388
+ const x = out.labeled[0];
389
+ assert.equal(x.scores.fix, 1);
390
+ assert.equal(x.scores.test, 0.5);
391
+ assert.deepEqual(x.raw, raw, 'the model scores are kept');
392
+ assert.deepEqual(x.secondary, ['docs', 'test', 'review'], 'bands come from the scaled scores (unscaled: docs only)');
393
+ assert.deepEqual(out.labeled[1], { id: 'y', gold: null, secondary: [], scores: nul, raw: nul }, 'a null label is not scaled');
394
+ assert.deepEqual(label.scaleLabel(x), x, 'scaling twice changes nothing');
395
+ const close = { id: 'c', gold: 'fix', secondary: ['docs'], scores: scored({ fix: 0.8, docs: 0.6, test: 0.2, review: 0.1 }) };
396
+ const wide = { id: 'w', gold: 'git', secondary: [], scores: scored({ git: 0.9, docs: 0.3, test: 0.2, review: 0.1 }) };
397
+ const nullRow = { id: 'n', gold: null, secondary: [], scores: nul };
398
+ assert.deepEqual([close, wide, nullRow].map(r => label.lagging(r, { margin: 0.3 })), [true, false, false], '(0.8 - 0.6) / 0.8 = 0.25 lags; null never');
399
+ assert.deepEqual([close, wide].map(r => label.lagging(r, { below: 0.85 })), [true, false], 'the top-score rule stays available');
400
+ const seen = [];
401
+ const second = async (p, b) => { seen.push(...b.map(i => i.id)); return { labels: b.map((_, i) => ({ i, primary: 'fix', scores: scored({ fix: 0.9, docs: 0.4, test: 0.2, review: 0.1 }) })) }; };
402
+ const e = await label.escalate([close, wide, nullRow], [{ id: 'c', text: 'c' }, { id: 'w', text: 'w' }, { id: 'n', text: 'n' }],
403
+ { run: second, rules, margin: 0.3, scale: true, batchSize: 1 });
404
+ assert.deepEqual(seen, ['c']);
405
+ assert.deepEqual(e.rows[0].scores.docs, Number((0.4 / 0.9).toFixed(4)), 'escalated labels are scaled too');
406
+ });
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+ // Laya dense intent labeler contract (#255 Phase 1+2): the stdlib Python suite
3
+ // proves the mapping/validator/derive contract without any model weights.
4
+ const { test } = require('node:test');
5
+ const assert = require('node:assert/strict');
6
+ const path = require('node:path');
7
+ const { spawnSync } = require('node:child_process');
8
+
9
+ const root = path.resolve(__dirname, '..');
10
+
11
+ test('S1-L01 the Laya dense labeler contract holds without model weights', () => {
12
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
13
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-label-test.py')], { encoding: 'utf8' });
14
+ assert.equal(r.status, 0, r.stdout + r.stderr);
15
+ });
16
+
17
+ test('S1-L02 the Laya calibration contract holds without model weights', () => {
18
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
19
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-calibrate-test.py')], { encoding: 'utf8' });
20
+ assert.equal(r.status, 0, r.stdout + r.stderr);
21
+ });
22
+
23
+ test('S1-L03 the Laya soft-target exporter contract holds without model weights', () => {
24
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
25
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-export-test.py')], { encoding: 'utf8' });
26
+ assert.equal(r.status, 0, r.stdout + r.stderr);
27
+ });
28
+
29
+ test('S1-L04 the single-device trainer contract holds (torch parts skip without torch)', () => {
30
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
31
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-train-test.py')], { encoding: 'utf8' });
32
+ assert.equal(r.status, 0, r.stdout + r.stderr);
33
+ });
34
+
35
+ test('S1-L05 the fine-tuned provider bridge contract holds without model weights', () => {
36
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
37
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-provider-test.py')], { encoding: 'utf8' });
38
+ assert.equal(r.status, 0, r.stdout + r.stderr);
39
+ });
40
+
41
+ test('S1-L06 the per-intent Bernoulli contract holds without model weights', () => {
42
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
43
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-laya-perintent-test.py')], { encoding: 'utf8' });
44
+ assert.equal(r.status, 0, r.stdout + r.stderr);
45
+ });
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+ // Relevance-native intent contract (#233 decision): per-intent Bernoulli
3
+ // decisions beside the untouched single-winner path.
4
+ const { test } = require('node:test');
5
+ const assert = require('node:assert/strict');
6
+ const { createRequest, decide, decideIntents } = require('../harness-everything/scripts/system-one/contract');
7
+ const { INTENT_OPTIONS } = require('../harness-everything/scripts/system-one/catalogs');
8
+ const { gradeRelevance } = require('../harness-everything/scripts/system-one/evaluate');
9
+ const { relevanceGates } = require('../harness-everything/scripts/system-one/evaluate');
10
+
11
+ const IDS = INTENT_OPTIONS.map(o => o.id);
12
+ const request = createRequest('intent', 'fix the crash and add a test', INTENT_OPTIONS);
13
+ const responseFor = masses => ({ schemaVersion: 1, requestHash: request.requestHash, catalogHash: request.catalogHash,
14
+ model: { id: 'm', revision: 'v1', domain: 'harness-routing-v1' },
15
+ scores: IDS.map(id => ({ id, probability: masses[id] ?? 0.05 })) });
16
+ const thresholds = (tau = 0.4) => Object.fromEntries(IDS.filter(id => id !== 'unclassified').map(id => [id, tau]));
17
+
18
+ test('S1-R01 independent intents fire on their own thresholds', () => {
19
+ const d = decideIntents(request, responseFor({ fix: 0.9, test: 0.5 }), { thresholds: thresholds() });
20
+ assert.equal(d.status, 'accepted');
21
+ assert.equal(d.reason, 'scored');
22
+ assert.equal(d.selectedId, 'fix');
23
+ assert.equal(d.confidence, 0.9);
24
+ assert.equal(d.margin, 0.4);
25
+ assert.deepEqual(d.model, { id: 'm', revision: 'v1', domain: 'harness-routing-v1' });
26
+ assert.equal(d.intents.fix.fired, true);
27
+ assert.equal(d.intents.test.fired, true);
28
+ assert.equal(d.intents.docs.fired, false);
29
+ assert.equal(Object.keys(d.intents).length, 12);
30
+ });
31
+
32
+ test('S1-R02 silence abstains and unclassified never fires', () => {
33
+ const quiet = decideIntents(request, responseFor({}), { thresholds: thresholds() });
34
+ assert.deepEqual([quiet.status, quiet.reason, quiet.selectedId], ['abstain', 'no-intent-fired', null]);
35
+ assert.ok(Object.values(quiet.intents).every(i => i.fired === false));
36
+ const loudNull = decideIntents(request, responseFor({ unclassified: 0.95 }), { thresholds: thresholds() });
37
+ assert.equal(loudNull.status, 'abstain');
38
+ });
39
+
40
+ test('S1-R03 the simplex rule does not apply to relevance vectors', () => {
41
+ const res = responseFor({ fix: 0.9, test: 0.8, docs: 0.7 });
42
+ assert.ok(res.scores.reduce((s, o) => s + o.probability, 0) > 2, 'independent scores sum past one');
43
+ assert.equal(decideIntents(request, res, { thresholds: thresholds() }).status, 'accepted');
44
+ assert.equal(decide(request, res, {}).status, 'invalid-output', 'single-winner still demands the simplex');
45
+ });
46
+
47
+ test('S1-R04 malformed relevance inputs fail closed', () => {
48
+ const good = responseFor({ fix: 0.9 });
49
+ const tau = thresholds();
50
+ for (const mutate of [
51
+ r => { r.scores = r.scores.slice(0, 12); },
52
+ r => { r.scores[0] = { ...r.scores[0], id: 'nope' }; },
53
+ r => { r.scores[0] = { ...r.scores[0], probability: 1.5 }; },
54
+ r => { r.scores[0] = { ...r.scores[0], probability: NaN }; },
55
+ ]) { const bad = JSON.parse(JSON.stringify(good)); mutate(bad);
56
+ assert.equal(decideIntents(request, bad, { thresholds: tau }).status, 'invalid-output'); }
57
+ for (const policy of [{}, { thresholds: {} }, { thresholds: { ...tau, fix: 2 } },
58
+ { thresholds: { ...tau, unclassified: 0.5 } }, { thresholds: tau, extra: 1 }]) {
59
+ assert.throws(() => decideIntents(request, good, policy), JSON.stringify(policy));
60
+ }
61
+ });
62
+
63
+ const relevanceCase = (id, gold, secondary) => ({ id, family: `f-${id}`, split: 'holdout', language: 'en',
64
+ source: 'human:fixture', reviewed: true, request: createRequest('intent', `prompt ${id}`, INTENT_OPTIONS), gold, secondary });
65
+ const byId = entries => new Map(entries.map(([id, scores]) => [id, { scores }]));
66
+ const probs = masses => IDS.map(id => masses[id] ?? 0.0);
67
+
68
+ test('S1-R05 relevance grading reports micro, macro, cardinality and abstain', () => {
69
+ const cases = [relevanceCase('a', 'fix', ['test']), relevanceCase('b', 'docs', []), relevanceCase('c', null, [])];
70
+ const runs = byId([['a', probs({ fix: 0.9, test: 0.5 })], ['b', probs({ docs: 0.8, fix: 0.5 })], ['c', probs({})]]);
71
+ const g = gradeRelevance(cases, runs, [...IDS.slice(0, 12), null], thresholds());
72
+ assert.deepEqual([g.micro.precision, g.micro.recall], [0.75, 1]);
73
+ assert.ok(Math.abs(g.micro.f1 - 0.857) < 0.001);
74
+ assert.ok(Math.abs(g.macroF1 - 0.889) < 0.001, 'fix 0.667, test 1, docs 1; unsupported intents skipped');
75
+ assert.deepEqual([g.cardinality.predicted, g.cardinality.gold], [4 / 3, 1]);
76
+ assert.deepEqual([g.abstainRate, g.exactSetMatch, g.weakPrecision], [1 / 3, 2 / 3, 0.5]);
77
+ assert.equal(g.perIntent.fix.support, 1);
78
+ assert.equal(g.perIntent.git.support, 0);
79
+ });
80
+
81
+ const goodMulti = () => ({ micro: { precision: 0.6, recall: 0.6, f1: 0.6 }, macroF1: 0.55,
82
+ perIntent: Object.fromEntries(['fix', 'test'].map(id => [id, { support: 20, f1: 0.5, precision: 0.5 }])),
83
+ cardinality: { predicted: 2.0, gold: 1.8 }, abstainRate: 0.1, exactSetMatch: 0.3, weakPrecision: 0.5 });
84
+ const goodEvidence = () => ({ family: { gold: { rate: 0.8 }, model: { rate: 0.85 } },
85
+ agreement: 1, warmP95Ms: 179, structural: { unchanged: true, rollbackLive: true } });
86
+
87
+ test('S1-R06 relevance gates follow the reviewed promotion contract', () => {
88
+ const pass = relevanceGates(goodMulti(), goodEvidence());
89
+ assert.ok(pass.rolloutReady === false, 'policy/live-host evidence keeps rollout red pre-production');
90
+ for (const k of ['microF1', 'macroF1', 'perIntentFloors', 'weakPrecision', 'cardinality',
91
+ 'abstainRate', 'familyConsistency', 'repeatability', 'warmLatency', 'structuralControls']) {
92
+ assert.equal(pass[k], true, k);
93
+ }
94
+ const cases = [
95
+ [g => { g.micro.f1 = 0.54; }, 'microF1'],
96
+ [g => { g.macroF1 = 0.49; }, 'macroF1'],
97
+ [g => { g.perIntent.fix.f1 = 0.29; g.perIntent.fix.support = 12; }, 'perIntentFloors'],
98
+ [g => { g.weakPrecision = 0.29; }, 'weakPrecision'],
99
+ [g => { g.cardinality.predicted = 3.0; }, 'cardinality'],
100
+ [g => { g.abstainRate = 0.21; }, 'abstainRate'],
101
+ ];
102
+ for (const [mutate, key] of cases) {
103
+ const g = goodMulti(); mutate(g);
104
+ assert.equal(relevanceGates(g, goodEvidence())[key], false, key);
105
+ }
106
+ const ev = goodEvidence();
107
+ assert.equal(relevanceGates(goodMulti(), { ...ev, family: { gold: { rate: 0.9 }, model: { rate: 0.8 } } }).familyConsistency, false);
108
+ assert.equal(relevanceGates(goodMulti(), { ...ev, agreement: 0.99 }).repeatability, false);
109
+ assert.equal(relevanceGates(goodMulti(), { ...ev, warmP95Ms: 251 }).warmLatency, false);
110
+ assert.equal(relevanceGates(goodMulti(), { ...ev, warmP95Ms: 250 }).warmLatency, true);
111
+ assert.equal(relevanceGates(goodMulti(), { ...ev, structural: { unchanged: true, rollbackLive: false } }).structuralControls, false);
112
+ });
@@ -328,3 +328,19 @@ test('S1-RS13 manifest acceptance thresholds are validated, carried by scored re
328
328
  assert.ok(evaluateWith(strict).every(r => r.decision.status === 'abstain' && r.decision.reason === 'low-confidence'));
329
329
  } finally { cleanup(strict); }
330
330
  });
331
+
332
+ test('S1-RS14 resident transport names its adapter and stays inside the scripts dir', () => {
333
+ const f = fixture();
334
+ try {
335
+ assert.equal(provider.validateManifest({ ...f.manifest, adapter: 'laya_adapter.py' }), true);
336
+ for (const bad of ['../evil.py', '/abs/evil.py', '', 'ADAPTER.PY', 'a'.repeat(65) + '.py']) {
337
+ assert.throws(() => provider.validateManifest({ ...f.manifest, adapter: bad }), String(bad));
338
+ }
339
+ const [exe, prefix] = resident.defaultCommand(f.manifest);
340
+ assert.equal(exe, f.manifest.python);
341
+ assert.deepEqual(prefix, [path.join(__dirname, '..', 'harness-everything', 'scripts', 'system-one', 'cua_adapter.py'), '--serve']);
342
+ const [, layaPrefix] = resident.defaultCommand({ ...f.manifest, adapter: 'laya_adapter.py' });
343
+ assert.ok(layaPrefix[0].endsWith(path.join('system-one', 'laya_adapter.py')));
344
+ assert.throws(() => resident.defaultCommand({ ...f.manifest, adapter: '../evil.py' }));
345
+ } finally { cleanup(f); }
346
+ });