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,101 @@
1
+ 'use strict';
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const { spawnSync } = require('node:child_process');
5
+ const path = require('node:path');
6
+ const { selectTier, TIER_OPTIONS } = require('../harness-everything/scripts/system-one/router');
7
+ const root = path.resolve(__dirname, '..');
8
+ function scorer(id = 'tier2', domain = 'harness-routing-v1') {
9
+ return req => ({ status: 'scored', response: { schemaVersion: 1, requestHash: req.requestHash, catalogHash: req.catalogHash,
10
+ model: { id: 'fixture', revision: 'v1', domain }, scores: req.options.map(o => ({ id: o.id, probability: o.id === id ? 1 : 0 })) } });
11
+ }
12
+ test('S1-R01 off/shadow/prefer and rollback', () => {
13
+ const input = { prompt: '實作功能', tier: 'Unclassified' };
14
+ const forbidden = () => { throw new Error('must not invoke'); };
15
+ assert.deepEqual(selectTier(input, {}, forbidden), { tier: input.tier, diagnostic: null });
16
+ assert.equal(selectTier(input, { HARNESS_SYSTEM_ONE_MODE: 'off' }, forbidden).tier, input.tier);
17
+ for (const mode of ['shadow', 'prefer']) {
18
+ let captured;
19
+ const result = selectTier(input, { HARNESS_SYSTEM_ONE_MODE: mode }, req => { captured = req; return scorer()(req); });
20
+ assert.deepEqual(captured.options, TIER_OPTIONS);
21
+ assert.equal(result.tier, mode === 'prefer' ? 'Tier 2 (Standard Task)' : input.tier);
22
+ assert.equal(result.diagnostic.status, 'accepted');
23
+ assert.ok(!JSON.stringify(result.diagnostic).includes(input.prompt));
24
+ }
25
+ assert.equal(selectTier(input, { HARNESS_SYSTEM_ONE_MODE: 'unknown' }, forbidden).diagnostic.reason, 'invalid-mode');
26
+ });
27
+ test('S1-R02 explicit precedence, abstention and every failure leave fallback intact', () => {
28
+ const env = { HARNESS_SYSTEM_ONE_MODE: 'prefer' };
29
+ const input = { prompt: 'use fable architecture', tier: 'Tier 3 (Macro Task)' };
30
+ assert.equal(selectTier({ ...input, explicit: true }, env, scorer('tier1')).tier, input.tier);
31
+ for (const provider of [scorer('unclassified'), scorer('tier1', 'forms-v1'), () => ({ status: 'unavailable', reason: 'provider-timeout' }), () => ({ status: 'scored', response: null }), () => { throw new Error('secret'); }]) {
32
+ const result = selectTier(input, env, provider);
33
+ assert.equal(result.tier, input.tier);
34
+ assert.ok(!JSON.stringify(result).includes('secret'));
35
+ }
36
+ assert.equal(selectTier({ ...input, prompt: '' }, env, scorer()).diagnostic.reason, 'invalid-request');
37
+ });
38
+ test('S1-R03 real CLI/kernel off parity and shadow failure repeated', () => {
39
+ const script = path.join(root, 'harness-everything/scripts/kernel-router-core.js');
40
+ const run = mode => spawnSync(process.execPath, [script, 'deploy to production'], { cwd: root, encoding: 'utf8', env: { ...process.env, HARNESS_SYSTEM_ONE_MODE: mode, HARNESS_SYSTEM_ONE_CONFIG: '' } });
41
+ const off = run('off'); assert.equal(off.status, 0);
42
+ const baseline = run(''); assert.equal(off.stdout, baseline.stdout);
43
+ const one = run('shadow'); const two = run('shadow');
44
+ assert.equal(one.status, 0); assert.equal(one.stdout, two.stdout); assert.equal(one.stderr, two.stderr);
45
+ assert.match(one.stdout, /SYSTEM ONE.*provider-config/);
46
+ const parse = text => JSON.parse(text.match(/ROUTER WORKFLOW PLAN \(JSON\): (.*)/)[1]);
47
+ assert.deepEqual(parse(one.stdout), parse(off.stdout));
48
+ assert.equal(parse(one.stdout).actionGate.required, true);
49
+ });
50
+ test('S1-R04 integrated accepted route preserves policy and explicit model choice', () => {
51
+ const provider = require('../harness-everything/scripts/system-one/provider');
52
+ const original = provider.score; const log = console.log; const env = process.env.HARNESS_SYSTEM_ONE_MODE;
53
+ try {
54
+ process.env.HARNESS_SYSTEM_ONE_MODE = 'prefer'; console.log = () => {};
55
+ provider.score = scorer('tier1');
56
+ const { run } = require('../harness-everything/scripts/tier-router');
57
+ const risky = run('deploy to production; save lesson to memory');
58
+ assert.equal(risky.workflowPlan.actionGate.required, true);
59
+ assert.notEqual(risky.workflowPlan.memory.write, 'none');
60
+ const explicit = run('use fable-staged without subagents');
61
+ assert.notEqual(explicit.workflowPlan.strategy, 'direct-single');
62
+ assert.ok(explicit.workflowPlan.requiredInvariants.includes('replan-after-repeated-failure'));
63
+ const normal = run('unusual bounded wording');
64
+ assert.equal(normal.workflowPlan.tier, 'tier1');
65
+ } finally { provider.score = original; console.log = log; if (env === undefined) delete process.env.HARNESS_SYSTEM_ONE_MODE; else process.env.HARNESS_SYSTEM_ONE_MODE = env; }
66
+ });
67
+ test('S1-R05 structural floor: a scorer can raise but never lower a deterministic macro/multi-task tier', () => {
68
+ const env = { HARNESS_SYSTEM_ONE_MODE: 'prefer' };
69
+ const macro = { prompt: 'audit every skill in the repository', tier: 'Tier 3 (Macro Task)', floor: 'tier3' };
70
+ for (const id of ['tier1', 'tier2']) {
71
+ const result = selectTier(macro, env, scorer(id));
72
+ assert.equal(result.tier, macro.tier);
73
+ assert.equal(result.diagnostic.applied, false);
74
+ assert.equal(result.diagnostic.reason, 'structural-floor');
75
+ assert.equal(result.diagnostic.selectedId, id);
76
+ }
77
+ const multi = { prompt: 'x', tier: 'Tier 2 (Standard Task)', floor: 'tier2' };
78
+ assert.equal(selectTier(multi, env, scorer('tier1')).tier, multi.tier);
79
+ assert.equal(selectTier(multi, env, scorer('tier3')).tier, 'Tier 3 (Macro Task)');
80
+ assert.equal(selectTier({ ...multi, floor: null }, env, scorer('tier1')).tier, 'Tier 1 (Trivial)');
81
+ assert.equal(selectTier({ ...multi, floor: 'tier9' }, env, () => { throw new Error('must not invoke'); }).diagnostic.reason, 'invalid-request');
82
+
83
+ const provider = require('../harness-everything/scripts/system-one/provider');
84
+ const original = provider.score; const log = console.log; const mode = process.env.HARNESS_SYSTEM_ONE_MODE;
85
+ try {
86
+ console.log = () => {};
87
+ const { run } = require('../harness-everything/scripts/tier-router');
88
+ for (const prompt of ['audit every skill in the repository', 'Refactor the parser. Then update the tests and also the docs. Finally rerun CI.']) {
89
+ process.env.HARNESS_SYSTEM_ONE_MODE = 'off';
90
+ const lexical = run(prompt).workflowPlan;
91
+ process.env.HARNESS_SYSTEM_ONE_MODE = 'prefer'; provider.score = scorer('tier1');
92
+ assert.deepEqual(run(prompt).workflowPlan, lexical);
93
+ provider.score = original;
94
+ }
95
+ process.env.HARNESS_SYSTEM_ONE_MODE = 'prefer'; provider.score = scorer('tier1');
96
+ const plan = run('audit every skill in the repository').workflowPlan;
97
+ assert.equal(plan.tier, 'tier3');
98
+ assert.notEqual(plan.strategy, 'direct-single');
99
+ assert.equal(plan.verification.independent, true);
100
+ } finally { provider.score = original; console.log = log; if (mode === undefined) delete process.env.HARNESS_SYSTEM_ONE_MODE; else process.env.HARNESS_SYSTEM_ONE_MODE = mode; }
101
+ });
@@ -0,0 +1,222 @@
1
+ """Stdlib adapter tests: no claim of real checkpoint inference."""
2
+ import hashlib
3
+ import importlib.util
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import unittest
14
+
15
+ sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
16
+ path = Path(__file__).resolve().parents[1] / 'harness-everything/scripts/system-one/cua_adapter.py'
17
+ spec = importlib.util.spec_from_file_location('adapter', path)
18
+ adapter = importlib.util.module_from_spec(spec)
19
+ spec.loader.exec_module(adapter)
20
+
21
+
22
+ class AdapterTests(unittest.TestCase):
23
+ def test_artifact_hash_and_pickle_rejection(self):
24
+ with tempfile.TemporaryDirectory() as root:
25
+ weights = Path(root) / 'model.safetensors'
26
+ weights.write_bytes(b'synthetic-not-real-weights')
27
+ sidecar = weights.with_suffix('.json')
28
+ sidecar.write_text('{}', encoding='utf-8')
29
+ manifest = {'checkpoint': str(weights), 'weightsSha256': hashlib.sha256(weights.read_bytes()).hexdigest(), 'configSha256': hashlib.sha256(sidecar.read_bytes()).hexdigest()}
30
+ self.assertEqual(adapter.verify_artifacts(manifest), weights)
31
+ sidecar.write_text('{"changed":true}', encoding='utf-8')
32
+ with self.assertRaisesRegex(ValueError, 'artifact-hash'):
33
+ adapter.verify_artifacts(manifest)
34
+ manifest['checkpoint'] = str(weights.with_suffix('.pt'))
35
+ with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
36
+ adapter.verify_artifacts(manifest)
37
+
38
+ def test_byte_limits_no_truncation(self):
39
+ request = {'context': '中文', 'options': [{'text': 'abc'}, {'text': 'x'}]}
40
+ adapter.check_limits(request, {'context_tokens': 6, 'option_tokens': 3})
41
+ for config in [{'context_tokens': 5, 'option_tokens': 3}, {'context_tokens': 6, 'option_tokens': 2}]:
42
+ with self.assertRaisesRegex(ValueError, 'input-too-long'):
43
+ adapter.check_limits(request, config)
44
+
45
+ def test_source_revision_only_from_recorded_vcs_commit(self):
46
+ commit = 'b7f7e2d8714609853a29c7d049140bc46aec0954'
47
+ vcs = {'url': 'https://github.com/trycua/cua', 'vcs_info': {'vcs': 'git', 'commit_id': commit}, 'subdirectory': 'libs/cua-s1/python'}
48
+ self.assertEqual(adapter.source_revision(json.dumps(vcs)), commit)
49
+ for text in ['', 'not-json', '[]', json.dumps({'url': 'file:///src', 'dir_info': {'editable': True}}),
50
+ json.dumps({'vcs_info': {'commit_id': 'main'}}), json.dumps({'vcs_info': {'commit_id': commit.upper()}}), json.dumps({'vcs_info': []})]:
51
+ self.assertIsNone(adapter.source_revision(text))
52
+ self.assertIsNone(adapter.source_revision(None))
53
+
54
+ def test_provenance_shape_without_ml_dependency(self):
55
+ result = adapter.provenance()
56
+ self.assertEqual(set(result), {'schemaVersion', 'python', 'cuaS1', 'torch'})
57
+ self.assertEqual(set(result['python']), {'implementation', 'version'})
58
+ self.assertEqual(set(result['cuaS1']), {'distribution', 'version', 'sourceRevision'})
59
+ self.assertEqual(json.loads(json.dumps(result)), result)
60
+
61
+
62
+ def stub_factory(weights, manifest):
63
+ return (lambda request: [1.0] + [0.0] * (len(request['options']) - 1)), {'context_tokens': 8, 'option_tokens': 8}
64
+
65
+
66
+ def call(port, payload, raw=None):
67
+ with socket.create_connection(('127.0.0.1', port), timeout=5) as conn:
68
+ conn.sendall(raw if raw is not None else (json.dumps(payload) + '\n').encode('utf-8'))
69
+ conn.shutdown(socket.SHUT_WR)
70
+ data = b''.join(iter(lambda: conn.recv(65536), b''))
71
+ return json.loads(data)
72
+
73
+
74
+ class ResidentServerTests(unittest.TestCase):
75
+ def setUp(self):
76
+ self.root = tempfile.TemporaryDirectory()
77
+ weights = Path(self.root.name) / 'model.safetensors'
78
+ weights.write_bytes(b'synthetic-not-real-weights')
79
+ weights.with_suffix('.json').write_text('{}', encoding='utf-8')
80
+ self.weights = weights
81
+ self.manifest = {'checkpoint': str(weights), 'modelId': 'stub', 'revision': 'v1', 'domain': 'harness-routing-v1',
82
+ 'weightsSha256': hashlib.sha256(weights.read_bytes()).hexdigest(),
83
+ 'configSha256': hashlib.sha256(weights.with_suffix('.json').read_bytes()).hexdigest()}
84
+ self.state = Path(self.root.name) / 'state.json'
85
+ self.lock = Path(self.root.name) / 'state.starting'
86
+ self.lock.write_text('{}', encoding='utf-8')
87
+
88
+ def tearDown(self):
89
+ self.root.cleanup()
90
+
91
+ def start(self, idle=30):
92
+ thread = threading.Thread(target=adapter.serve, args=(self.manifest, self.state, self.lock),
93
+ kwargs={'scorer_factory': stub_factory, 'idle_timeout_s': idle}, daemon=True)
94
+ thread.start()
95
+ deadline = time.time() + 10
96
+ while not self.state.exists() and time.time() < deadline:
97
+ time.sleep(0.02)
98
+ self.assertTrue(self.state.exists())
99
+ return thread, json.loads(self.state.read_text(encoding='utf-8'))
100
+
101
+ def request(self, context='fix', options=('a', 'b')):
102
+ return {'schemaVersion': 1, 'task': 'tier', 'context': context, 'requestHash': 'a' * 64, 'catalogHash': 'b' * 64,
103
+ 'options': [{'id': f'o{i}', 'text': t} for i, t in enumerate(options)]}
104
+
105
+ def test_protocol_auth_limits_and_shutdown(self):
106
+ thread, state = self.start()
107
+ self.assertEqual(set(state), {'schemaVersion', 'pid', 'port', 'token', 'startedAt'})
108
+ self.assertRegex(state['token'], r'^[0-9a-f]{64}$')
109
+ self.assertEqual(state['pid'], os.getpid())
110
+ self.assertFalse(self.lock.exists())
111
+ if os.name == 'posix':
112
+ self.assertEqual(self.state.stat().st_mode & 0o777, 0o600)
113
+ token, port = state['token'], state['port']
114
+ self.assertEqual(call(port, {'token': token, 'op': 'ping'})['ok'], True)
115
+ self.assertEqual(call(port, {'token': '0' * 64, 'op': 'ping'}), {'ok': False, 'reason': 'unauthorized'})
116
+ self.assertEqual(call(port, {'op': 'ping'}), {'ok': False, 'reason': 'unauthorized'})
117
+ self.assertEqual(call(port, None, raw=b'not-json\n'), {'ok': False, 'reason': 'invalid-request'})
118
+ self.assertEqual(call(port, None, raw=b'x' * (2 * 1024 * 1024 + 2)), {'ok': False, 'reason': 'request-limit'})
119
+ self.assertEqual(call(port, {'token': token, 'op': 'unknown'}), {'ok': False, 'reason': 'invalid-request'})
120
+ reply = call(port, {'token': token, 'op': 'score', 'request': self.request()})
121
+ self.assertEqual(reply['ok'], True)
122
+ self.assertEqual(reply['response']['requestHash'], 'a' * 64)
123
+ self.assertEqual(reply['response']['model'], {'id': 'stub', 'revision': 'v1', 'domain': 'harness-routing-v1'})
124
+ self.assertEqual([s['probability'] for s in reply['response']['scores']], [1.0, 0.0])
125
+ self.assertEqual(call(port, {'token': token, 'op': 'score', 'request': self.request(context='123456789')}),
126
+ {'ok': False, 'reason': 'input-too-long'})
127
+ self.assertEqual(call(port, {'token': token, 'op': 'score', 'request': {'context': 'x'}}), {'ok': False, 'reason': 'invalid-request'})
128
+ self.assertEqual(call(port, {'token': token, 'op': 'shutdown'}), {'ok': True})
129
+ thread.join(5)
130
+ self.assertFalse(thread.is_alive())
131
+ self.assertFalse(self.state.exists())
132
+
133
+ def test_artifact_change_stops_server(self):
134
+ thread, state = self.start()
135
+ time.sleep(0.05)
136
+ self.weights.write_bytes(b'changed-weights-with-new-size')
137
+ reply = call(state['port'], {'token': state['token'], 'op': 'score', 'request': self.request()})
138
+ self.assertEqual(reply, {'ok': False, 'reason': 'artifact-changed'})
139
+ thread.join(5)
140
+ self.assertFalse(thread.is_alive())
141
+ self.assertFalse(self.state.exists())
142
+
143
+ def test_idle_timeout_exits_and_removes_state(self):
144
+ thread, _ = self.start(idle=0.3)
145
+ thread.join(5)
146
+ self.assertFalse(thread.is_alive())
147
+ self.assertFalse(self.state.exists())
148
+
149
+ @unittest.skipUnless(os.name == 'nt', 'Windows DACL')
150
+ def test_state_file_has_owner_only_explicit_dacl_on_windows(self):
151
+ thread, state = self.start()
152
+ # Drop the file path (it contains "C:\Users\...") and keep only the ACE text.
153
+ acl = subprocess.run(['icacls', str(self.state)], capture_output=True, text=True).stdout.replace(str(self.state), '')
154
+ self.assertIn(':(F)', acl)
155
+ for bad in ['(I)', 'Users', 'Everyone', 'Administrators', 'SYSTEM']:
156
+ self.assertNotIn(bad, acl)
157
+ call(state['port'], {'token': state['token'], 'op': 'shutdown'})
158
+ thread.join(5)
159
+
160
+ @unittest.skipUnless(os.name == 'nt', 'Windows DACL')
161
+ def test_explicit_foreign_aces_are_replaced_not_kept(self):
162
+ # CI runners create files with explicit (non-inherited) SYSTEM/Administrators/OWNER RIGHTS entries.
163
+ target = Path(self.root.name) / 'explicit.json'
164
+ target.write_text('{}', encoding='utf-8')
165
+ subprocess.run(['icacls', str(target), '/inheritance:d'], capture_output=True, check=True)
166
+ subprocess.run(['icacls', str(target), '/grant', '*S-1-5-32-544:F', '*S-1-5-18:F', '*S-1-3-4:F', '*S-1-5-32-545:R'], capture_output=True, check=True)
167
+ adapter._restrict_to_current_user(target)
168
+ acl = subprocess.run(['icacls', str(target)], capture_output=True, text=True).stdout.replace(str(target), '')
169
+ self.assertEqual(acl.count(':('), 1)
170
+ self.assertIn(':(F)', acl)
171
+
172
+ def test_slow_client_does_not_block_others_and_burst_is_served(self):
173
+ thread, state = self.start()
174
+ idle = socket.create_connection(('127.0.0.1', state['port']), timeout=5)
175
+ try:
176
+ began = time.monotonic()
177
+ self.assertEqual(call(state['port'], {'token': state['token'], 'op': 'ping'})['ok'], True)
178
+ self.assertLess(time.monotonic() - began, 0.5)
179
+ results = []
180
+ workers = [threading.Thread(target=lambda: results.append(call(state['port'], {'token': state['token'], 'op': 'ping'}))) for _ in range(32)]
181
+ for w in workers:
182
+ w.start()
183
+ for w in workers:
184
+ w.join(10)
185
+ self.assertEqual(len(results), 32)
186
+ self.assertTrue(all(r.get('ok') is True or r == {'ok': False, 'reason': 'busy'} for r in results))
187
+ self.assertGreaterEqual(sum(1 for r in results if r.get('ok') is True), 16)
188
+ finally:
189
+ idle.close()
190
+ call(state['port'], {'token': state['token'], 'op': 'shutdown'})
191
+ thread.join(5)
192
+
193
+ def test_server_exits_when_its_state_file_no_longer_names_it(self):
194
+ thread, _ = self.start()
195
+ self.state.write_text('{"corrupt": true}', encoding='utf-8')
196
+ thread.join(5)
197
+ self.assertFalse(thread.is_alive())
198
+ self.assertEqual(self.state.read_text(encoding='utf-8'), '{"corrupt": true}')
199
+
200
+ def test_rejects_requests_outside_phase0_structure(self):
201
+ thread, state = self.start()
202
+ token, port = state['token'], state['port']
203
+ many = self.request(options=tuple('x' for _ in range(257)))
204
+ extra = dict(self.request(), extra=1)
205
+ dup = self.request(); dup['options'][1]['id'] = dup['options'][0]['id']
206
+ bad_id = self.request(); bad_id['options'][0]['id'] = 'Bad ID'
207
+ wrong_version = dict(self.request(), schemaVersion=2)
208
+ for request in [many, extra, dup, bad_id, wrong_version]:
209
+ self.assertEqual(call(port, {'token': token, 'op': 'score', 'request': request}), {'ok': False, 'reason': 'invalid-request'})
210
+ self.assertEqual(call(port, {'token': token, 'op': 'score', 'request': self.request(options=tuple('x' for _ in range(256)))})['ok'], True)
211
+ call(port, {'token': token, 'op': 'shutdown'})
212
+ thread.join(5)
213
+
214
+ def test_startup_failure_is_recorded_in_lock(self):
215
+ self.manifest['weightsSha256'] = '0' * 64
216
+ adapter.serve(self.manifest, self.state, self.lock, scorer_factory=stub_factory, idle_timeout_s=1)
217
+ self.assertFalse(self.state.exists())
218
+ self.assertEqual(json.loads(self.lock.read_text(encoding='utf-8'))['failed'], 'artifact-hash')
219
+
220
+
221
+ if __name__ == '__main__':
222
+ unittest.main()
@@ -120,3 +120,17 @@ The OpenCode adapter uses the documented plugin API and has deterministic mechan
120
120
  The matrix records the official documentation reviewed for each platform. Important source families include [OpenAI plugin packaging](https://developers.openai.com/plugins/build/plugins), [OpenAI public submission](https://developers.openai.com/plugins/deploy/submission), [Codex skills](https://learn.chatgpt.com/docs/build-skills), [Codex hooks](https://learn.chatgpt.com/docs/hooks), [Claude skills](https://code.claude.com/docs/en/skills), [OpenCode skills](https://opencode.ai/docs/skills), [GitHub Copilot Agent Skills](https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-cloud-agent/add-skills), [Cursor skills](https://cursor.com/docs/skills), [Continue rules](https://docs.continue.dev/customize/rules), and [Hermes skills](https://hermes-agent.nousresearch.com/docs/user-guide/features/skills).
121
121
 
122
122
  When a platform behavior changes, update this page, `docs/platform-compatibility.json`, and every affected current-state surface in the same change. `npm run test:docs:capabilities` and the compatibility mechanism suite enforce the repository-side contract; they do not replace manual live-host evidence.
123
+ # Experimental System One routing
124
+
125
+ The shared tier router supports opt-in `HARNESS_SYSTEM_ONE_MODE=shadow|prefer`
126
+ with a local CUA-S1 provider manifest (`HARNESS_SYSTEM_ONE_CONFIG`). Default `off`
127
+ retains existing behavior; `prefer` never lowers a tier below the deterministic
128
+ structural floor. Canonical and packaged runtime copies use the same
129
+ contract; this establishes no new live-host capability. Python, PyTorch and a
130
+ compatible local checkpoint are optional external dependencies, not npm payloads;
131
+ the explicit `npm run system-one:install` sets them up and hooks never run it.
132
+ With `transport: "resident"`, an opted-in router hook may spawn one detached
133
+ loopback-only Python server per manifest; host survival of that process after
134
+ a hook exits is not live-verified.
135
+ Public Skills-only artifacts do not acquire lifecycle hooks from this feature.
136
+ See [System One routing](system-one-routing.md) for limits, rollback and evidence.
@@ -0,0 +1,271 @@
1
+ # System One routing migration
2
+
3
+ Status: experimental engineering; issue [#233](https://github.com/dyphn1/Harness-everything/issues/233).
4
+ The default router stays lexical until a Harness checkpoint passes the rollout gates.
5
+ Implement each phase in **documentation → failing tests → implementation** order.
6
+
7
+ ## Phase 0: scorer contract
8
+
9
+ System One scores a complete, caller-owned candidate list in one pass. It cannot
10
+ generate a workflow, execute actions, authorize tools, or write memory. Policy and
11
+ contract assembly remain deterministic. This boundary does not add execution locks.
12
+
13
+ `createRequest(task, context, options)` returns a version-1 request. Task names and
14
+ candidate IDs use lowercase letters, digits, dots, underscores or hyphens (1–80
15
+ characters). Context is nonempty UTF-8 (at most 65,536 bytes). There are 2–256
16
+ unique `{id, text}` options; text is nonempty and at most 4,096 bytes. Empty,
17
+ malformed, unknown-field and wrong-type inputs are errors. Input objects are not
18
+ mutated. Candidate order matters. `catalogHash` is SHA-256 of JSON-encoded
19
+ `{task, options}`; `requestHash` additionally binds the exact context. Neither
20
+ fingerprint grants permission or authenticates a model.
21
+
22
+ The provider response has exactly `schemaVersion`, `requestHash`, `catalogHash`,
23
+ `model`, and `scores`. Model has nonempty `id`, `revision`, and `domain` strings.
24
+ Scores have exactly `{id, probability}` in request order. All candidates occur
25
+ exactly once; probabilities are finite numbers in [0, 1], summing to one within
26
+ 1e-6. Unknown fields, stale request/catalog hashes, and version mismatches fail.
27
+
28
+ `decide(request, response, policy)` returns exactly `status`, `reason`,
29
+ `selectedId`, `confidence`, `margin`, and `model`. Status is `accepted`, `abstain`,
30
+ or `invalid-output`; nonaccepted results always have `selectedId: null`.
31
+ Policy requires a domain (default `harness-routing-v1`), minimum confidence
32
+ (default 0.9) and minimum margin (default 0.2). Invalid policy is a caller error.
33
+ Reject domain mismatch, tied winners, low confidence and low margin. A softmax
34
+ score is not calibrated correctness probability. Invalid output returns no raw
35
+ response, exception, or prompt. Identical inputs give identical decisions.
36
+
37
+ ## Phase 1: local provider
38
+
39
+ `provider.score(request, manifestPath)` uses a trusted host-configured manifest,
40
+ never a prompt-supplied executable. No shell or automatic download is used.
41
+ The manifest is version 1 with `python` (executable), `checkpoint` (absolute
42
+ `.safetensors` path), `weightsSha256`, `configSha256` (matching `.json` sidecar),
43
+ `modelId`, `revision`, `domain`, and optional `timeoutMs` (1–10000, default 2000).
44
+ All fields are required except the timeout; unknown fields are rejected. Hashes
45
+ must be lowercase SHA-256. Revision and domain are artifact-owner declarations,
46
+ not independently verified quality claims. The known `cua-ai/cua-s1-forms` ID
47
+ must use domain `forms-v1`. No pickle format or remote URL is accepted.
48
+
49
+ Install the optional `cua_s1` source in a dedicated Python 3.11–3.13 environment
50
+ from upstream revision `b7f7e2d8714609853a29c7d049140bc46aec0954`, using the
51
+ `libs/cua-s1/python` project. This npm package does not install Python, torch or
52
+ weights. Configure its Python executable in the manifest. A manifest alone does
53
+ not prove which Python package was installed, so `provider.provenance(manifestPath)`
54
+ runs `cua_adapter.py --provenance` with the configured interpreter. The probe
55
+ reads installed metadata only (no torch import, no checkpoint load) and reports
56
+ the Python implementation/version, the distribution providing `cua_s1`, its
57
+ version, the torch version, and the source revision. Only a PEP 610
58
+ `direct_url.json` VCS `commit_id` counts as a source revision, so install from a
59
+ VCS URL pinned to that commit (not an editable or local-directory install).
60
+ The status is `pinned` when it matches, `mismatch` otherwise, or `unavailable`
61
+ when no revision is recorded. Malformed probe output is `provider-json`.
62
+
63
+ `npm run system-one:install` (or `node harness-everything/scripts/system-one/install.js`)
64
+ performs these steps on explicit request; hooks never run it. It selects a
65
+ Python 3.11–3.13 interpreter (`--python` overrides; 3.14 is rejected by upstream),
66
+ creates `<dir>/venv`, installs CPU-only torch from the PyTorch CPU index, then
67
+ installs the pinned `cua_s1` Git URL. It downloads the `cua-ai/cua-s1-forms`
68
+ safetensors weights and JSON sidecar at Hugging Face revision
69
+ `f54adbf447f4ca6ec259f529ee3f2e3e09f8cc71`, verifies pinned sizes and SHA-256
70
+ before an atomic write (the pickle `.pt` is never fetched), and writes
71
+ `<dir>/manifest.json` with `timeoutMs: 10000`, `transport: "resident"` and
72
+ `idleTimeoutMs: 1800000`. The default `<dir>` is
73
+ `~/.agents/harness-everything/system-one`; `--dir` takes an absolute path and
74
+ `--dry-run` prints the plan without changes. Acceptance requires a `pinned`
75
+ provenance probe and one real warm CPU inference through a resident server that
76
+ the installer starts and then stops; otherwise the exit code is 1. Child-process
77
+ output goes to stderr; stdout carries only the JSON report.
78
+ Torch/numpy/safetensors versions resolve at install time and are recorded by
79
+ the probe. The installer does not change the router mode: it prints
80
+ `HARNESS_SYSTEM_ONE_MODE=shadow` and the manifest path for the host
81
+ environment. This checkpoint declares domain `forms-v1`, so shadow diagnostics
82
+ report `domain-mismatch` and prefer never applies it. It also rejects context
83
+ above its 224-byte limit (`provider-exit`), so installing it proves the local
84
+ inference path only, not Harness routing quality.
85
+
86
+ The adapter verifies both files before `load_checkpoint(..., 'cpu')`, sets one
87
+ torch thread and deterministic inference, calls the upstream collator/model,
88
+ and returns a probability for every option. It rejects context or option text
89
+ that exceeds the loaded byte limits before collation (no silent truncation).
90
+ No prompts or model values are written to disk or echoed in error messages.
91
+
92
+ The Node transport has a hard timeout and a 1 MiB stdout/stderr bound; it kills
93
+ the direct child on timeout. It starts one short-lived Python process per score
94
+ request. This is the default `oneshot` transport, not a warm server; see the
95
+ resident provider below.
96
+ The process cannot execute actions and is not given a CUA driver. Failures return
97
+ `{status: 'unavailable', reason}` with a bounded reason code; malformed score
98
+ responses are checked by Phase 0. Transport fixtures prove IPC and failure
99
+ handling only. Real checkpoint inference and measured CPU latency remain a
100
+ separate gate, with explicit unavailable evidence if dependencies are absent.
101
+
102
+ ## Resident provider (Phase 4 prerequisite)
103
+
104
+ The one-shot bridge pays Python start, `import torch` and checkpoint load on every
105
+ call (measured ≈5 s on CPU); warm in-process inference is a few milliseconds. The
106
+ manifest may set `transport: "resident"` (default `"oneshot"`) and optional
107
+ `idleTimeoutMs` (60000–14400000, default 1800000) to keep one verified model in
108
+ memory. Other manifest rules are unchanged; the timeout remains one-shot only.
109
+
110
+ **Lifecycle.** A resident-mode score never blocks on model loading. If no live
111
+ server exists, the Node provider creates a start lock with exclusive-create,
112
+ spawns `cua_adapter.py --serve` detached with the configured Python (no shell),
113
+ and returns `unavailable/provider-starting`, so the lexical route is used for
114
+ that prompt. Concurrent callers seeing a lock younger than 60 s do not spawn
115
+ again. The server verifies artifact hashes before `load_checkpoint`, writes its
116
+ state file atomically, then removes the lock. A startup failure writes a bounded
117
+ reason into the lock and exits; callers report `provider-unavailable` without
118
+ respawning until the lock is 60 s old. An executable that cannot be spawned at
119
+ all is detected synchronously (no child PID) and recorded as `spawn-failed` the
120
+ same way. The server exits after `idleTimeoutMs` without requests, on
121
+ `shutdown`, when either checkpoint file's size or modification time changes
122
+ (`artifact-changed`), or as soon as its state file no longer names its PID and
123
+ token (replaced, corrupted or deleted), so an undiscoverable server never
124
+ lingers as an orphan. It deletes only a state file that still names it.
125
+
126
+ **Files.** State and lock live beside the manifest as
127
+ `system-one-resident-<digest>.json` / `.starting`, where `<digest>` is the first
128
+ 16 hex digits of SHA-256 of the parsed manifest re-serialized with `JSON.stringify`
129
+ (file key order). Editing the manifest
130
+ therefore selects a new server; the old one exits when idle. The state file has
131
+ exactly `schemaVersion: 1`, `pid`, `port`, `token` (64 hex), and `startedAt`, and
132
+ is created with mode 0600; on Windows the file instead receives an explicit
133
+ DACL with inheritance removed and a single full-control entry for the current
134
+ user's SID before the token is written. The manifest directory must still be
135
+ writable only by that user: whoever can replace files there can redirect the
136
+ client, and whoever can edit the manifest chooses the executable.
137
+
138
+ **Protocol.** The server binds only `127.0.0.1` on an ephemeral port and handles
139
+ one request per connection: one newline-terminated JSON object of at most 2 MiB
140
+ with `token`, `op` (`score`, `ping`, `shutdown`) and, for `score`, a request with
141
+ the exact Phase 0 structure (fields, lowercase IDs, unique options, 2–256
142
+ options, 64-hex fingerprints). Connections are served concurrently, up to 64, each
143
+ with a 1 s read deadline; beyond that the reply is `busy`. Inference itself is
144
+ serialized, so a silent or slow client cannot delay other callers. Tokens are compared in constant time; a mismatch returns
145
+ `{ok: false, reason: "unauthorized"}`. `score` applies the same byte limits
146
+ (no truncation) and returns `{ok: true, response}` in the Phase 0 response
147
+ format, which Phase 0 validation still checks. Any other failure returns
148
+ `{ok: false, reason}` with a bounded code; no prompt, traceback, path or score is
149
+ echoed in errors. The server never executes actions and is not given a driver.
150
+
151
+ **Client.** The router API is synchronous, so the client performs one socket
152
+ round trip on a worker thread and waits with `Atomics.wait` (1000 ms deadline).
153
+ Results map to the existing reasons: timeout → `provider-timeout` (no respawn);
154
+ refused connection or dead PID → stale state removed and a new start
155
+ (`provider-starting`); `unauthorized` → `provider-unavailable`; any other
156
+ server-declined request → `provider-exit`; malformed replies → `provider-json`.
157
+
158
+ **Operators.** `node harness-everything/scripts/system-one/resident.js
159
+ start|status|stop <absolute manifest>` controls a server explicitly; `start`
160
+ waits up to 60 s for readiness. The evaluation CLI waits for readiness before
161
+ measuring, so resident runs are recorded with `coldStart: false`. The installer
162
+ writes `transport: "resident"`, verifies one resident score, and stops the server
163
+ it started. Repository tests use a stub scorer behind the real server/protocol
164
+ code; they prove the mechanism, not host survival of detached processes or model
165
+ quality. Those require retained evidence.
166
+
167
+ ## Phase 2: tier integration and rollback
168
+
169
+ Set `HARNESS_SYSTEM_ONE_MODE=off|shadow|prefer` in the host environment. Default
170
+ is `off`: no provider process, diagnostic, or contract change. Supply an absolute
171
+ `HARNESS_SYSTEM_ONE_CONFIG` path to the Phase 1 manifest for the other modes.
172
+ An unknown mode reports `invalid-mode` and leaves the lexical result unchanged.
173
+ Shadow records the decision but never changes the route. Prefer replaces only
174
+ the recommended tier when a valid `harness-routing-v1` result passes Phase 0
175
+ thresholds. The full fixed tier catalog (tier1, tier2, tier3, unclassified) is
176
+ always scored; it is never filtered using lexical matches. `unclassified` means
177
+ abstention and keeps the existing route. Explicit strategy/model requests keep
178
+ precedence and prevent model tier replacement. Set mode back to `off` to roll back.
179
+
180
+ Prefer can raise a tier but never lower it below the deterministic structural
181
+ floor: a macro-scope signal sets floor `tier3`, and multi-task, multi-sentence
182
+ structure (other than a trivial docs edit) sets floor `tier2`. An accepted result
183
+ below the floor is not applied and reports `structural-floor`, so repository-wide
184
+ work keeps its Tier 3 strategy, independent verification and worktree
185
+ invariants. Tier-3 keywords are lexical guesses, not structural floors. The
186
+ policy assembler still consumes the original structural and risk signals.
187
+ Safety, explicit prohibitions, memory ownership, and verification are not model
188
+ outputs. This phase does not yet replace guide matching, dynamic
189
+ skill triggers, fact-audit reminders, or the structural workflow signals.
190
+ The same scorer API can evaluate caller-supplied text options; additional routing
191
+ surfaces require their own catalog and held-out evidence before integration.
192
+
193
+ When enabled, a single `SYSTEM ONE` JSON diagnostic reports mode, status, reason,
194
+ selected candidate, model identity, confidence and margin; it omits prompt text,
195
+ score vectors and artifact paths. The existing router contract schema is unchanged.
196
+ Kernel/packaged entry points inherit these host environment variables. Prompts
197
+ and hook payload fields cannot set model configuration or launch executables.
198
+ Repository tests establish mechanism/package evidence only; actual host loading
199
+ and semantic quality remain unverified until retained sessions demonstrate them.
200
+
201
+ ## Phase 3: corpus and paired evaluation
202
+
203
+ Use `node scripts/evaluate-system-one.js corpus.json /absolute/manifest.json report.json`.
204
+ The corpus is `{schemaVersion: 1, cases: [...]}`. Each case has exactly `id`,
205
+ `family`, `split` (`train|validation|holdout`), `language` (`en|zh-TW`), `source`
206
+ (human-reviewed provenance, not baseline-generated gold), `reviewed` (boolean),
207
+ `request` (Phase 0 tier request), and `gold` (candidate ID, or null for abstention).
208
+ The complete fixed tier catalog must match. IDs and request hashes are unique;
209
+ no family may span splits. Evaluation uses only holdout, never training labels.
210
+ The committed seed corpus is a mechanism fixture, not an independently reviewed
211
+ holdout. Expand and review it separately before making quality claims.
212
+
213
+ The CLI runs the real lexical baseline and the configured provider twice per
214
+ holdout case. Records contain IDs, baseline prediction, decision, model identity,
215
+ the catalog-order probability vector (`scores`; null for unavailable or invalid
216
+ output), latency, and `coldStart: true`; they do not copy prompts into the
217
+ report. A scored run's confidence and margin must match its vector. Gold
218
+ `unclassified` is represented by null. Nonaccepted model results also predict
219
+ null. The evaluator rejects missing, duplicate or unknown cases, unsupported
220
+ predictions, malformed measurements, and inconsistent model identities. Reruns
221
+ compare the full decision, model identity and score vector, but not measured
222
+ latency: equal top-2 values with a reordered tail still disagree.
223
+ No normalization is permitted for candidate IDs or model revision.
224
+
225
+ Report both baseline and model accuracy/macro-F1, model coverage, accepted
226
+ precision/error rate, abstention, repeated-decision agreement, and separate
227
+ cold/warm p95. Zero accepted decisions has null precision and never passes.
228
+ Unavailable responses remain abstentions and count against coverage. Null gold
229
+ is included in macro-F1's class set; the four catalog labels are always included
230
+ even when unobserved, preventing favorable per-run class selection.
231
+
232
+ The evaluator emits explicit rollout checks, not an automatic deployment. It
233
+ requires reviewed holdout counts, semantic/coverage thresholds, repeatability,
234
+ warm measurements, a `pinned` source revision, plus independently retained
235
+ policy and live-host evidence. The report's `evidence.source` keeps the probe
236
+ result (including `mismatch` or `unavailable`) and `environment.python`.
237
+ The latter evidence is not supplied by this offline runner, so it always reports
238
+ those gates pending. With the one-shot adapter, all latency is cold and the warm
239
+ gate also remains pending. Exporting a report never changes router defaults.
240
+
241
+ ## Model suitability
242
+
243
+ The [CUA-S1-FORMS model card](https://huggingface.co/cua-ai/cua-s1-forms)
244
+ describes a form-specific option scorer, with English-centric training and short
245
+ byte contexts. These results do not establish Harness routing quality. Its
246
+ checkpoint is an experimental baseline, not a production routing checkpoint.
247
+ The [upstream source](https://github.com/trycua/cua/tree/main/libs/cua-s1)
248
+ has a source-only release description; source and checkpoint provenance/licenses
249
+ must be checked independently. Do not infer a published Python wheel or use an
250
+ unversioned download during a prompt hook.
251
+
252
+ ## Planned phases
253
+
254
+ | Phase | Deliverable | Acceptance evidence |
255
+ | --- | --- | --- |
256
+ | 0 | Versioned option-scoring boundary | Complete positive/negative contract tests |
257
+ | 1 | Local CUA-S1 adapter | Bounded subprocess, artifact validation, explicit failures |
258
+ | 2 | Router integration | Off/shadow/prefer, existing policy invariants, rollback |
259
+ | 3 | Corpus and paired evaluator | Leakage checks, coverage/error metrics, repeatability |
260
+ | 4 | Harness training and rollout | Real checkpoint, reviewed holdout, measured host results |
261
+
262
+ ## Rollout gates
263
+
264
+ Phase 4 requires a separately reviewed, family-disjoint holdout of at least 200
265
+ cases, at least 50 each in English and Traditional Chinese. Accepted precision
266
+ must be ≥98%, coverage ≥80%, and macro-F1 at least the lexical baseline.
267
+ Policy invariants must remain intact in every case; repeat decisions twice with
268
+ 100% agreement. Record checkpoint/source hashes, CPU, OS, runtime, thread count,
269
+ cold latency and warm p95 (target ≤100ms). Synthetic fixtures and mock providers
270
+ only validate mechanisms. They cannot satisfy these model/behavior gates.
271
+ Until measured evidence passes, retain the default, fallback and this open issue.
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.19.1
7
+ version: 0.22.0
8
8
  ---
9
9
 
10
10
  # Harness Everything