harness-everything 0.28.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 (109) 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 +47 -0
  5. package/PRIVACY.md +9 -0
  6. package/benchmarks/fixtures/system-one-holdout-reviews.json +18 -18
  7. package/benchmarks/fixtures/system-one-holdout.json +9 -9
  8. package/benchmarks/fixtures/system-one-intent-holdout-draft.json +2228 -0
  9. package/benchmarks/fixtures/system-one-intent-holdout.json +16509 -0
  10. package/benchmarks/fixtures/system-one-intent-reviews.json +2723 -0
  11. package/benchmarks/results/system-one/harness-routing-v1-cpu-2026-09-24/README.md +75 -0
  12. package/benchmarks/results/system-one/harness-routing-v1-cpu-2026-09-24/report.json +10832 -0
  13. package/benchmarks/results/system-one/harness-routing-v1-ngram-2026-09-24/README.md +72 -0
  14. package/benchmarks/results/system-one/harness-routing-v1-ngram-2026-09-24/report.json +10817 -0
  15. package/benchmarks/results/system-one/harness-routing-v3-ngram-2026-09-24/README.md +63 -0
  16. package/benchmarks/results/system-one/harness-routing-v3-ngram-2026-09-24/report.json +10817 -0
  17. package/benchmarks/results/system-one/intent-ngram-v1-2026-09-24/README.md +64 -0
  18. package/benchmarks/results/system-one/intent-ngram-v1-2026-09-24/report.json +15177 -0
  19. package/benchmarks/results/system-one/labeler-holdout-check-2026-09-24/report.json +1104 -0
  20. package/benchmarks/results/system-one/labeler-holdout-check-codex-2026-09-24/report.json +1104 -0
  21. package/benchmarks/results/system-one/labeler-holdout-check-codex-tier3-2026-09-24/report.json +1104 -0
  22. package/benchmarks/results/system-one/labeler-holdout-check-intent-2026-09-24/report.json +2976 -0
  23. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-005-steps.json +6125 -0
  24. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-haiku-sonnet-escalation.json +6344 -0
  25. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report-scaled-margin-escalation.json +6206 -0
  26. package/benchmarks/results/system-one/labeler-holdout-check-intent-scores-haiku-2026-09-24/report.json +6103 -0
  27. package/benchmarks/results/system-one/laya-ft-2026-09-25/README.md +83 -0
  28. package/benchmarks/results/system-one/laya-ft-2026-09-25/report.json +71 -0
  29. package/benchmarks/results/system-one/laya-ft-2026-09-25/shadow-report.json +44 -0
  30. package/benchmarks/results/system-one/laya-zs-2026-09-25/README.md +68 -0
  31. package/benchmarks/results/system-one/laya-zs-2026-09-25/report.json +173 -0
  32. package/ci/mechanism-34-observations.test.js +550 -0
  33. package/ci/mechanism-system-one-collect.test.js +16 -0
  34. package/ci/mechanism-system-one-evaluation.test.js +17 -0
  35. package/ci/mechanism-system-one-intent.test.js +406 -0
  36. package/ci/mechanism-system-one-label.test.js +27 -0
  37. package/ci/mechanism-system-one-laya.test.js +45 -0
  38. package/ci/mechanism-system-one-ngram.test.js +161 -0
  39. package/ci/mechanism-system-one-relevance.test.js +112 -0
  40. package/ci/mechanism-system-one-resident.test.js +16 -0
  41. package/ci/mechanism-system-one-train.test.js +12 -0
  42. package/ci/system-one-laya-calibrate-test.py +65 -0
  43. package/ci/system-one-laya-export-test.py +155 -0
  44. package/ci/system-one-laya-label-test.py +201 -0
  45. package/ci/system-one-laya-perintent-test.py +60 -0
  46. package/ci/system-one-laya-provider-test.py +115 -0
  47. package/ci/system-one-laya-train-test.py +93 -0
  48. package/ci/system-one-ngram-parity.py +19 -0
  49. package/ci/system-one-train-test.py +6 -0
  50. package/docs/routing.md +25 -0
  51. package/docs/system-one-corpus.md +31 -3
  52. package/docs/system-one-intent-gates.md +102 -0
  53. package/docs/system-one-intent.md +173 -0
  54. package/docs/system-one-laya-training.md +38 -0
  55. package/docs/system-one-observations.md +206 -0
  56. package/docs/system-one-routing.md +102 -5
  57. package/docs/system-one-suggestion-gates.md +292 -0
  58. package/docs/system-one-training.md +69 -7
  59. package/harness-everything/SKILL.md +1 -1
  60. package/harness-everything/scripts/kernel-router.js +10 -0
  61. package/harness-everything/scripts/system-one/catalogs.js +35 -0
  62. package/harness-everything/scripts/system-one/contract.js +45 -1
  63. package/harness-everything/scripts/system-one/evaluate.js +118 -21
  64. package/harness-everything/scripts/system-one/intent.js +22 -0
  65. package/harness-everything/scripts/system-one/laya_adapter.py +141 -0
  66. package/harness-everything/scripts/system-one/ngram.js +84 -0
  67. package/harness-everything/scripts/system-one/provider.js +24 -7
  68. package/harness-everything/scripts/system-one/resident.js +8 -3
  69. package/harness-everything/scripts/system-one/router.js +1 -1
  70. package/hooks/hooks.json +40 -0
  71. package/hooks/scripts/codex-user-prompt.js +39 -0
  72. package/hooks/scripts/lib/observations.js +581 -0
  73. package/hooks/scripts/observation-hook.js +25 -0
  74. package/opencode-plugin/plugin.json +1 -1
  75. package/package.json +1 -1
  76. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  77. package/plugins/harness-everything/hooks/hooks.json +35 -2
  78. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +39 -0
  79. package/plugins/harness-everything/hooks/scripts/lib/observations.js +581 -0
  80. package/plugins/harness-everything/hooks/scripts/observation-hook.js +25 -0
  81. package/plugins/harness-everything/plugin.json +1 -1
  82. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  83. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +10 -0
  84. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/catalogs.js +35 -0
  85. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +45 -1
  86. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +118 -21
  87. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/intent.js +22 -0
  88. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/laya_adapter.py +141 -0
  89. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/ngram.js +84 -0
  90. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +24 -7
  91. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +8 -3
  92. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +1 -1
  93. package/sbom.cdx.json +7 -7
  94. package/scripts/evaluate-system-one.js +32 -13
  95. package/scripts/system-one-calibrate-laya.py +165 -0
  96. package/scripts/system-one-calibrate.js +42 -13
  97. package/scripts/system-one-collect.js +7 -3
  98. package/scripts/system-one-compare-laya.py +156 -0
  99. package/scripts/system-one-corpus.js +22 -15
  100. package/scripts/system-one-eval-laya.js +112 -0
  101. package/scripts/system-one-export-laya.py +197 -0
  102. package/scripts/system-one-label-laya.py +243 -0
  103. package/scripts/system-one-label.js +192 -37
  104. package/scripts/system-one-observations-export.js +106 -0
  105. package/scripts/system-one-observations-review.js +86 -0
  106. package/scripts/system-one-perintent-laya.py +134 -0
  107. package/scripts/system-one-train-laya.py +344 -0
  108. package/scripts/system-one-train-ngram.py +181 -0
  109. package/scripts/system-one-train.py +14 -1
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
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 { createHash } = require('node:crypto');
8
+ const { spawnSync } = require('node:child_process');
9
+ const ngram = require('../harness-everything/scripts/system-one/ngram');
10
+ const provider = require('../harness-everything/scripts/system-one/provider');
11
+ const { createRequest, decide } = require('../harness-everything/scripts/system-one/contract');
12
+ const { TIER_OPTIONS } = require('../harness-everything/scripts/system-one/router');
13
+ const root = path.resolve(__dirname, '..');
14
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
15
+ const sha = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
16
+ const IDS = TIER_OPTIONS.map(o => o.id);
17
+
18
+ // A tiny model whose weights push any text containing the "commit" trigram toward tier1.
19
+ function artifact(dir, { dim = 1024, nmax = 3, catalog = IDS, sidecar = {}, bytes } = {}) {
20
+ const W = new Float32Array(dim * catalog.length);
21
+ const hot = ngram.fnv1a32('3:com') % dim;
22
+ W[hot * catalog.length + 0] = 40;
23
+ const bin = path.join(dir, 'tier.bin'); const json = path.join(dir, 'tier.json');
24
+ fs.writeFileSync(bin, bytes || Buffer.from(W.buffer));
25
+ fs.writeFileSync(json, JSON.stringify({ format: 'harness-ngram', formatVersion: 1, dim, nmax, hash: 'fnv1a32', catalog, bias: catalog.map(() => 0), metadata: { fixture: true }, ...sidecar }));
26
+ return { bin, json };
27
+ }
28
+ function manifest(dir, files, extra = {}) {
29
+ const m = { schemaVersion: 1, transport: 'ngram', checkpoint: files.bin, weightsSha256: sha(files.bin), configSha256: sha(files.json),
30
+ modelId: 'fixture/ngram', revision: 'v1', domain: 'harness-routing-v1', ...extra };
31
+ const p = path.join(dir, 'manifest.json'); fs.writeFileSync(p, JSON.stringify(m)); return { m, p };
32
+ }
33
+ const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-ngram-'));
34
+
35
+ test('S1-N01 fnv1a32 matches the published test vectors', () => {
36
+ assert.equal(ngram.fnv1a32(''), 0x811c9dc5);
37
+ assert.equal(ngram.fnv1a32('a'), 0xe40c292c);
38
+ assert.equal(ngram.fnv1a32('foobar'), 0xbf9cf968);
39
+ });
40
+
41
+ test('S1-N02 featurization follows the pinned rules', () => {
42
+ const f = ngram.featurize(' Commit ALL\tchanges ', 3, 1 << 16);
43
+ assert.deepEqual(f, ngram.featurize('commit all changes', 3, 1 << 16), 'lowercase and whitespace normalization');
44
+ const norm = Math.sqrt([...f.values()].reduce((s, v) => s + v * v, 0));
45
+ assert.ok(Math.abs(norm - 1) < 1e-12);
46
+ assert.ok(f.has(ngram.fnv1a32('len:4') % (1 << 16)), 'length bucket for 18 UTF-8 bytes');
47
+ const cjk = ngram.featurize('修正😀', 2, 1 << 16);
48
+ assert.ok(cjk.has(ngram.fnv1a32('2:正😀') % (1 << 16)), 'n-grams are over code points, not UTF-16 units');
49
+ assert.ok(!ngram.featurize('a b', 3, 1 << 16).has(ngram.fnv1a32('1: ') % (1 << 16)), 'space-only grams are skipped');
50
+ });
51
+
52
+ test('S1-N03 the Python trainer and the Node provider produce identical features', () => {
53
+ const texts = ['commit all changes', '幫我修正 parser 的錯誤並補測試', ' MIXED Case\ttext 😀 ', 'x', '重構 plugin 介面,跨兩個 repo'];
54
+ const hashes = ['', 'a', 'foobar', '3:修正測'];
55
+ const r = spawnSync(python, [path.join(__dirname, 'system-one-ngram-parity.py')], { input: JSON.stringify({ texts, hashes, nmax: 3, dim: 1 << 16 }), encoding: 'utf8', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8' } });
56
+ assert.equal(r.status, 0, r.stderr);
57
+ const py = JSON.parse(r.stdout);
58
+ assert.deepEqual(py.hash, hashes.map(h => ngram.fnv1a32(h)));
59
+ texts.forEach((t, i) => {
60
+ const node = ngram.featurize(t, 3, 1 << 16);
61
+ assert.deepEqual(Object.keys(py.features[i]).map(Number).sort((a, b) => a - b), [...node.keys()].sort((a, b) => a - b), t);
62
+ for (const [k, v] of Object.entries(py.features[i])) assert.ok(Math.abs(v - node.get(Number(k))) < 1e-12, t);
63
+ });
64
+ });
65
+
66
+ test('S1-N04 the ngram transport scores in process with the Phase 0 response shape', async () => {
67
+ const dir = tmp();
68
+ try {
69
+ const { m, p } = manifest(dir, artifact(dir), { acceptance: { minConfidence: 0.5, minMargin: 0 } });
70
+ assert.equal(provider.validateManifest(m), true);
71
+ const request = createRequest('tier', 'please commit these changes', TIER_OPTIONS);
72
+ const result = provider.score(request, p);
73
+ assert.equal(result.status, 'scored');
74
+ assert.deepEqual(result.acceptance, { minConfidence: 0.5, minMargin: 0 });
75
+ assert.deepEqual(result.response.model, { id: 'fixture/ngram', revision: 'v1', domain: 'harness-routing-v1' });
76
+ assert.ok(Math.abs(result.response.scores.reduce((s, x) => s + x.probability, 0) - 1) < 1e-9);
77
+ const d = decide(request, result.response, result.acceptance);
78
+ assert.equal(d.status, 'accepted'); assert.equal(d.selectedId, 'tier1');
79
+ assert.deepEqual(await provider.scoreAsync(request, p), result);
80
+ const other = provider.score(createRequest('tier', 'unrelated words only', TIER_OPTIONS), p);
81
+ assert.ok(other.response.scores.every(s => Math.abs(s.probability - 0.25) < 1e-9), 'no active weights gives a uniform vector');
82
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
83
+ });
84
+
85
+ test('S1-N05 any artifact mismatch is provider-config and never scores', () => {
86
+ const request = createRequest('tier', 'commit it', TIER_OPTIONS);
87
+ const cases = [
88
+ dir => { const f = artifact(dir); const { m, p } = manifest(dir, f); fs.appendFileSync(f.bin, Buffer.alloc(4)); return p; },
89
+ dir => { const f = artifact(dir, { bytes: Buffer.alloc(8) }); return manifest(dir, f).p; },
90
+ dir => manifest(dir, artifact(dir, { catalog: ['tier1', 'tier2', 'tier3', 'other'] })).p,
91
+ dir => manifest(dir, artifact(dir, { sidecar: { format: 'other' } })).p,
92
+ dir => manifest(dir, artifact(dir, { sidecar: { extra: 1 } })).p,
93
+ dir => manifest(dir, artifact(dir, { dim: 1000 })).p,
94
+ dir => manifest(dir, artifact(dir, { nmax: 9 })).p,
95
+ dir => manifest(dir, artifact(dir, { sidecar: { bias: [0, 0] } })).p,
96
+ ];
97
+ for (const make of cases) {
98
+ const dir = tmp();
99
+ try { assert.deepEqual(provider.score(request, make(dir)), { status: 'unavailable', reason: 'provider-config' }); }
100
+ finally { fs.rmSync(dir, { recursive: true, force: true }); }
101
+ }
102
+ });
103
+
104
+ test('S1-N06 manifest rules: ngram needs a .bin and no python; other transports still need python', () => {
105
+ const dir = tmp();
106
+ try {
107
+ const { m } = manifest(dir, artifact(dir));
108
+ assert.equal(provider.validateManifest(m), true);
109
+ assert.throws(() => provider.validateManifest({ ...m, checkpoint: m.checkpoint.replace(/\.bin$/, '.safetensors') }));
110
+ assert.throws(() => provider.validateManifest({ ...m, transport: 'resident' }), 'resident requires python and a .safetensors checkpoint');
111
+ assert.throws(() => provider.validateManifest({ ...m, transport: 'bogus' }));
112
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
113
+ });
114
+
115
+ test('S1-N08 the evaluator records ngram samples warm and verifies the artifact as provenance', () => {
116
+ const dir = tmp();
117
+ try {
118
+ const { p } = manifest(dir, artifact(dir));
119
+ const output = path.join(dir, 'report.json');
120
+ const corpus = path.join(root, 'benchmarks/fixtures/system-one-routing.json');
121
+ const r = spawnSync(process.execPath, [path.join(root, 'scripts/evaluate-system-one.js'), corpus, p, output], { encoding: 'utf8', cwd: root });
122
+ assert.equal(r.status, 0, r.stderr);
123
+ const report = JSON.parse(fs.readFileSync(output, 'utf8'));
124
+ assert.ok(report.records.every(x => x.runs.every(run => run.coldStart === false)));
125
+ assert.equal(report.latency.coldSamples, 0);
126
+ assert.equal(report.gates.warmLatency, true);
127
+ assert.deepEqual(report.evidence.source, { status: 'recorded', transport: 'ngram', artifactVerified: true });
128
+ assert.equal(report.gates.sourceProvenance, true);
129
+ assert.equal(report.evidence.kind, 'offline-ngram');
130
+ fs.appendFileSync(path.join(dir, 'tier.bin'), Buffer.alloc(4));
131
+ const tampered = spawnSync(process.execPath, [path.join(root, 'scripts/evaluate-system-one.js'), corpus, p, output], { encoding: 'utf8', cwd: root });
132
+ assert.equal(tampered.status, 0, tampered.stderr);
133
+ const bad = JSON.parse(fs.readFileSync(output, 'utf8'));
134
+ assert.equal(bad.evidence.source.artifactVerified, false);
135
+ assert.equal(bad.gates.sourceProvenance, false);
136
+ assert.equal(bad.model.coverage, 0);
137
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
138
+ });
139
+
140
+ test('S1-N07 a real ngram training run produces an artifact the provider scores (skipped without torch)', t => {
141
+ if (spawnSync(python, ['-c', 'import torch'], { encoding: 'utf8' }).status !== 0) { t.skip('torch not installed'); return; }
142
+ const dir = tmp();
143
+ try {
144
+ const data = path.join(dir, 'data'); fs.mkdirSync(data);
145
+ const texts = [['commit all changes', 'tier1'], ['push and open a pr', 'tier1'], ['add a new flag with tests', 'tier3'], ['migrate every service', 'tier3'], ['fix the failing parser test', 'tier2'], ['go', null]];
146
+ const prompts = []; const labels = [];
147
+ for (let k = 0; k < 10; k++) texts.forEach(([x, g], 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 }); });
148
+ fs.writeFileSync(path.join(data, 'prompts.jsonl'), prompts.map(x => JSON.stringify(x)).join('\n') + '\n');
149
+ fs.writeFileSync(path.join(data, 'labels.jsonl'), labels.map(x => JSON.stringify(x)).join('\n') + '\n');
150
+ const out = path.join(dir, 'model');
151
+ const r = spawnSync(python, [path.join(root, 'scripts/system-one-train-ngram.py'), '--data-dir', data, '--out', out, '--dim', '4096', '--epochs', '40'], { encoding: 'utf8' });
152
+ assert.equal(r.status, 0, r.stdout + r.stderr);
153
+ const files = { bin: path.join(out, 'harness-routing-v1.bin'), json: path.join(out, 'harness-routing-v1.json') };
154
+ assert.equal(fs.statSync(files.bin).size, 4096 * 4 * 4);
155
+ assert.equal(fs.readFileSync(path.join(out, 'val-scores.jsonl'), 'utf8').trim().split('\n').length, 12);
156
+ const { p } = manifest(dir, files);
157
+ const scored = provider.score(createRequest('tier', 'commit all changes now', TIER_OPTIONS), p);
158
+ assert.equal(scored.status, 'scored');
159
+ assert.equal(decide(createRequest('tier', 'commit all changes now', TIER_OPTIONS), scored.response, { minConfidence: 0.5, minMargin: 0 }).selectedId, 'tier1');
160
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
161
+ });
@@ -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
+ });
@@ -41,6 +41,18 @@ test('S1-T03 calibration maximizes coverage subject to accepted precision on val
41
41
  assert.deepEqual(calibrate(rows, { minPrecision: 0.98 }), c, 'deterministic');
42
42
  });
43
43
 
44
+ test('S1-T06 the default calibration target is the owner advisory 85%', () => {
45
+ const rows = [
46
+ ...Array.from({ length: 86 }, () => row('tier1', [0.9, 0.05, 0.03, 0.02])),
47
+ ...Array.from({ length: 14 }, () => row('tier2', [0.9, 0.05, 0.03, 0.02])),
48
+ ];
49
+ const c = calibrate(rows);
50
+ assert.equal(c.minPrecision, 0.85);
51
+ assert.equal(c.feasible, true);
52
+ assert.equal(c.coverage, 1);
53
+ assert.equal(calibrate(rows, { minPrecision: 0.9 }).feasible, false);
54
+ });
55
+
44
56
  test('S1-T04 calibration CLI reads validation scores and writes thresholds', () => {
45
57
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-cal-'));
46
58
  try {
@@ -0,0 +1,65 @@
1
+ """Stdlib tests for the Laya zero-shot calibration (#255 Phase 3 prep).
2
+
3
+ No model dependency. Run with:
4
+ python3 ci/system-one-laya-calibrate-test.py
5
+ """
6
+ import importlib.util
7
+ import sys
8
+ import unittest
9
+ from pathlib import Path
10
+
11
+ sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
12
+ path = Path(__file__).resolve().parents[1] / 'scripts/system-one-calibrate-laya.py'
13
+ spec = importlib.util.spec_from_file_location('laya_calibrate', path)
14
+ laya_calibrate = importlib.util.module_from_spec(spec)
15
+ spec.loader.exec_module(laya_calibrate)
16
+
17
+
18
+ class IsotonicTests(unittest.TestCase):
19
+ def test_exact_staircase_on_separable_data(self):
20
+ knots = laya_calibrate.isotonic_fit([0.1, 0.2, 0.8, 0.9], [0.0, 0.0, 1.0, 1.0])
21
+ self.assertEqual([laya_calibrate.isotonic_predict(knots, x) for x in (0.1, 0.2, 0.8, 0.9)],
22
+ [0.0, 0.0, 1.0, 1.0])
23
+
24
+ def test_predictions_are_monotone(self):
25
+ xs = [0.05, 0.4, 0.35, 0.7, 0.6, 0.9, 0.2, 0.5]
26
+ ys = [0.0, 1.0, 0.0, 0.6, 1.0, 0.8, 0.2, 0.4]
27
+ knots = laya_calibrate.isotonic_fit(xs, ys)
28
+ grid = [i / 20 for i in range(21)]
29
+ preds = [laya_calibrate.isotonic_predict(knots, x) for x in grid]
30
+ self.assertTrue(all(b >= a for a, b in zip(preds, preds[1:])), 'monotone non-decreasing')
31
+
32
+ def test_duplicate_x_averages_y(self):
33
+ knots = laya_calibrate.isotonic_fit([0.5, 0.5, 0.5], [0.0, 0.6, 0.3])
34
+ self.assertAlmostEqual(laya_calibrate.isotonic_predict(knots, 0.5), 0.3)
35
+
36
+ def test_clamps_outside_range(self):
37
+ knots = laya_calibrate.isotonic_fit([0.2, 0.8], [0.3, 0.9])
38
+ self.assertEqual(laya_calibrate.isotonic_predict(knots, 0.0), 0.3)
39
+ self.assertEqual(laya_calibrate.isotonic_predict(knots, 1.0), 0.9)
40
+
41
+ def test_knots_are_json_serializable(self):
42
+ import json
43
+ knots = laya_calibrate.isotonic_fit([0.1, 0.9, 0.4], [0.2, 0.8, 0.5])
44
+ self.assertEqual(json.loads(json.dumps(knots)), knots)
45
+
46
+
47
+ class DeriveCalibratedTests(unittest.TestCase):
48
+ def scores(self, **over):
49
+ base = {i: 0.0 for i in
50
+ ['explain', 'discuss', 'git', 'fix', 'edit', 'feature', 'refactor',
51
+ 'review', 'test', 'docs', 'plan', 'investigate']}
52
+ base.update(over)
53
+ return base
54
+
55
+ def test_null_cutoff_abstains_low_max(self):
56
+ out = laya_calibrate.derive_calibrated(self.scores(fix=0.5, test=0.3), {}, 0.6)
57
+ self.assertIsNone(out['gold'])
58
+
59
+ def test_identity_mapping_keeps_bands(self):
60
+ out = laya_calibrate.derive_calibrated(self.scores(fix=0.9, test=0.5), {}, 0.2)
61
+ self.assertEqual((out['gold'], out['secondary']), ('fix', ['test']))
62
+
63
+
64
+ if __name__ == '__main__':
65
+ unittest.main()
@@ -0,0 +1,155 @@
1
+ """Stdlib contract tests for the Laya soft-target exporter (#255 Phase 3).
2
+
3
+ The exporter converts teacher relevance scores to upstream RLCD training
4
+ items without loading any model: sequence building is injected. Run with:
5
+ python3 ci/system-one-laya-export-test.py
6
+ """
7
+ import importlib.util
8
+ import json
9
+ import sys
10
+ import tempfile
11
+ import unittest
12
+ from pathlib import Path
13
+
14
+ sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
15
+ path = Path(__file__).resolve().parents[1] / 'scripts/system-one-export-laya.py'
16
+ spec = importlib.util.spec_from_file_location('laya_exporter', path)
17
+ laya_exporter = importlib.util.module_from_spec(spec)
18
+ spec.loader.exec_module(laya_exporter)
19
+
20
+ INTENTS = ['explain', 'discuss', 'git', 'fix', 'edit', 'feature', 'refactor',
21
+ 'review', 'test', 'docs', 'plan', 'investigate']
22
+
23
+
24
+ def fake_builder(state, instructions, probs):
25
+ """Deterministic stub: token ids derive from the text, markers fixed."""
26
+ ids = [len(state) % 251 + 1, len(instructions) % 251 + 1, 7]
27
+ return {'ids': ids, 'markers': [0, 1], 'target': [probs['false'], probs['true']]}
28
+
29
+
30
+ class ItemTests(unittest.TestCase):
31
+ def test_noul_target_is_false_true_pair(self):
32
+ item = laya_exporter.build_item('fix it', 'repair?', {'true': 0.8, 'false': 0.2}, fake_builder)
33
+ self.assertEqual(item['qtype'], 2, 'noul qtype follows laya.common.QTYPES')
34
+ self.assertEqual(item['target'], [0.2, 0.8])
35
+ self.assertEqual(item['label'], 1)
36
+
37
+ def test_relevance_p_maps_to_true_p(self):
38
+ item = laya_exporter.build_item('x', 'y', {'true': 0.0, 'false': 1.0}, fake_builder)
39
+ self.assertEqual((item['target'], item['label']), ([1.0, 0.0], 0))
40
+
41
+ def test_target_distribution_is_conserved(self):
42
+ for p in (0.0, 0.25, 0.6, 1.0):
43
+ item = laya_exporter.build_item('x', 'y', {'true': p, 'false': 1 - p}, fake_builder)
44
+ self.assertAlmostEqual(sum(item['target']), 1.0, msg=f'p={p}')
45
+
46
+ def test_bad_probabilities_fail(self):
47
+ with self.assertRaisesRegex(ValueError, 'probabilities'):
48
+ laya_exporter.build_item('x', 'y', {'true': 0.8, 'false': 0.8}, fake_builder)
49
+
50
+
51
+ class ExportTests(unittest.TestCase):
52
+ def write_data(self, data, prompts, teacher):
53
+ (data / 'prompts.jsonl').write_text(
54
+ '\n'.join(json.dumps(p) for p in prompts) + '\n', encoding='utf-8')
55
+ (data / 'labels-intent-scores.jsonl').write_text(
56
+ '\n'.join(json.dumps(t) for t in teacher) + '\n', encoding='utf-8')
57
+
58
+ def teacher_row(self, id, scores):
59
+ return {'id': id, 'gold': 'fix', 'secondary': [], 'scores': scores}
60
+
61
+ def test_exports_train_only_in_id_order(self):
62
+ prompts = [{'id': 'b', 'split': 'train', 'text': 'commit'},
63
+ {'id': 'a', 'split': 'train', 'text': 'fix it'},
64
+ {'id': 'c', 'split': 'validation', 'text': 'skip me'}]
65
+ scores = {i: (0.9 if i == 'fix' else 0.0) for i in INTENTS}
66
+ with tempfile.TemporaryDirectory() as d:
67
+ data = Path(d) / 'data'
68
+ data.mkdir()
69
+ self.write_data(data, prompts, [self.teacher_row('a', scores), self.teacher_row('b', scores)])
70
+ out = Path(d) / 'train_items.json'
71
+ manifest = Path(d) / 'manifest.json'
72
+ summary = laya_exporter.export(data, 'train', out, manifest, fake_builder, seed=0)
73
+ self.assertEqual(summary['items'], 24, '2 prompts x 12 intents')
74
+ rows = [json.loads(line) for line in out.read_text(encoding='utf-8').strip().split('\n')]
75
+ self.assertEqual([r['promptId'] for r in rows[::12]], ['a', 'b'], 'deterministic id order')
76
+ self.assertTrue(all(set(r) >= {'promptId', 'intent', 'ids', 'markers', 'qtype', 'target', 'label'} for r in rows))
77
+ self.assertEqual(summary['manifest']['seed'], 0)
78
+
79
+ def test_seed_controls_order(self):
80
+ prompts = [{'id': c, 'split': 'train', 'text': c * 20} for c in 'abcd']
81
+ scores = {i: 0.1 for i in INTENTS}
82
+ with tempfile.TemporaryDirectory() as d:
83
+ data = Path(d) / 'data'
84
+ data.mkdir()
85
+ self.write_data(data, prompts, [self.teacher_row(p['id'], scores) for p in prompts])
86
+ outs = []
87
+ for seed in (11, 11, 12):
88
+ out = Path(d) / f'o{seed}.json'
89
+ laya_exporter.export(data, 'train', out, Path(d) / f'm{seed}.json', fake_builder, seed=seed)
90
+ outs.append([json.loads(line)['promptId'] for line in out.read_text(encoding='utf-8').strip().split('\n')][::12])
91
+ self.assertEqual(outs[0], outs[1], 'same seed replays the order')
92
+ self.assertNotEqual(outs[0], outs[2], 'a different seed shuffles')
93
+
94
+ def test_overlap_with_forbidden_ids_fails(self):
95
+ prompts = [{'id': 'a', 'split': 'train', 'text': 'fix it'}]
96
+ scores = {i: 0.1 for i in INTENTS}
97
+ with tempfile.TemporaryDirectory() as d:
98
+ data = Path(d) / 'data'
99
+ data.mkdir()
100
+ self.write_data(data, prompts, [self.teacher_row('a', scores)])
101
+ forbid = Path(d) / 'forbid.json'
102
+ forbid.write_text(json.dumps(['a']), encoding='utf-8')
103
+ with self.assertRaisesRegex(ValueError, 'overlap'):
104
+ laya_exporter.export(data, 'train', Path(d) / 'o.json', Path(d) / 'm.json',
105
+ fake_builder, seed=7, forbid_path=forbid)
106
+
107
+ def test_missing_teacher_row_is_skipped_and_counted(self):
108
+ prompts = [{'id': 'a', 'split': 'train', 'text': 'fix it'},
109
+ {'id': 'b', 'split': 'train', 'text': 'no teacher'}]
110
+ scores = {i: 0.1 for i in INTENTS}
111
+ with tempfile.TemporaryDirectory() as d:
112
+ data = Path(d) / 'data'
113
+ data.mkdir()
114
+ self.write_data(data, prompts, [self.teacher_row('a', scores)])
115
+ out = Path(d) / 'o.json'
116
+ summary = laya_exporter.export(data, 'train', out, Path(d) / 'm.json', fake_builder, seed=7)
117
+ self.assertEqual((summary['items'], summary['skippedNoTeacher']), (12, 1))
118
+
119
+ def test_oversample_repeats_only_selected_positive_intent(self):
120
+ prompts = [{'id': 'a', 'split': 'train', 'text': 'restructure'},
121
+ {'id': 'b', 'split': 'train', 'text': 'fix it'}]
122
+ scores_a = {i: (0.9 if i == 'refactor' else 0.0) for i in INTENTS}
123
+ scores_b = {i: (0.9 if i == 'fix' else 0.0) for i in INTENTS}
124
+ with tempfile.TemporaryDirectory() as d:
125
+ data = Path(d) / 'data'
126
+ data.mkdir()
127
+ self.write_data(data, prompts, [self.teacher_row('a', scores_a), self.teacher_row('b', scores_b)])
128
+ out = Path(d) / 'o.json'
129
+ summary = laya_exporter.export(data, 'train', out, Path(d) / 'm.json', fake_builder,
130
+ seed=0, oversample={'refactor': 3})
131
+ rows = [json.loads(line) for line in out.read_text(encoding='utf-8').strip().split('\n')]
132
+ keys = [(r['promptId'], r['intent']) for r in rows]
133
+ self.assertEqual(summary['items'], 26, '24 base items plus two refactor repeats')
134
+ self.assertEqual(keys.count(('a', 'refactor')), 3)
135
+ self.assertTrue(all(keys.count(('a', intent)) == 1 for intent in INTENTS if intent != 'refactor'),
136
+ 'sibling intents must not be reweighted')
137
+ self.assertTrue(all(keys.count(('b', intent)) == 1 for intent in INTENTS),
138
+ 'non-positive prompt must remain at base multiplicity')
139
+ self.assertEqual(summary['manifest']['oversample'], {'refactor': 3})
140
+
141
+ def test_bad_oversample_spec_fails(self):
142
+ with tempfile.TemporaryDirectory() as d:
143
+ data = Path(d) / 'data'
144
+ data.mkdir()
145
+ self.write_data(data, [], [])
146
+ with self.assertRaisesRegex(ValueError, 'oversample'):
147
+ laya_exporter.export(data, 'train', Path(d) / 'o.json', Path(d) / 'm.json',
148
+ fake_builder, oversample={'nope': 2})
149
+ with self.assertRaisesRegex(ValueError, 'oversample'):
150
+ laya_exporter.export(data, 'train', Path(d) / 'o.json', Path(d) / 'm.json',
151
+ fake_builder, oversample={'fix': 1})
152
+
153
+
154
+ if __name__ == '__main__':
155
+ unittest.main()