harness-everything 0.20.7 → 0.22.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +26 -0
  4. package/benchmarks/fixtures/system-one-routing.json +549 -0
  5. package/benchmarks/results/system-one/cua-s1-forms-cpu-2026-09-23/README.md +62 -0
  6. package/benchmarks/results/system-one/cua-s1-forms-cpu-2026-09-23/report.json +856 -0
  7. package/benchmarks/results/system-one/cua-s1-forms-resident-cpu-2026-09-23/README.md +74 -0
  8. package/benchmarks/results/system-one/cua-s1-forms-resident-cpu-2026-09-23/report.json +856 -0
  9. package/ci/fixtures/system-one-provider.cjs +13 -0
  10. package/ci/fixtures/system-one-resident-stub.py +28 -0
  11. package/ci/mechanism-packaging-bytecode.test.js +61 -0
  12. package/ci/mechanism-system-one-contract.test.js +48 -0
  13. package/ci/mechanism-system-one-evaluation.test.js +87 -0
  14. package/ci/mechanism-system-one-install.test.js +106 -0
  15. package/ci/mechanism-system-one-provider.test.js +63 -0
  16. package/ci/mechanism-system-one-resident.test.js +185 -0
  17. package/ci/mechanism-system-one-router.test.js +101 -0
  18. package/ci/system-one-adapter-test.py +222 -0
  19. package/docs/platform-capabilities.md +14 -0
  20. package/docs/system-one-routing.md +271 -0
  21. package/harness-everything/SKILL.md +1 -1
  22. package/harness-everything/scripts/system-one/contract.js +45 -0
  23. package/harness-everything/scripts/system-one/cua_adapter.py +353 -0
  24. package/harness-everything/scripts/system-one/evaluate.js +98 -0
  25. package/harness-everything/scripts/system-one/install.js +161 -0
  26. package/harness-everything/scripts/system-one/provider.js +79 -0
  27. package/harness-everything/scripts/system-one/resident.js +176 -0
  28. package/harness-everything/scripts/system-one/router.js +37 -0
  29. package/harness-everything/scripts/tier-router.js +16 -0
  30. package/opencode-plugin/plugin.json +1 -1
  31. package/package.json +2 -1
  32. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  33. package/plugins/harness-everything/plugin.json +1 -1
  34. package/plugins/harness-everything/scripts/lib/packaging-noise.js +6 -0
  35. package/plugins/harness-everything/scripts/lib/skills.js +2 -0
  36. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  37. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +45 -0
  38. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +353 -0
  39. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +98 -0
  40. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +161 -0
  41. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +79 -0
  42. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +176 -0
  43. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +37 -0
  44. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +16 -0
  45. package/sbom.cdx.json +7 -7
  46. package/scripts/build-openai-submission.js +2 -0
  47. package/scripts/evaluate-system-one.js +66 -0
  48. package/scripts/lib/packaging-noise.js +6 -0
  49. package/scripts/lib/skills.js +2 -0
  50. package/scripts/sync-openai-plugin.js +2 -1
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+ // Deliberately synthetic transport fixture, never model-quality evidence.
3
+ const mode = process.argv[2];
4
+ if (mode === 'timeout') setInterval(() => {}, 1000);
5
+ else if (mode === 'overflow') process.stdout.write('x'.repeat(2 * 1024 * 1024));
6
+ else if (mode === 'exit') process.exit(3);
7
+ else if (mode === 'invalid') console.log('not-json');
8
+ else { let input = ''; process.stdin.on('data', c => { input += c; }); process.stdin.on('end', () => {
9
+ const req = JSON.parse(input);
10
+ console.log(JSON.stringify({ schemaVersion: 1, requestHash: req.requestHash, catalogHash: req.catalogHash,
11
+ model: { id: 'fixture', revision: 'fixture-v1', domain: mode === 'forms' ? 'forms-v1' : 'harness-routing-v1' },
12
+ scores: req.options.map((o, i) => ({ id: o.id, probability: i === 0 ? 1 : 0 })) }));
13
+ }); }
@@ -0,0 +1,28 @@
1
+ """Stub scorer behind the real resident server code; never model-quality evidence."""
2
+ import importlib.util
3
+ from pathlib import Path
4
+ import sys
5
+ import time
6
+
7
+ sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
8
+ path = Path(__file__).resolve().parents[2] / 'harness-everything/scripts/system-one/cua_adapter.py'
9
+ spec = importlib.util.spec_from_file_location('adapter', path)
10
+ adapter = importlib.util.module_from_spec(spec)
11
+ spec.loader.exec_module(adapter)
12
+
13
+
14
+ def factory(weights, manifest):
15
+ if manifest['modelId'] == 'stub-fail':
16
+ raise ValueError('load-failed')
17
+
18
+ def score(request):
19
+ if manifest['modelId'] == 'stub-slow':
20
+ time.sleep(3)
21
+ return [1.0] + [0.0] * (len(request['options']) - 1)
22
+ return score, {'context_tokens': 224, 'option_tokens': 96}
23
+
24
+
25
+ if __name__ == '__main__':
26
+ if sys.argv[1:2] != ['--serve']:
27
+ sys.exit(2)
28
+ sys.exit(adapter.serve_main(sys.argv[2:], scorer_factory=factory))
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+ // Python bytecode written by local/CI test runs is an untracked build artifact; no distribution may ship it.
3
+ const { test } = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { spawnSync } = require('node:child_process');
9
+ const { copyDir } = require('../scripts/lib/skills');
10
+ const { filesUnder } = require('../scripts/build-openai-submission');
11
+ const root = path.resolve(__dirname, '..');
12
+ const noise = files => files.filter(f => /(^|[\\/])__pycache__([\\/]|$)|\.py[co]$/.test(f));
13
+
14
+ function plant(dir) {
15
+ fs.mkdirSync(path.join(dir, '__pycache__'), { recursive: true });
16
+ fs.writeFileSync(path.join(dir, '__pycache__', 'cua_adapter.cpython-313.pyc'), 'bytecode');
17
+ fs.writeFileSync(path.join(dir, 'stray.pyc'), 'bytecode');
18
+ fs.writeFileSync(path.join(dir, 'keep.py'), 'print(1)\n');
19
+ }
20
+
21
+ test('PK-01 skills installer copy and submission file walk skip Python bytecode', () => {
22
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-pk-'));
23
+ try {
24
+ const src = path.join(tmp, 'src', 'scripts');
25
+ plant(src);
26
+ copyDir(path.join(tmp, 'src'), path.join(tmp, 'dest'));
27
+ const copied = filesUnder(path.join(tmp, 'dest'));
28
+ assert.deepEqual(noise(copied), []);
29
+ assert.ok(copied.includes('scripts/keep.py'));
30
+ const walked = filesUnder(path.join(tmp, 'src'));
31
+ assert.deepEqual(noise(walked), []);
32
+ assert.deepEqual(walked, ['scripts/keep.py']);
33
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
34
+ });
35
+
36
+ test('PK-02 plugin sync does not mirror bytecode from the canonical tree', () => {
37
+ const canonical = path.join(root, 'harness-everything', 'scripts', 'system-one');
38
+ const planted = [path.join(canonical, '__pycache__', 'cua_adapter.cpython-313.pyc'), path.join(canonical, 'stray.pyc')];
39
+ const hadCache = fs.existsSync(path.join(canonical, '__pycache__'));
40
+ try {
41
+ fs.mkdirSync(path.join(canonical, '__pycache__'), { recursive: true });
42
+ for (const file of planted) fs.writeFileSync(file, 'bytecode');
43
+ const sync = spawnSync(process.execPath, [path.join(root, 'scripts', 'sync-openai-plugin.js')], { cwd: root, encoding: 'utf8' });
44
+ assert.equal(sync.status, 0, sync.stderr);
45
+ const mirror = path.join(root, 'plugins', 'harness-everything', 'skills', 'harness-everything', 'scripts', 'system-one');
46
+ assert.deepEqual(noise(filesUnder(mirror)), []);
47
+ assert.equal(fs.existsSync(path.join(mirror, '__pycache__')), false);
48
+ } finally {
49
+ for (const file of planted) fs.rmSync(file, { force: true });
50
+ if (!hadCache) fs.rmSync(path.join(canonical, '__pycache__'), { recursive: true, force: true });
51
+ }
52
+ });
53
+
54
+ test('PK-03 Python tests do not write bytecode into the source tree', () => {
55
+ const canonical = path.join(root, 'harness-everything', 'scripts', 'system-one');
56
+ fs.rmSync(path.join(canonical, '__pycache__'), { recursive: true, force: true });
57
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
58
+ const run = spawnSync(python, [path.join(__dirname, 'system-one-adapter-test.py')], { encoding: 'utf8', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '' } });
59
+ assert.equal(run.status, 0, run.stderr);
60
+ assert.equal(fs.existsSync(path.join(canonical, '__pycache__')), false);
61
+ });
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const { createRequest, validateRequest, decide } = require('../harness-everything/scripts/system-one/contract');
5
+ const options = [{ id: 'tier1', text: 'Bounded edit' }, { id: 'tier3', text: 'Architecture' }];
6
+ const request = () => createRequest('tier', '修正 typo', options);
7
+ function response(req, p = [0.95, 0.05]) {
8
+ return { schemaVersion: 1, requestHash: req.requestHash, catalogHash: req.catalogHash,
9
+ model: { id: 'test', revision: 'test-v1', domain: 'harness-routing-v1' },
10
+ scores: req.options.map((o, i) => ({ id: o.id, probability: p[i] })) };
11
+ }
12
+ test('S1-C01 complete response, no mutation and repeatability', () => {
13
+ const req = request(); const res = response(req); const before = JSON.stringify({ req, res });
14
+ assert.deepEqual(decide(req, res), { status: 'accepted', reason: 'scored', selectedId: 'tier1', confidence: 0.95, margin: 0.8999999999999999, model: res.model });
15
+ assert.deepEqual(decide(req, res), decide(req, res));
16
+ assert.equal(JSON.stringify({ req, res }), before);
17
+ assert.deepEqual(req, request());
18
+ assert.equal(validateRequest(req), true);
19
+ assert.notEqual(req.requestHash, createRequest('tier', 'other', options).requestHash);
20
+ assert.notEqual(req.catalogHash, createRequest('tier', 'other', [...options].reverse()).catalogHash);
21
+ });
22
+ test('S1-C02 rejected input partitions and byte boundaries', () => {
23
+ for (const context of ['', ' ', null, 1, {}, 'x'.repeat(65537)]) assert.throws(() => createRequest('tier', context, options), { code: 'invalid-request' });
24
+ for (const task of ['', null, 'A', 'a'.repeat(81)]) assert.throws(() => createRequest(task, 'x', options));
25
+ for (const opts of [null, [], [options[0]], [options[0], options[0]], [{ id: 'x', text: '' }, options[1]], [{ ...options[0], extra: true }, options[1]], [{ id: 1, text: 'x' }, options[1]], [{ id: 'x', text: '中'.repeat(1366) }, options[1]], Array.from({ length: 257 }, (_, i) => ({ id: 'a' + i, text: 'x' }))]) assert.throws(() => createRequest('tier', 'x', opts));
26
+ const max = createRequest('a'.repeat(80), 'x'.repeat(65536), Array.from({ length: 256 }, (_, i) => ({ id: 'a' + i, text: 'x'.repeat(4096) })));
27
+ assert.equal(validateRequest(max), true);
28
+ for (const mutate of [r => { r.extra = 1; }, r => { delete r.context; }, r => { r.schemaVersion = 2; }, r => { r.options.reverse(); }, r => { r.context = 'replay'; }]) {
29
+ const r = request(); mutate(r); assert.throws(() => validateRequest(r));
30
+ }
31
+ });
32
+ test('S1-C03 complete output validation and no raw-data leakage', () => {
33
+ const req = request();
34
+ for (const mutate of [r => { r.schemaVersion = 2; }, r => { r.requestHash = 'stale'; }, r => { r.catalogHash = 'stale'; }, r => { r.scores.pop(); }, r => { r.scores.push(r.scores[0]); }, r => { r.scores.reverse(); }, r => { r.scores[1].id = r.scores[0].id; }, r => { r.scores[0].probability = NaN; }, r => { r.scores[0].probability = Infinity; }, r => { r.scores[0].probability = -1; }, r => { r.scores[0].probability = 1.1; }, r => { r.scores[0].probability = '0.95'; }, r => { r.scores[0].probability = 0.8; }, r => { r.scores[0].extra = 'secret'; }, r => { r.model.extra = 'secret'; }, r => { r.model.revision = ''; }, r => { delete r.model; }, r => { r.extra = 'secret'; }]) {
35
+ const res = response(req); mutate(res);
36
+ assert.deepEqual(decide(req, res), { status: 'invalid-output', reason: 'invalid-response', selectedId: null, confidence: null, margin: null, model: null });
37
+ }
38
+ for (const value of [null, [], 'invalid']) assert.equal(decide(req, value).status, 'invalid-output');
39
+ });
40
+ test('S1-C04 abstention and policy boundaries', () => {
41
+ const req = request(); const res = response(req);
42
+ res.model.domain = 'forms-v1'; assert.equal(decide(req, res).reason, 'domain-mismatch');
43
+ assert.equal(decide(req, response(req, [0.5, 0.5]), { minConfidence: 0, minMargin: 0 }).reason, 'tie');
44
+ assert.equal(decide(req, response(req, [0.8, 0.2])).reason, 'low-confidence');
45
+ assert.equal(decide(req, response(req, [0.6, 0.4]), { minConfidence: 0.5, minMargin: 0.3 }).reason, 'low-margin');
46
+ assert.equal(decide(req, response(req, [1, 0]), { minConfidence: 1, minMargin: 1 }).status, 'accepted');
47
+ for (const policy of [null, { minConfidence: NaN }, { minMargin: -1 }, { minConfidence: 2 }, { extra: 1 }, { domain: '' }]) assert.throws(() => decide(req, response(req), policy), { code: 'invalid-policy' });
48
+ });
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { spawnSync } = require('node:child_process');
7
+ const assert = require('node:assert/strict');
8
+ const { createRequest } = require('../harness-everything/scripts/system-one/contract');
9
+ const { TIER_OPTIONS } = require('../harness-everything/scripts/system-one/router');
10
+ const { validateCorpus, evaluate } = require('../harness-everything/scripts/system-one/evaluate');
11
+ const make = () => ({ schemaVersion: 1, cases: [
12
+ { id: 'a', family: 'typo', split: 'holdout', language: 'en', source: 'human:fixture', reviewed: false, request: createRequest('tier', 'fix typo', TIER_OPTIONS), gold: 'tier1' },
13
+ { id: 'b', family: 'unclear', split: 'holdout', language: 'zh-TW', source: 'human:fixture', reviewed: false, request: createRequest('tier', '看看這個', TIER_OPTIONS), gold: null },
14
+ ] });
15
+ const decision = id => ({ status: id ? 'accepted' : 'abstain', reason: id ? 'scored' : 'unclassified', selectedId: id, confidence: 1, margin: 1, model: { id: 'fixture', revision: 'v1', domain: 'harness-routing-v1' } });
16
+ const oneHot = id => TIER_OPTIONS.map(o => (o.id === (id || 'unclassified') ? 1 : 0));
17
+ function records() { return make().cases.map(c => ({ id: c.id, baseline: 'tier2', runs: [0, 1].map(() => ({ decision: decision(c.gold), scores: oneHot(c.gold), latencyMs: 20, coldStart: true })) })); }
18
+ test('S1-E01 exact paired metrics, no promotion from fixtures or cold timing', () => {
19
+ const result = evaluate(make(), records());
20
+ assert.equal(result.model.accuracy, 1); assert.equal(result.model.coverage, 0.5);
21
+ assert.equal(result.model.acceptedPrecision, 1); assert.equal(result.model.acceptedErrorRate, 0);
22
+ assert.equal(result.model.macroF1, 0.5); assert.equal(result.baseline.accuracy, 0);
23
+ assert.equal(result.agreement, 1); assert.equal(result.latency.coldP95Ms, 20); assert.equal(result.latency.warmP95Ms, null);
24
+ assert.equal(result.rolloutReady, false); assert.equal(result.gates.reviewedHoldout, false);
25
+ assert.equal(result.gates.policyEvidence, false); assert.equal(result.gates.liveHostEvidence, false);
26
+ assert.deepEqual(evaluate(make(), records()), evaluate(make(), records()));
27
+ });
28
+ test('S1-E02 corpus completeness, family leakage and no duplicated prompts', () => {
29
+ assert.equal(validateCorpus(make()), true);
30
+ for (const mutate of [c => { c.schemaVersion = 2; }, c => { c.extra = true; }, c => { c.cases = []; }, c => { c.cases[1].id = 'a'; }, c => { c.cases[1].family = 'typo'; c.cases[1].split = 'train'; }, c => { c.cases[1].request = c.cases[0].request; }, c => { c.cases[0].gold = 'unknown'; }, c => { c.cases[0].language = 'unknown'; }, c => { c.cases[0].reviewed = 'yes'; }, c => { c.cases[0].source = ''; }, c => { c.cases[0].request = createRequest('tier', 'x', [{ id: 'x', text: 'x' }, { id: 'y', text: 'y' }]); }, c => { delete c.cases[0].family; }, c => { c.cases[0].extra = 1; }]) { const c = make(); mutate(c); assert.throws(() => validateCorpus(c)); }
31
+ });
32
+ test('S1-E03 missing/extra/invalid predictions cannot silently improve scores', () => {
33
+ for (const mutate of [r => r.pop(), r => r.push(r[0]), r => { r[0].id = 'unknown'; }, r => { r[0].runs.pop(); }, r => { r[0].runs[0].decision.selectedId = 'unknown'; }, r => { r[0].runs[0].latencyMs = NaN; }, r => { r[0].runs[0].latencyMs = -1; }, r => { r[0].runs[0].coldStart = 'false'; }, r => { r[0].runs[0].decision.status = 'abstain'; }, r => { r[0].baseline = 'unknown'; }, r => { r[0].runs[0].decision.model.revision = 'v2'; }]) { const r = records(); mutate(r); assert.throws(() => evaluate(make(), r)); }
34
+ for (const mutate of [r => { delete r[0].runs[0].scores; }, r => { r[0].runs[0].scores = [1, 0, 0]; }, r => { r[0].runs[0].scores = [0.5, 0.5, 0, 0]; }, r => { r[0].runs[0].scores = [1, 0, 0, NaN]; }, r => { r[0].runs[0].scores = null; }, r => { r[0].runs[0].decision = { status: 'unavailable', reason: 'provider-timeout' }; }]) { const r = records(); mutate(r); assert.throws(() => evaluate(make(), r)); }
35
+ const r = records(); r[0].runs[1].decision = decision('tier3'); r[0].runs[1].scores = oneHot('tier3');
36
+ assert.equal(evaluate(make(), r).agreement, 0.5);
37
+ });
38
+ test('S1-E06 repeatability compares the full score vector, not only top-2 summaries', () => {
39
+ const r = records();
40
+ const accepted = { status: 'accepted', reason: 'scored', selectedId: 'tier1', confidence: 0.9, margin: 0.85, model: { id: 'fixture', revision: 'v1', domain: 'harness-routing-v1' } };
41
+ r[0].runs[0] = { decision: { ...accepted }, scores: [0.9, 0.05, 0.03, 0.02], latencyMs: 20, coldStart: true };
42
+ r[0].runs[1] = { decision: { ...accepted }, scores: [0.9, 0.05, 0.02, 0.03], latencyMs: 20, coldStart: true };
43
+ const report = evaluate(make(), r);
44
+ assert.equal(report.agreement, 0.5); assert.equal(report.gates.repeatability, false);
45
+ r[0].runs[1].scores = [0.9, 0.05, 0.03, 0.02];
46
+ assert.equal(evaluate(make(), r).agreement, 1);
47
+ r.forEach(x => x.runs.forEach(v => { v.decision = { status: 'unavailable', reason: 'provider-config' }; v.scores = null; }));
48
+ assert.equal(evaluate(make(), r).agreement, 1);
49
+ });
50
+ test('S1-E04 zero coverage and wrong accepted predictions fail quality gates', () => {
51
+ const r = records(); r.forEach(x => x.runs.forEach(v => { v.decision = { status: 'unavailable', reason: 'provider-config' }; v.scores = null; }));
52
+ const report = evaluate(make(), r);
53
+ assert.equal(report.model.coverage, 0); assert.equal(report.model.acceptedPrecision, null); assert.equal(report.rolloutReady, false);
54
+ const wrong = records(); wrong.forEach(x => x.runs.forEach(v => { v.decision = decision('tier3'); v.scores = oneHot('tier3'); }));
55
+ assert.equal(evaluate(make(), wrong).model.acceptedErrorRate, 1);
56
+ });
57
+ test('S1-E05 real evaluation CLI repeats with only documented timing volatility', () => {
58
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-eval-'));
59
+ try {
60
+ const root = path.resolve(__dirname, '..');
61
+ const input = path.join(dir, 'corpus.json'); fs.writeFileSync(input, JSON.stringify(make()));
62
+ const run = () => {
63
+ const output = path.join(dir, 'report.json');
64
+ const child = spawnSync(process.execPath, [path.join(root, 'scripts/evaluate-system-one.js'), input, path.join(dir, 'missing.json'), output], { encoding: 'utf8', cwd: root });
65
+ assert.equal(child.status, 0, child.stderr);
66
+ const report = JSON.parse(fs.readFileSync(output, 'utf8'));
67
+ assert.equal(report.model.coverage, 0); assert.equal(report.rolloutReady, false);
68
+ assert.equal(report.records[0].runs[0].decision.reason, 'provider-config');
69
+ assert.equal(report.records[0].runs[0].scores, null);
70
+ assert.deepEqual(report.evidence.source, { status: 'unavailable', reason: 'provider-config' });
71
+ assert.equal(report.evidence.environment.python, null);
72
+ assert.equal(report.gates.sourceProvenance, false);
73
+ report.records.forEach(r => r.runs.forEach(v => { v.latencyMs = 0; }));
74
+ report.latency.coldP95Ms = 0;
75
+ return { status: child.status, stdout: child.stdout, stderr: child.stderr, report, files: fs.readdirSync(dir).sort() };
76
+ };
77
+ assert.deepEqual(run(), run());
78
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
79
+ });
80
+ test('S1-E07 source provenance gate requires the pinned cua_s1 revision', () => {
81
+ const recorded = status => ({ status: 'recorded', provenance: { python: { implementation: 'CPython', version: '3.12.4' }, cuaS1: { distribution: 'cua-s1', version: '0.1.0', sourceRevision: null, pinnedRevision: 'b'.repeat(40), sourceRevisionStatus: status }, torch: null } });
82
+ assert.equal(evaluate(make(), records()).gates.sourceProvenance, false);
83
+ assert.equal(evaluate(make(), records(), { status: 'unavailable', reason: 'provider-exit' }).gates.sourceProvenance, false);
84
+ for (const status of ['unavailable', 'mismatch']) assert.equal(evaluate(make(), records(), recorded(status)).gates.sourceProvenance, false);
85
+ assert.equal(evaluate(make(), records(), recorded('pinned')).gates.sourceProvenance, true);
86
+ assert.equal(evaluate(make(), records(), recorded('pinned')).rolloutReady, false);
87
+ });
@@ -0,0 +1,106 @@
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 install = require('../harness-everything/scripts/system-one/install');
10
+ const { validateManifest, PINNED_CUA_S1_REVISION } = require('../harness-everything/scripts/system-one/provider');
11
+ const script = path.join(__dirname, '../harness-everything/scripts/system-one/install.js');
12
+ const sha = buf => createHash('sha256').update(buf).digest('hex');
13
+
14
+ test('S1-I01 pins stay consistent with the provider contract', () => {
15
+ const { PINS } = install;
16
+ assert.equal(PINS.cuaS1Revision, PINNED_CUA_S1_REVISION);
17
+ assert.ok(PINS.cuaS1Spec.includes(`@${PINNED_CUA_S1_REVISION}#subdirectory=libs/cua-s1/python`));
18
+ assert.match(PINS.modelRevision, /^[0-9a-f]{40}$/);
19
+ assert.equal(PINS.modelId, 'cua-ai/cua-s1-forms'); assert.equal(PINS.domain, 'forms-v1');
20
+ for (const file of Object.values(PINS.files)) {
21
+ assert.match(file.sha256, /^[0-9a-f]{64}$/); assert.ok(Number.isInteger(file.size) && file.size > 0);
22
+ assert.equal(install.fileUrl(file.name), `https://huggingface.co/cua-ai/cua-s1-forms/resolve/${PINS.modelRevision}/${file.name}`);
23
+ }
24
+ assert.equal(path.basename(PINS.files.config.name, '.json'), path.basename(PINS.files.weights.name, '.safetensors'));
25
+ const dir = path.resolve(os.tmpdir(), 'system-one');
26
+ const manifest = install.buildManifest(dir, path.join(dir, 'venv', 'python'));
27
+ assert.equal(validateManifest(manifest), true);
28
+ assert.equal(manifest.checkpoint, path.join(dir, 'checkpoints', PINS.modelRevision, PINS.files.weights.name));
29
+ assert.equal(manifest.weightsSha256, PINS.files.weights.sha256); assert.equal(manifest.configSha256, PINS.files.config.sha256);
30
+ assert.equal(manifest.revision, PINS.modelRevision); assert.equal(manifest.timeoutMs, 10000);
31
+ assert.equal(manifest.transport, 'resident'); assert.equal(manifest.idleTimeoutMs, 1800000);
32
+ });
33
+
34
+ test('S1-I02 interpreter selection accepts only the upstream-supported Python range', () => {
35
+ for (const v of ['3.11.0', '3.12.4', '3.13.6']) assert.equal(install.supportedPython(v), true);
36
+ for (const v of ['3.10.9', '3.14.0', '2.7.18', '3.13', '', 'x', null]) assert.equal(install.supportedPython(v), false);
37
+ const win = install.pythonCandidates('win32');
38
+ assert.deepEqual(win[0], ['py', '-3.13']);
39
+ assert.ok(win.every(c => !c.includes('-3.14')));
40
+ assert.deepEqual(install.pythonCandidates('linux')[0], ['python3.13']);
41
+ assert.equal(install.venvPython('/x', 'win32'), path.join('/x', 'venv', 'Scripts', 'python.exe'));
42
+ assert.equal(install.venvPython('/x', 'linux'), path.join('/x', 'venv', 'bin', 'python'));
43
+ });
44
+
45
+ test('S1-I03 argument parsing is explicit and rejects ambiguous input', () => {
46
+ const home = install.parseArgs([]);
47
+ assert.equal(home.dir, path.join(os.homedir(), '.agents', 'harness-everything', 'system-one'));
48
+ assert.equal(home.python, null); assert.equal(home.dryRun, false);
49
+ const dir = path.resolve(os.tmpdir(), 's1');
50
+ assert.deepEqual(install.parseArgs(['--dir', dir, '--python', 'py', '--dry-run']), { dir, python: 'py', dryRun: true });
51
+ for (const argv of [['--dir', 'relative'], ['--dir'], ['--python'], ['--unknown'], ['extra'], ['--dry-run', '--dry-run']]) {
52
+ assert.throws(() => install.parseArgs(argv), { message: 'usage' });
53
+ }
54
+ });
55
+
56
+ test('S1-I04 downloads are verified before an atomic write; a valid file is reused', async () => {
57
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-install-'));
58
+ try {
59
+ const good = Buffer.from('pinned-bytes\r\n');
60
+ const spec = { name: 'x.json', sha256: sha(good), size: good.length };
61
+ const dest = path.join(dir, 'x.json');
62
+ let calls = 0;
63
+ const fetcher = bytes => async () => { calls++; return bytes; };
64
+ for (const bad of [Buffer.from('tampered-bytes'), Buffer.concat([good, Buffer.from('x')]), Buffer.alloc(0)]) {
65
+ await assert.rejects(install.ensureFile('https://example.invalid/x', dest, spec, fetcher(bad)), /download-verification/);
66
+ assert.equal(fs.existsSync(dest), false);
67
+ assert.deepEqual(fs.readdirSync(dir), []);
68
+ }
69
+ assert.equal(await install.ensureFile('https://example.invalid/x', dest, spec, fetcher(good)), 'downloaded');
70
+ assert.ok(fs.readFileSync(dest).equals(good));
71
+ const before = calls;
72
+ assert.equal(await install.ensureFile('https://example.invalid/x', dest, spec, fetcher(good)), 'verified-existing');
73
+ assert.equal(calls, before);
74
+ fs.writeFileSync(dest, 'corrupted');
75
+ assert.equal(await install.ensureFile('https://example.invalid/x', dest, spec, fetcher(good)), 'downloaded');
76
+ assert.ok(fs.readFileSync(dest).equals(good));
77
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
78
+ });
79
+
80
+ test('S1-I06 child command output goes to stderr so stdout stays machine-readable JSON', () => {
81
+ const code = `require(${JSON.stringify(script)}).exec(process.execPath, ['-e', 'console.log("pip-noise")'])`;
82
+ const child = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
83
+ assert.equal(child.status, 0, child.stderr);
84
+ assert.equal(child.stdout, '');
85
+ assert.match(child.stderr, /pip-noise/);
86
+ const captured = spawnSync(process.execPath, ['-e', `process.stdout.write(require(${JSON.stringify(script)}).exec(process.execPath, ['-e', 'console.log("3.13.6")'], true))`], { encoding: 'utf8' });
87
+ assert.equal(captured.stdout, '3.13.6');
88
+ });
89
+
90
+ test('S1-I05 dry run prints the pinned plan and changes nothing, repeatably', () => {
91
+ const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-dry-')), 'target');
92
+ try {
93
+ const run = () => spawnSync(process.execPath, [script, '--dir', dir, '--python', 'python-not-used', '--dry-run'], { encoding: 'utf8' });
94
+ const one = run(); const two = run();
95
+ assert.equal(one.status, 0, one.stderr); assert.equal(one.stdout, two.stdout);
96
+ const plan = JSON.parse(one.stdout);
97
+ assert.equal(plan.dryRun, true); assert.equal(plan.dir, dir);
98
+ assert.equal(plan.manifest, path.join(dir, 'manifest.json'));
99
+ assert.ok(plan.steps.some(s => s.includes(install.PINS.cuaS1Spec)));
100
+ assert.ok(plan.steps.some(s => s.includes(install.PINS.torchIndex)));
101
+ assert.deepEqual(plan.env, { HARNESS_SYSTEM_ONE_MODE: 'shadow', HARNESS_SYSTEM_ONE_CONFIG: path.join(dir, 'manifest.json') });
102
+ assert.equal(fs.existsSync(dir), false);
103
+ const bad = spawnSync(process.execPath, [script, '--dir', 'relative'], { encoding: 'utf8' });
104
+ assert.equal(bad.status, 2); assert.match(bad.stderr, /Usage/);
105
+ } finally { fs.rmSync(path.dirname(dir), { recursive: true, force: true }); }
106
+ });
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const path = require('node:path');
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const { spawnSync } = require('node:child_process');
8
+ const { createRequest, decide } = require('../harness-everything/scripts/system-one/contract');
9
+ const { score, runProvider, validateManifest, provenance, validateProvenance, PINNED_CUA_S1_REVISION } = require('../harness-everything/scripts/system-one/provider');
10
+ const fixture = path.join(__dirname, 'fixtures/system-one-provider.cjs');
11
+ const request = createRequest('tier', '修正 typo; $(never execute)', [{ id: 'tier1', text: 'Small' }, { id: 'tier3', text: 'Large' }]);
12
+ const manifest = () => ({ schemaVersion: 1, python: 'python3', checkpoint: path.resolve('model.safetensors'), weightsSha256: 'a'.repeat(64), configSha256: 'b'.repeat(64), modelId: 'test', revision: 'v1', domain: 'harness-routing-v1' });
13
+ test('S1-P01 real IPC exact input/output repeated in clean child processes', () => {
14
+ const one = runProvider(request, process.execPath, [fixture, 'ok']);
15
+ const two = runProvider(request, process.execPath, [fixture, 'ok']);
16
+ assert.deepEqual(one, two); assert.equal(one.status, 'scored');
17
+ assert.equal(decide(request, one.response).selectedId, 'tier1');
18
+ assert.deepEqual(Object.keys(one).sort(), ['response', 'status']);
19
+ });
20
+ test('S1-P02 unavailable, timeout, output bounds, malformed output and repeatability', () => {
21
+ for (const [mode, reason] of [['timeout', 'provider-timeout'], ['overflow', 'provider-output-limit'], ['exit', 'provider-exit'], ['invalid', 'provider-json']]) {
22
+ // Only the timeout case uses a short budget; child startup under parallel CI load can exceed 300ms.
23
+ const call = () => runProvider(request, process.execPath, [fixture, mode], mode === 'timeout' ? 300 : 10000);
24
+ assert.deepEqual(call(), { status: 'unavailable', reason }); assert.deepEqual(call(), call());
25
+ }
26
+ assert.deepEqual(runProvider(request, path.join(os.tmpdir(), 'absent-system-one-python'), []), { status: 'unavailable', reason: 'provider-unavailable' });
27
+ assert.deepEqual(score(request, '/missing/system-one-manifest.json'), { status: 'unavailable', reason: 'provider-config' });
28
+ });
29
+ test('S1-P03 trusted manifest validation', () => {
30
+ assert.equal(validateManifest(manifest()), true);
31
+ assert.equal(validateManifest({ ...manifest(), timeoutMs: 1 }), true);
32
+ assert.equal(validateManifest({ ...manifest(), timeoutMs: 10000 }), true);
33
+ for (const change of [{ schemaVersion: 2 }, { python: '' }, { checkpoint: 'relative.safetensors' }, { checkpoint: path.resolve('model.pt') }, { weightsSha256: 'abc' }, { configSha256: null }, { modelId: '' }, { revision: null }, { domain: '' }, { timeoutMs: 0 }, { timeoutMs: 10001 }, { timeoutMs: '100' }, { unexpected: true }, { modelId: 'cua-ai/cua-s1-forms' }]) assert.throws(() => validateManifest({ ...manifest(), ...change }));
34
+ for (const key of Object.keys(manifest())) { const m = manifest(); delete m[key]; assert.throws(() => validateManifest(m)); }
35
+ });
36
+ test('S1-P04 Python artifact validation and byte-limit rejection without ML dependency', () => {
37
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
38
+ const result = spawnSync(python, [path.join(__dirname, 'system-one-adapter-test.py')], { encoding: 'utf8' });
39
+ assert.equal(result.status, 0, result.stderr || String(result.error));
40
+ assert.match(result.stderr, /OK/);
41
+ });
42
+ test('S1-P05 runtime/source provenance is recorded, and a missing or mismatched revision stays visible', () => {
43
+ const probe = rev => ({ schemaVersion: 1, python: { implementation: 'CPython', version: '3.12.4' }, cuaS1: { distribution: 'cua-s1', version: '0.1.0', sourceRevision: rev }, torch: '2.5.1' });
44
+ assert.equal(validateProvenance(probe(PINNED_CUA_S1_REVISION)).cuaS1.sourceRevisionStatus, 'pinned');
45
+ assert.equal(validateProvenance(probe('0'.repeat(40))).cuaS1.sourceRevisionStatus, 'mismatch');
46
+ assert.equal(validateProvenance(probe(null)).cuaS1.sourceRevisionStatus, 'unavailable');
47
+ assert.equal(validateProvenance(probe(null)).cuaS1.pinnedRevision, PINNED_CUA_S1_REVISION);
48
+ for (const mutate of [p => { p.schemaVersion = 2; }, p => { p.extra = 1; }, p => { delete p.torch; }, p => { p.python.version = ''; }, p => { p.python.extra = 1; }, p => { p.cuaS1.sourceRevision = 'abc'; }, p => { p.cuaS1.sourceRevision = 'A'.repeat(40); }, p => { p.cuaS1.version = 1; }, p => { p.cuaS1.extra = 1; }, p => { p.torch = 'x'.repeat(129); }, p => { p.python.version = '3.12\n'; }]) {
49
+ const p = probe(null); mutate(p); assert.throws(() => validateProvenance(p));
50
+ }
51
+ assert.deepEqual(provenance('/missing/system-one-manifest.json'), { status: 'unavailable', reason: 'provider-config' });
52
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-prov-'));
53
+ try {
54
+ const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
55
+ const file = path.join(dir, 'manifest.json');
56
+ fs.writeFileSync(file, JSON.stringify({ ...manifest(), python, checkpoint: path.join(dir, 'absent.safetensors') }));
57
+ const one = provenance(file); const two = provenance(file);
58
+ assert.deepEqual(one, two);
59
+ assert.equal(one.status, 'recorded', JSON.stringify(one));
60
+ assert.match(one.provenance.python.version, /^3\.\d+\.\d+/);
61
+ if (one.provenance.cuaS1.distribution === null) assert.equal(one.provenance.cuaS1.sourceRevisionStatus, 'unavailable');
62
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
63
+ });
@@ -0,0 +1,185 @@
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 resident = require('../harness-everything/scripts/system-one/resident');
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 python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
14
+ const stub = path.join(__dirname, 'fixtures/system-one-resident-stub.py');
15
+ const request = createRequest('tier', 'fix a typo in README', TIER_OPTIONS);
16
+ const sha = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
17
+ const sleep = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
18
+
19
+ function fixture(modelId = 'stub') {
20
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-s1-resident-'));
21
+ const checkpoint = path.join(dir, 'model.safetensors');
22
+ fs.writeFileSync(checkpoint, 'synthetic-not-real-weights');
23
+ fs.writeFileSync(path.join(dir, 'model.json'), '{}');
24
+ const manifest = { schemaVersion: 1, python, checkpoint, weightsSha256: sha(checkpoint), configSha256: sha(path.join(dir, 'model.json')),
25
+ modelId, revision: 'v1', domain: 'harness-routing-v1', transport: 'resident', idleTimeoutMs: 60000 };
26
+ const manifestPath = path.join(dir, 'manifest.json');
27
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));
28
+ const spawns = [];
29
+ const deps = { command: m => { spawns.push(m.modelId); return [python, [stub, '--serve']]; } };
30
+ return { dir, manifest, manifestPath, spawns, deps };
31
+ }
32
+ function cleanup(f) {
33
+ try { resident.stop(f.manifest, f.manifestPath); } catch (_) { /* best effort */ }
34
+ fs.rmSync(f.dir, { recursive: true, force: true });
35
+ }
36
+
37
+ test('S1-RS01 manifest transport fields and digest-bound file names', () => {
38
+ const f = fixture();
39
+ try {
40
+ assert.equal(provider.validateManifest(f.manifest), true);
41
+ for (const change of [{ transport: 'oneshot' }, { idleTimeoutMs: 60000 }, { idleTimeoutMs: 14400000 }]) assert.equal(provider.validateManifest({ ...f.manifest, ...change }), true);
42
+ for (const change of [{ transport: 'daemon' }, { transport: '' }, { idleTimeoutMs: 59999 }, { idleTimeoutMs: 14400001 }, { idleTimeoutMs: '60000' }]) {
43
+ assert.throws(() => provider.validateManifest({ ...f.manifest, ...change }));
44
+ }
45
+ const files = resident.stateFiles(f.manifest, f.manifestPath);
46
+ const digest = createHash('sha256').update(JSON.stringify(f.manifest)).digest('hex').slice(0, 16);
47
+ assert.equal(files.state, path.join(f.dir, `system-one-resident-${digest}.json`));
48
+ assert.equal(files.lock, path.join(f.dir, `system-one-resident-${digest}.starting`));
49
+ assert.notEqual(resident.stateFiles({ ...f.manifest, revision: 'v2' }, f.manifestPath).state, files.state);
50
+ } finally { cleanup(f); }
51
+ });
52
+
53
+ test('S1-RS02 cold start never blocks, spawns once, then serves warm repeatable scores', () => {
54
+ const f = fixture();
55
+ try {
56
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-starting' });
57
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-starting' });
58
+ assert.deepEqual(f.spawns, ['stub']);
59
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
60
+ assert.equal(f.spawns.length, 1);
61
+ const one = resident.score(request, f.manifest, f.manifestPath, f.deps);
62
+ const two = resident.score(request, f.manifest, f.manifestPath, f.deps);
63
+ assert.equal(one.status, 'scored'); assert.deepEqual(one, two);
64
+ assert.equal(decide(request, one.response).selectedId, 'tier1');
65
+ assert.equal(resident.status(f.manifest, f.manifestPath).running, true);
66
+ assert.equal(resident.stop(f.manifest, f.manifestPath), true);
67
+ const deadline = Date.now() + 5000;
68
+ while (fs.existsSync(resident.stateFiles(f.manifest, f.manifestPath).state) && Date.now() < deadline) sleep(50);
69
+ assert.equal(resident.status(f.manifest, f.manifestPath).running, false);
70
+ } finally { cleanup(f); }
71
+ });
72
+
73
+ test('S1-RS03 stale state is removed and replaced; a wrong token is rejected without respawn', () => {
74
+ const f = fixture();
75
+ try {
76
+ const { state } = resident.stateFiles(f.manifest, f.manifestPath);
77
+ const dead = spawnSync(process.execPath, ['-e', '0']).pid;
78
+ fs.writeFileSync(state, JSON.stringify({ schemaVersion: 1, pid: dead, port: 9, token: 'a'.repeat(64), startedAt: 1 }));
79
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-starting' });
80
+ assert.equal(f.spawns.length, 1);
81
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
82
+ const good = JSON.parse(fs.readFileSync(state, 'utf8'));
83
+ fs.writeFileSync(state, JSON.stringify({ ...good, token: 'b'.repeat(64) }));
84
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-unavailable' });
85
+ assert.equal(f.spawns.length, 1);
86
+ fs.writeFileSync(state, JSON.stringify(good));
87
+ for (const bad of ['not-json', JSON.stringify({ ...good, extra: 1 }), JSON.stringify({ ...good, token: 'short' })]) {
88
+ fs.writeFileSync(state, bad);
89
+ assert.equal(resident.status(f.manifest, f.manifestPath).running, false);
90
+ }
91
+ fs.writeFileSync(state, JSON.stringify(good));
92
+ } finally { cleanup(f); }
93
+ });
94
+
95
+ test('S1-RS04 a slow server times out within the deadline and is not respawned', () => {
96
+ const f = fixture('stub-slow');
97
+ try {
98
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
99
+ const start = Date.now();
100
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-timeout' });
101
+ assert.ok(Date.now() - start < 2500);
102
+ assert.equal(f.spawns.length, 1);
103
+ } finally { cleanup(f); }
104
+ });
105
+
106
+ test('S1-RS05 startup failure is visible and throttled instead of respawning every prompt', () => {
107
+ const f = fixture('stub-fail');
108
+ try {
109
+ assert.equal(resident.score(request, f.manifest, f.manifestPath, f.deps).reason, 'provider-starting');
110
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), false);
111
+ const lock = JSON.parse(fs.readFileSync(resident.stateFiles(f.manifest, f.manifestPath).lock, 'utf8'));
112
+ assert.equal(lock.failed, 'load-failed');
113
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, f.deps), { status: 'unavailable', reason: 'provider-unavailable' });
114
+ assert.equal(f.spawns.length, 1);
115
+ } finally { cleanup(f); }
116
+ });
117
+
118
+ test('S1-RS06 provider dispatch uses the real adapter and reports a missing ML runtime', () => {
119
+ const f = fixture();
120
+ try {
121
+ assert.deepEqual(provider.score(request, f.manifestPath), { status: 'unavailable', reason: 'provider-starting' });
122
+ const { lock } = resident.stateFiles(f.manifest, f.manifestPath);
123
+ const deadline = Date.now() + 20000;
124
+ while (Date.now() < deadline && !(fs.existsSync(lock) && JSON.parse(fs.readFileSync(lock, 'utf8')).failed)) sleep(100);
125
+ const probe = spawnSync(python, ['-c', 'import torch, cua_s1'], { encoding: 'utf8' });
126
+ if (probe.status !== 0) {
127
+ assert.equal(JSON.parse(fs.readFileSync(lock, 'utf8')).failed, 'load-failed');
128
+ assert.deepEqual(provider.score(request, f.manifestPath), { status: 'unavailable', reason: 'provider-unavailable' });
129
+ }
130
+ const off = { ...f.manifest, transport: 'oneshot' };
131
+ fs.writeFileSync(f.manifestPath, JSON.stringify(off));
132
+ assert.notEqual(provider.score(request, f.manifestPath).reason, 'provider-starting');
133
+ } finally { cleanup(f); }
134
+ });
135
+
136
+ test('S1-RS07 operator CLI reports status and stops a running server', () => {
137
+ const f = fixture();
138
+ try {
139
+ const cli = args => spawnSync(process.execPath, [path.join(__dirname, '../harness-everything/scripts/system-one/resident.js'), ...args], { encoding: 'utf8' });
140
+ assert.equal(JSON.parse(cli(['status', f.manifestPath]).stdout).running, false);
141
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
142
+ const running = JSON.parse(cli(['status', f.manifestPath]).stdout);
143
+ assert.equal(running.running, true); assert.ok(!JSON.stringify(running).includes('token'));
144
+ assert.equal(cli(['stop', f.manifestPath]).status, 0);
145
+ const deadline = Date.now() + 5000;
146
+ while (JSON.parse(cli(['status', f.manifestPath]).stdout).running && Date.now() < deadline) sleep(50);
147
+ assert.equal(JSON.parse(cli(['status', f.manifestPath]).stdout).running, false);
148
+ assert.equal(cli(['bogus', f.manifestPath]).status, 2);
149
+ assert.equal(cli(['status', 'relative.json']).status, 2);
150
+ } finally { cleanup(f); }
151
+ });
152
+
153
+ test('S1-RS08 an executable that cannot spawn is recorded as a visible, throttled failure', () => {
154
+ const f = fixture();
155
+ try {
156
+ const missing = path.join(f.dir, 'no-such-python.exe');
157
+ const deps = { command: () => { f.spawns.push('missing'); return [missing, []]; } };
158
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, deps), { status: 'unavailable', reason: 'provider-unavailable' });
159
+ assert.equal(JSON.parse(fs.readFileSync(resident.stateFiles(f.manifest, f.manifestPath).lock, 'utf8')).failed, 'spawn-failed');
160
+ assert.deepEqual(resident.score(request, f.manifest, f.manifestPath, deps), { status: 'unavailable', reason: 'provider-unavailable' });
161
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 2000, deps), false);
162
+ assert.deepEqual(f.spawns, ['missing']);
163
+ } finally { cleanup(f); }
164
+ });
165
+
166
+ test('S1-RS09 a corrupted state file never leaves an orphan server behind', () => {
167
+ const f = fixture();
168
+ try {
169
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
170
+ const { state } = resident.stateFiles(f.manifest, f.manifestPath);
171
+ const old = JSON.parse(fs.readFileSync(state, 'utf8'));
172
+ fs.writeFileSync(state, 'corrupt');
173
+ assert.equal(resident.ensureReady(f.manifest, f.manifestPath, 20000, f.deps), true);
174
+ const fresh = JSON.parse(fs.readFileSync(state, 'utf8'));
175
+ assert.notEqual(fresh.pid, old.pid);
176
+ // "Stopped serving" is the contract. On POSIX an exited child stays a zombie (kill(pid, 0) succeeds)
177
+ // until this blocked test process reaps it, so a refused/failed ping also proves the server is gone.
178
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
179
+ const serving = () => alive(old.pid) && resident.callSync(old.port, { token: old.token, op: 'ping' }).reply?.ok === true;
180
+ const deadline = Date.now() + 5000;
181
+ while (serving() && Date.now() < deadline) sleep(100);
182
+ assert.equal(serving(), false);
183
+ assert.equal(resident.status(f.manifest, f.manifestPath).pid, fresh.pid);
184
+ } finally { cleanup(f); }
185
+ });