harness-everything 0.50.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/ci.yml +23 -0
- package/CHANGELOG.md +174 -115
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
- package/ci/mechanism-2am-observations-session-import.test.js +4 -1
- package/ci/mechanism-34-observations.test.js +127 -23
- package/ci/mechanism-349-ci-change-scope.test.js +260 -0
- package/ci/mechanism-handoff-file.test.js +121 -0
- package/ci/mechanism-prb-outline-review.test.js +783 -107
- package/ci/mechanism-system-one-contract.test.js +9 -2
- package/ci/mechanism-system-one-curves.test.js +206 -0
- package/ci/mechanism-system-one-cycle.test.js +585 -0
- package/ci/mechanism-system-one-evaluation.test.js +32 -5
- package/ci/mechanism-system-one-handoff-input.test.js +208 -0
- package/ci/mechanism-system-one-install.test.js +202 -77
- package/ci/mechanism-system-one-live.test.js +361 -0
- package/ci/mechanism-system-one-relevance.test.js +11 -1
- package/ci/mechanism-system-one-train.test.js +136 -53
- package/ci/release-unreleased-heading.test.js +24 -0
- package/ci/system-one-adapter-test.py +331 -0
- package/ci/system-one-train-test.py +116 -24
- package/docs/adr/EVID-001.md +123 -0
- package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
- package/docs/doc-workflow-reconciliation.md +29 -16
- package/docs/governed-index.md +2 -0
- package/docs/platform-capabilities.md +2 -0
- package/docs/routing.md +2 -2
- package/docs/system-one-cycle.md +68 -0
- package/docs/system-one-observations.md +9 -8
- package/docs/system-one-routing.md +163 -115
- package/docs/system-one-suggestion-gates.md +6 -8
- package/docs/system-one-training.md +44 -7
- package/docs/workflow-runtime.md +19 -0
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/kernel-router.js +2 -1
- package/harness-everything/scripts/system-one/contract.js +19 -15
- package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/harness-everything/scripts/system-one/install.js +281 -113
- package/harness-everything/scripts/system-one/manifest.js +58 -0
- package/harness-everything/scripts/system-one/provider.js +96 -2
- package/harness-everything/scripts/system-one/resident.js +47 -1
- package/harness-everything/scripts/system-one/router.js +80 -1
- package/harness-everything/scripts/tier-router.js +21 -6
- package/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
- package/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
- package/hooks/scripts/lib/observations.js +43 -4
- package/hooks/scripts/lib/workflow-obligations.js +8 -4
- package/hooks/scripts/state-persist.js +26 -7
- package/hooks/scripts/w6-state-operations.js +239 -0
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +2 -2
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
- package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +8 -4
- package/plugins/harness-everything/hooks/scripts/state-persist.js +26 -7
- package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +239 -0
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/scripts/handoff-file.js +223 -0
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
- package/sbom.cdx.json +7 -7
- package/scripts/ci-change-scope.js +59 -0
- package/scripts/handoff-file.js +223 -0
- package/scripts/sync-openai-plugin.js +4 -0
- package/scripts/system-one-calibrate.js +108 -41
- package/scripts/system-one-curves.js +332 -0
- package/scripts/system-one-cycle/adjudication-input.js +65 -0
- package/scripts/system-one-cycle/build.js +165 -0
- package/scripts/system-one-cycle/collect.js +50 -0
- package/scripts/system-one-cycle/common.js +137 -0
- package/scripts/system-one-cycle/engines.js +62 -0
- package/scripts/system-one-cycle/evaluate.js +70 -0
- package/scripts/system-one-cycle/judge.js +106 -0
- package/scripts/system-one-cycle/label.js +59 -0
- package/scripts/system-one-cycle/package.js +173 -0
- package/scripts/system-one-cycle/score.py +111 -0
- package/scripts/system-one-cycle/train.js +136 -0
- package/scripts/system-one-cycle.js +131 -0
- package/scripts/system-one-observations-export.js +29 -6
- package/scripts/system-one-observations-review.js +4 -5
- package/scripts/system-one-train.py +117 -61
|
@@ -11,6 +11,9 @@ import tempfile
|
|
|
11
11
|
import threading
|
|
12
12
|
import time
|
|
13
13
|
import unittest
|
|
14
|
+
from contextlib import nullcontext
|
|
15
|
+
from types import ModuleType
|
|
16
|
+
from unittest.mock import patch
|
|
14
17
|
|
|
15
18
|
sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
|
|
16
19
|
path = Path(__file__).resolve().parents[1] / 'harness-everything/scripts/system-one/cua_adapter.py'
|
|
@@ -18,8 +21,336 @@ spec = importlib.util.spec_from_file_location('adapter', path)
|
|
|
18
21
|
adapter = importlib.util.module_from_spec(spec)
|
|
19
22
|
spec.loader.exec_module(adapter)
|
|
20
23
|
|
|
24
|
+
ACTIVE_OPTIONS = {
|
|
25
|
+
'validity': ['invalid'],
|
|
26
|
+
'intent': ['explain', 'discuss', 'git', 'fix', 'edit', 'feature', 'refactor', 'review', 'test', 'docs', 'plan', 'investigate'],
|
|
27
|
+
'tier': ['tier1', 'tier2', 'tier3'],
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def write_active_fixture(root):
|
|
32
|
+
thresholds = {
|
|
33
|
+
'validity': {'invalid': 0.55},
|
|
34
|
+
'intent': {key: 0.55 for key in ACTIVE_OPTIONS['intent']},
|
|
35
|
+
'tier': {key: 0.55 for key in ACTIVE_OPTIONS['tier']},
|
|
36
|
+
}
|
|
37
|
+
thresholds['intent']['fix'] = 1
|
|
38
|
+
version_dir = Path(root) / 'v1'
|
|
39
|
+
version_dir.mkdir()
|
|
40
|
+
stages = {}
|
|
41
|
+
for stage in ('validity', 'intent', 'tier'):
|
|
42
|
+
weights = f'{stage}-weights.safetensors'
|
|
43
|
+
config = f'{stage}-config.json'
|
|
44
|
+
weight_bytes = f'{stage}-weights'.encode()
|
|
45
|
+
config_bytes = json.dumps({'stage': stage}).encode()
|
|
46
|
+
(version_dir / weights).write_bytes(weight_bytes)
|
|
47
|
+
(version_dir / config).write_bytes(config_bytes)
|
|
48
|
+
stages[stage] = {
|
|
49
|
+
'weights': weights, 'config': config,
|
|
50
|
+
'sha256': hashlib.sha256(weight_bytes).hexdigest(),
|
|
51
|
+
'options': ACTIVE_OPTIONS[stage], 'thresholds': thresholds[stage],
|
|
52
|
+
}
|
|
53
|
+
if stage == 'intent':
|
|
54
|
+
stages[stage]['referenceOnly'] = ['fix']
|
|
55
|
+
(version_dir / 'manifest.json').write_text(json.dumps({
|
|
56
|
+
'schemaVersion': 1, 'version': 'v1', 'createdAt': '2026-11-14T00:00:00Z',
|
|
57
|
+
'stages': stages, 'evaluation': None,
|
|
58
|
+
}), encoding='utf-8')
|
|
59
|
+
pointer = Path(root) / 'active.json'
|
|
60
|
+
pointer.write_text(json.dumps({
|
|
61
|
+
'schemaVersion': 1, 'version': 'v1', 'dir': str(version_dir),
|
|
62
|
+
'previous': None, 'activatedAt': '2026-11-14T00:00:00Z',
|
|
63
|
+
}), encoding='utf-8')
|
|
64
|
+
return pointer
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RequestSocket:
|
|
68
|
+
def __init__(self, message):
|
|
69
|
+
self.data = (json.dumps(message) + '\n').encode()
|
|
70
|
+
|
|
71
|
+
def recv(self, size):
|
|
72
|
+
result, self.data = self.data[:size], self.data[size:]
|
|
73
|
+
return result
|
|
74
|
+
|
|
21
75
|
|
|
22
76
|
class AdapterTests(unittest.TestCase):
|
|
77
|
+
def test_active_pointer_loads_all_stage_checkpoints_from_separate_files(self):
|
|
78
|
+
with tempfile.TemporaryDirectory() as root:
|
|
79
|
+
pointer = write_active_fixture(root)
|
|
80
|
+
loaded = []
|
|
81
|
+
|
|
82
|
+
def fake_loader(weights, manifest):
|
|
83
|
+
loaded.append((weights.name, Path(manifest['config']).name))
|
|
84
|
+
return (lambda _request: []), {'context_tokens': 8, 'option_tokens': 8}
|
|
85
|
+
|
|
86
|
+
bundle = adapter.load_active_bundle(pointer, scorer_loader=fake_loader)
|
|
87
|
+
self.assertEqual(bundle['version'], 'v1')
|
|
88
|
+
self.assertEqual(list(bundle['scorers']), ['validity', 'intent', 'tier'])
|
|
89
|
+
self.assertEqual(bundle['scorers']['intent']['referenceOnly'], ['fix'])
|
|
90
|
+
self.assertEqual(loaded, [(f'{stage}-weights.safetensors', f'{stage}-config.json') for stage in ('validity', 'intent', 'tier')])
|
|
91
|
+
|
|
92
|
+
def test_active_manifest_uses_shared_reference_only_validation(self):
|
|
93
|
+
with tempfile.TemporaryDirectory() as root:
|
|
94
|
+
pointer = write_active_fixture(root)
|
|
95
|
+
manifest_path = pointer.parent / 'v1' / 'manifest.json'
|
|
96
|
+
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
|
97
|
+
manifest['stages']['intent']['thresholds']['fix'] = 0.99
|
|
98
|
+
manifest_path.write_text(json.dumps(manifest), encoding='utf-8')
|
|
99
|
+
with self.assertRaisesRegex(ValueError, 'active-manifest'):
|
|
100
|
+
adapter.load_active_bundle(pointer, scorer_loader=lambda *_: (lambda _request: [] , {}))
|
|
101
|
+
|
|
102
|
+
def test_active_stage_protocol_scores_independent_values_and_checks_catalog(self):
|
|
103
|
+
with tempfile.TemporaryDirectory() as root:
|
|
104
|
+
pointer = write_active_fixture(root)
|
|
105
|
+
|
|
106
|
+
def fake_loader(_weights, _manifest):
|
|
107
|
+
return (lambda request: [0.2, 0.76, 0.9, 0.1][:len(request['options'])]), {'context_tokens': 64, 'option_tokens': 64}
|
|
108
|
+
|
|
109
|
+
bundle = adapter.load_active_bundle(pointer, scorer_loader=fake_loader)
|
|
110
|
+
token = 'a' * 64
|
|
111
|
+
|
|
112
|
+
def request(ids):
|
|
113
|
+
return {
|
|
114
|
+
'schemaVersion': 1, 'task': 'tier', 'context': 'fixture',
|
|
115
|
+
'options': [{'id': option, 'text': option} for option in ids],
|
|
116
|
+
'catalogHash': 'b' * 64, 'requestHash': 'c' * 64,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
def handle(ids):
|
|
120
|
+
message = {'token': token, 'op': 'score', 'stage': 'tier', 'request': request(ids)}
|
|
121
|
+
score = lambda req, stage: bundle['scorers'][stage]['score'](req)
|
|
122
|
+
return adapter._handle(RequestSocket(message), token, bundle['manifest'], None, bundle['stamp'], score, None, bundle)
|
|
123
|
+
|
|
124
|
+
reply, stop = handle(ACTIVE_OPTIONS['tier'])
|
|
125
|
+
self.assertFalse(stop)
|
|
126
|
+
self.assertTrue(reply['ok'])
|
|
127
|
+
probabilities = [score['probability'] for score in reply['response']['scores']]
|
|
128
|
+
self.assertEqual(probabilities, [0.2, 0.76, 0.9])
|
|
129
|
+
self.assertGreater(sum(probabilities), 1)
|
|
130
|
+
bad, stop = handle(['tier1', 'tier2'])
|
|
131
|
+
self.assertFalse(stop)
|
|
132
|
+
self.assertEqual(bad, {'ok': False, 'reason': 'invalid-request'})
|
|
133
|
+
|
|
134
|
+
def test_load_scorer_uses_independent_sigmoid_probabilities(self):
|
|
135
|
+
class Logits:
|
|
136
|
+
def sigmoid(self):
|
|
137
|
+
class Probabilities:
|
|
138
|
+
def __getitem__(self, _index):
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
def tolist(self):
|
|
142
|
+
return [0.91, 0.28]
|
|
143
|
+
|
|
144
|
+
return Probabilities()
|
|
145
|
+
|
|
146
|
+
def softmax(self, *_args):
|
|
147
|
+
raise AssertionError('softmax is not the per-option readout')
|
|
148
|
+
|
|
149
|
+
class FakeModel:
|
|
150
|
+
def __call__(self, _batch):
|
|
151
|
+
return Logits()
|
|
152
|
+
|
|
153
|
+
torch = ModuleType('torch')
|
|
154
|
+
torch.set_num_threads = lambda _count: None
|
|
155
|
+
torch.use_deterministic_algorithms = lambda _enabled: None
|
|
156
|
+
torch.inference_mode = nullcontext
|
|
157
|
+
cua_s1 = ModuleType('cua_s1')
|
|
158
|
+
model = ModuleType('cua_s1.model')
|
|
159
|
+
model.ChoiceExample = lambda **values: values
|
|
160
|
+
model.load_checkpoint = lambda _weights, _device: (FakeModel(), lambda examples: examples, {'context_tokens': 10, 'option_tokens': 10})
|
|
161
|
+
with tempfile.TemporaryDirectory() as root:
|
|
162
|
+
weights = Path(root) / 'unused.safetensors'
|
|
163
|
+
weights.with_suffix('.json').write_text(json.dumps({'metadata': {
|
|
164
|
+
'domain': 'harness-routing-v1', 'task': 'tier', 'loss': 'binary_cross_entropy',
|
|
165
|
+
}}), encoding='utf-8')
|
|
166
|
+
manifest = {'modelId': 'fixture-v1', 'domain': 'harness-routing-v1'}
|
|
167
|
+
with patch.dict(sys.modules, {'torch': torch, 'cua_s1': cua_s1, 'cua_s1.model': model}):
|
|
168
|
+
score, _config = adapter.load_scorer(weights, manifest)
|
|
169
|
+
self.assertEqual(score({'task': 'tier', 'context': 'fixture', 'options': [{'text': 'a'}, {'text': 'b'}]}), [0.91, 0.28])
|
|
170
|
+
|
|
171
|
+
def test_unknown_checkpoint_semantics_remain_unavailable(self):
|
|
172
|
+
with tempfile.TemporaryDirectory() as root:
|
|
173
|
+
weights = Path(root) / 'model.safetensors'
|
|
174
|
+
weights.with_suffix('.json').write_text(json.dumps({'metadata': {
|
|
175
|
+
'domain': 'harness-routing-v1', 'task': 'tier', 'loss': 'cross_entropy',
|
|
176
|
+
}}), encoding='utf-8')
|
|
177
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-semantics'):
|
|
178
|
+
adapter.load_scorer(weights, {'modelId': 'unknown-v1', 'domain': 'harness-routing-v1'})
|
|
179
|
+
|
|
180
|
+
def test_supported_forms_checkpoint_semantics_remain_categorical(self):
|
|
181
|
+
with tempfile.TemporaryDirectory() as root:
|
|
182
|
+
weights = Path(root) / 'model.safetensors'
|
|
183
|
+
weights.with_suffix('.json').write_text(json.dumps({'metadata': {
|
|
184
|
+
'domain': 'forms-v1', 'loss': 'cross_entropy',
|
|
185
|
+
}}), encoding='utf-8')
|
|
186
|
+
self.assertEqual(adapter._score_semantics(weights, {
|
|
187
|
+
'modelId': 'cua-ai/cua-s1-forms', 'domain': 'forms-v1',
|
|
188
|
+
}), ('categorical', 'tier'))
|
|
189
|
+
|
|
190
|
+
def test_staged_checkpoint_readout_is_independent_in_oneshot_and_active_bundle(self):
|
|
191
|
+
try:
|
|
192
|
+
import torch
|
|
193
|
+
import torch.nn.functional as functional
|
|
194
|
+
from cua_s1.model import ChoiceExample, make_system, save_checkpoint
|
|
195
|
+
except ImportError as exc:
|
|
196
|
+
self.skipTest(f'real CUA checkpoint dependencies unavailable: {exc}')
|
|
197
|
+
|
|
198
|
+
stage_options = {
|
|
199
|
+
'validity': [('invalid', 'The request is invalid.')],
|
|
200
|
+
'intent': [('explain', 'Explain'), ('fix', 'Fix')],
|
|
201
|
+
'tier': [('tier1', 'Small change'), ('tier2', 'Iterative change'), ('tier3', 'Macro change')],
|
|
202
|
+
}
|
|
203
|
+
torch.set_num_threads(1)
|
|
204
|
+
torch.use_deterministic_algorithms(True)
|
|
205
|
+
with tempfile.TemporaryDirectory(prefix='harness-s1-stages-') as root:
|
|
206
|
+
root = Path(root)
|
|
207
|
+
version_dir = root / 'v1'
|
|
208
|
+
version_dir.mkdir()
|
|
209
|
+
stage_manifests, one_shot_scores = {}, {}
|
|
210
|
+
for index, (stage, options) in enumerate(stage_options.items()):
|
|
211
|
+
torch.manual_seed(20261115 + index)
|
|
212
|
+
config = {'encoder': 'tiny', 'width': 8, 'rank': 8, 'context_tokens': 64, 'option_tokens': 64}
|
|
213
|
+
model, collator = make_system(config, 'cpu')
|
|
214
|
+
example = ChoiceExample(context='fixture context', options=tuple(text for _, text in options), label=0)
|
|
215
|
+
batch = collator([example])
|
|
216
|
+
target = torch.zeros((1, len(options)), dtype=torch.float32)
|
|
217
|
+
target[0, 0] = 1.0
|
|
218
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01, weight_decay=0.0)
|
|
219
|
+
for _ in range(2):
|
|
220
|
+
model.train()
|
|
221
|
+
optimizer.zero_grad()
|
|
222
|
+
loss = functional.binary_cross_entropy_with_logits(model(batch), target)
|
|
223
|
+
loss.backward()
|
|
224
|
+
optimizer.step()
|
|
225
|
+
model.eval()
|
|
226
|
+
weights, config_path = save_checkpoint(version_dir / f'{stage}.safetensors', model, config, {
|
|
227
|
+
'domain': 'harness-routing-v1', 'task': stage, 'loss': 'binary_cross_entropy',
|
|
228
|
+
})
|
|
229
|
+
option_rows = [{'id': option_id, 'text': text} for option_id, text in options]
|
|
230
|
+
request = {'schemaVersion': 1, 'task': stage, 'context': 'fixture context', 'options': option_rows,
|
|
231
|
+
'catalogHash': 'a' * 64, 'requestHash': 'b' * 64}
|
|
232
|
+
manifest = {
|
|
233
|
+
'checkpoint': str(weights), 'weightsSha256': hashlib.sha256(weights.read_bytes()).hexdigest(),
|
|
234
|
+
'configSha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
|
|
235
|
+
'modelId': f'fixture-{stage}', 'revision': 'v1', 'domain': 'harness-routing-v1',
|
|
236
|
+
}
|
|
237
|
+
response = adapter.infer(request, manifest)
|
|
238
|
+
one_shot_scores[stage] = [item['probability'] for item in response['scores']]
|
|
239
|
+
with torch.inference_mode():
|
|
240
|
+
expected = model(batch).sigmoid()[0].tolist()
|
|
241
|
+
for actual, expected_value in zip(one_shot_scores[stage], expected):
|
|
242
|
+
self.assertAlmostEqual(actual, expected_value, places=6)
|
|
243
|
+
stage_manifests[stage] = {
|
|
244
|
+
'weights': weights.name, 'config': config_path.name,
|
|
245
|
+
'sha256': manifest['weightsSha256'], 'options': [option_id for option_id, _ in options],
|
|
246
|
+
'thresholds': {option_id: 0.5 for option_id, _ in options},
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
(version_dir / 'manifest.json').write_text(json.dumps({
|
|
250
|
+
'schemaVersion': 1, 'version': 'v1', 'createdAt': '2026-11-15T00:00:00Z',
|
|
251
|
+
'stages': stage_manifests, 'evaluation': None,
|
|
252
|
+
}), encoding='utf-8')
|
|
253
|
+
pointer = root / 'active.json'
|
|
254
|
+
pointer.write_text(json.dumps({
|
|
255
|
+
'schemaVersion': 1, 'version': 'v1', 'dir': str(version_dir),
|
|
256
|
+
'previous': None, 'activatedAt': '2026-11-15T00:00:00Z',
|
|
257
|
+
}), encoding='utf-8')
|
|
258
|
+
bundle = adapter.load_active_bundle(pointer)
|
|
259
|
+
token = 'c' * 64
|
|
260
|
+
resident_sums = []
|
|
261
|
+
for stage, options in stage_options.items():
|
|
262
|
+
request = {'schemaVersion': 1, 'task': stage, 'context': 'fixture context',
|
|
263
|
+
'options': [{'id': option_id, 'text': text} for option_id, text in options],
|
|
264
|
+
'catalogHash': 'a' * 64, 'requestHash': 'b' * 64}
|
|
265
|
+
message = {'token': token, 'op': 'score', 'stage': stage, 'request': request}
|
|
266
|
+
score = lambda req, selected_stage: bundle['scorers'][selected_stage]['score'](req)
|
|
267
|
+
reply, stop = adapter._handle(RequestSocket(message), token, bundle['manifest'], None,
|
|
268
|
+
bundle['stamp'], score, None, bundle)
|
|
269
|
+
self.assertFalse(stop)
|
|
270
|
+
self.assertTrue(reply['ok'], reply)
|
|
271
|
+
resident = [item['probability'] for item in reply['response']['scores']]
|
|
272
|
+
self.assertEqual(resident, one_shot_scores[stage])
|
|
273
|
+
resident_sums.append(sum(resident))
|
|
274
|
+
self.assertTrue(any(abs(total - 1.0) > 1e-6 for total in resident_sums), resident_sums)
|
|
275
|
+
|
|
276
|
+
def test_real_categorical_checkpoint_adapter_round_trip_reaches_legacy_decide(self):
|
|
277
|
+
try:
|
|
278
|
+
import torch
|
|
279
|
+
import torch.nn.functional as functional
|
|
280
|
+
from cua_s1.model import ChoiceExample, load_checkpoint, make_system, save_checkpoint
|
|
281
|
+
except ImportError as exc:
|
|
282
|
+
self.skipTest(f'real CUA checkpoint dependencies unavailable: {exc}')
|
|
283
|
+
|
|
284
|
+
repo = Path(__file__).resolve().parents[1]
|
|
285
|
+
with tempfile.TemporaryDirectory(prefix='harness-s1-legacy-') as root:
|
|
286
|
+
root = Path(root)
|
|
287
|
+
torch.set_num_threads(1)
|
|
288
|
+
torch.use_deterministic_algorithms(True)
|
|
289
|
+
torch.manual_seed(20261115)
|
|
290
|
+
config = {'encoder': 'tinyx', 'width': 128, 'rank': 128, 'layers': 2, 'heads': 4,
|
|
291
|
+
'dropout': 0.1, 'context_tokens': 224, 'option_tokens': 96}
|
|
292
|
+
options = (
|
|
293
|
+
'A small bounded edit or operation with clear scope.',
|
|
294
|
+
'Implementation or bug fix needing iterative testing.',
|
|
295
|
+
'Architecture, repository-wide change or multi-stage engineering.',
|
|
296
|
+
'Unclear intent, insufficient context or outside these categories.',
|
|
297
|
+
)
|
|
298
|
+
model, collator = make_system(config, 'cpu')
|
|
299
|
+
example = ChoiceExample(context='repair typo', options=options, label=0)
|
|
300
|
+
batch = collator([example])
|
|
301
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=0.02, weight_decay=0.0)
|
|
302
|
+
for _ in range(40):
|
|
303
|
+
model.train()
|
|
304
|
+
optimizer.zero_grad()
|
|
305
|
+
loss = functional.cross_entropy(model(batch), batch['labels'])
|
|
306
|
+
loss.backward()
|
|
307
|
+
optimizer.step()
|
|
308
|
+
model.eval()
|
|
309
|
+
with torch.inference_mode():
|
|
310
|
+
categorical = model(batch)[0].softmax(-1)
|
|
311
|
+
ranked = categorical.sort(descending=True).values
|
|
312
|
+
if ranked[0] >= 0.9 and ranked[0] - ranked[1] >= 0.2:
|
|
313
|
+
break
|
|
314
|
+
self.assertGreaterEqual(float(ranked[0]), 0.9)
|
|
315
|
+
self.assertGreaterEqual(float(ranked[0] - ranked[1]), 0.2)
|
|
316
|
+
weights, config_path = save_checkpoint(root / 'model.safetensors', model, config, {
|
|
317
|
+
'domain': 'harness-routing-v1', 'bestEpoch': _ + 1,
|
|
318
|
+
'validation': {'nll': float(loss.detach()), 'accuracy': 1.0},
|
|
319
|
+
'datasets': {'prompts.jsonl': 'a' * 64, 'labels.jsonl': 'b' * 64},
|
|
320
|
+
'seed': 20261115, 'catalog': ['tier1', 'tier2', 'tier3'],
|
|
321
|
+
})
|
|
322
|
+
manifest = {
|
|
323
|
+
'schemaVersion': 1, 'python': sys.executable, 'checkpoint': str(weights),
|
|
324
|
+
'weightsSha256': hashlib.sha256(weights.read_bytes()).hexdigest(),
|
|
325
|
+
'configSha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
|
|
326
|
+
'modelId': 'legacy-tier-fixture-v1', 'revision': 'f12-categorical-fixture-v1',
|
|
327
|
+
'domain': 'harness-routing-v1', 'timeoutMs': 10000,
|
|
328
|
+
}
|
|
329
|
+
self.assertEqual(adapter.verify_artifacts(manifest), weights)
|
|
330
|
+
loaded, _loaded_collator, loaded_config = load_checkpoint(weights, 'cpu')
|
|
331
|
+
self.assertEqual(loaded_config, config)
|
|
332
|
+
with torch.inference_mode():
|
|
333
|
+
loaded_softmax = loaded(collator([example]))[0].softmax(-1)
|
|
334
|
+
self.assertAlmostEqual(float(loaded_softmax.sum()), 1.0, places=6)
|
|
335
|
+
|
|
336
|
+
request_script = "const {createRequest}=require('./harness-everything/scripts/system-one/contract'); const {TIER_OPTIONS}=require('./harness-everything/scripts/system-one/router'); process.stdout.write(JSON.stringify(createRequest('tier','repair typo',TIER_OPTIONS)));"
|
|
337
|
+
request_result = subprocess.run(['node', '-e', request_script], cwd=repo, capture_output=True, text=True, check=True)
|
|
338
|
+
request = json.loads(request_result.stdout)
|
|
339
|
+
adapter_result = subprocess.run(
|
|
340
|
+
[sys.executable, str(path), json.dumps(manifest)], input=json.dumps(request),
|
|
341
|
+
cwd=repo, capture_output=True, text=True, timeout=15,
|
|
342
|
+
)
|
|
343
|
+
self.assertEqual(adapter_result.returncode, 0, adapter_result.stderr)
|
|
344
|
+
response = json.loads(adapter_result.stdout)
|
|
345
|
+
decide_script = "const fs=require('node:fs'); const input=JSON.parse(fs.readFileSync(0,'utf8')); const {decide}=require('./harness-everything/scripts/system-one/contract'); const decision=decide(input.request,input.response,{minConfidence:0.9,minMargin:0.2}); process.stdout.write(JSON.stringify({decision,scores:input.response.scores.map(x=>x.probability)}));"
|
|
346
|
+
decision_result = subprocess.run(
|
|
347
|
+
['node', '-e', decide_script], input=json.dumps({'request': request, 'response': response}),
|
|
348
|
+
cwd=repo, capture_output=True, text=True, check=True,
|
|
349
|
+
)
|
|
350
|
+
outcome = json.loads(decision_result.stdout)
|
|
351
|
+
self.assertEqual(outcome['decision']['status'], 'accepted', outcome)
|
|
352
|
+
self.assertEqual(outcome['decision']['selectedId'], 'tier1', outcome)
|
|
353
|
+
|
|
23
354
|
def test_artifact_hash_and_pickle_rejection(self):
|
|
24
355
|
with tempfile.TemporaryDirectory() as root:
|
|
25
356
|
weights = Path(root) / 'model.safetensors'
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Stdlib-only tests for
|
|
1
|
+
"""Stdlib-only tests for CUA-S1 targets and data handling (no torch needed)."""
|
|
2
2
|
import importlib.util
|
|
3
3
|
import json
|
|
4
4
|
from pathlib import Path
|
|
@@ -12,16 +12,55 @@ trainer = importlib.util.module_from_spec(spec)
|
|
|
12
12
|
spec.loader.exec_module(trainer)
|
|
13
13
|
assert 'torch' not in sys.modules, 'importing the trainer must not import torch'
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
assert
|
|
19
|
-
assert
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
15
|
+
tier_catalog = trainer.catalog_for('tier')
|
|
16
|
+
intent_catalog = trainer.catalog_for('intent')
|
|
17
|
+
validity_catalog = trainer.catalog_for('validity')
|
|
18
|
+
assert [o['id'] for o in tier_catalog] == ['tier1', 'tier2', 'tier3'], tier_catalog
|
|
19
|
+
assert [o['id'] for o in intent_catalog][-1] == 'unclassified', intent_catalog
|
|
20
|
+
assert [o['id'] for o in validity_catalog] == ['invalid'], validity_catalog
|
|
21
|
+
|
|
22
|
+
validity_rows = [
|
|
23
|
+
{'id': 'valid', 'gold': 'tier2'},
|
|
24
|
+
{'id': 'invalid', 'gold': None},
|
|
25
|
+
]
|
|
26
|
+
assert [trainer.build_targets(r, validity_catalog, 'validity') for r in validity_rows] == [[0.0], [1.0]]
|
|
27
|
+
print('PASS validity target: all labeled rows; invalid iff tier gold is null')
|
|
28
|
+
|
|
29
|
+
intent_row = {'id': 'intent', 'gold': 'fix', 'secondary': ['test']}
|
|
30
|
+
intent_ids = [o['id'] for o in intent_catalog]
|
|
31
|
+
intent_targets = trainer.build_targets(intent_row, intent_catalog, 'intent')
|
|
32
|
+
assert intent_targets[intent_ids.index('fix')] == 1.0
|
|
33
|
+
assert intent_targets[intent_ids.index('test')] == 1.0
|
|
34
|
+
assert sum(intent_targets) == 2.0
|
|
35
|
+
assert intent_targets[intent_ids.index('unclassified')] == 0.0
|
|
36
|
+
print('PASS intent target: hard multi-hot for gold and secondary')
|
|
37
|
+
|
|
38
|
+
tier_row = {'id': 'tier', 'gold': 'tier2'}
|
|
39
|
+
tier_targets = trainer.build_targets(tier_row, tier_catalog, 'tier')
|
|
40
|
+
assert tier_targets == [0.0, 1.0, 0.0]
|
|
41
|
+
print('PASS tier target: three-way one-hot on valid rows')
|
|
42
|
+
|
|
43
|
+
scores_row = {'id': 'scored', 'gold': 'fix', 'secondary': ['test'],
|
|
44
|
+
'scores': {'fix': 0.9, 'test': 0.55}}
|
|
45
|
+
scores_targets = trainer.build_targets(scores_row, intent_catalog, 'intent', target='scores')
|
|
46
|
+
assert scores_targets[intent_ids.index('fix')] == 0.9
|
|
47
|
+
assert scores_targets[intent_ids.index('test')] == 0.55
|
|
48
|
+
assert scores_targets[intent_ids.index('git')] == 0.0
|
|
49
|
+
print('PASS intent target: soft scores from labels-intent-scores rows')
|
|
50
|
+
|
|
51
|
+
intent_rows = [{'id': 'valid', 'gold': 'fix', 'secondary': []},
|
|
52
|
+
{'id': 'invalid', 'gold': None, 'secondary': []}]
|
|
53
|
+
assert trainer.eligible_rows(validity_rows, 'validity') == validity_rows
|
|
54
|
+
assert trainer.eligible_rows(intent_rows, 'intent') == [intent_rows[0]]
|
|
55
|
+
assert trainer.eligible_rows(validity_rows, 'tier') == [validity_rows[0]]
|
|
56
|
+
assert trainer.build_targets(validity_rows[1], validity_catalog, 'validity') == [1.0]
|
|
57
|
+
assert trainer.target_gold(validity_rows[0], 'validity') == 'actionable'
|
|
58
|
+
assert trainer.target_gold(validity_rows[1], 'validity') == 'invalid'
|
|
59
|
+
print('PASS null handling: validity keeps null; intent and tier exclude it')
|
|
60
|
+
|
|
61
|
+
record = trainer.validation_record(tier_row, tier_catalog, [0.1, 0.8, 0.2], 'tier')
|
|
62
|
+
assert record == {'id': 'tier', 'gold': 'tier2', 'scores': {'tier1': 0.1, 'tier2': 0.8, 'tier3': 0.2}}
|
|
63
|
+
print('PASS validation score rows use independent option-keyed scores')
|
|
25
64
|
|
|
26
65
|
prompts = [
|
|
27
66
|
{'id': 'a', 'family': 'f1', 'source': 'claude', 'split': 'train', 'text': 'commit'},
|
|
@@ -30,27 +69,39 @@ prompts = [
|
|
|
30
69
|
{'id': 'd', 'family': 'f4', 'source': 'codex', 'split': 'train', 'text': 'owner override'},
|
|
31
70
|
]
|
|
32
71
|
labels = [{'id': 'a', 'gold': 'tier1'}, {'id': 'b', 'gold': None}, {'id': 'd', 'gold': 'tier3'}]
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
72
|
+
examples = trainer.join(prompts, labels)
|
|
73
|
+
assert [(e['id'], e['split'], e['gold']) for e in examples] == [
|
|
74
|
+
('a', 'train', 'tier1'), ('b', 'validation', None), ('d', 'train', 'tier3')], examples
|
|
36
75
|
try:
|
|
37
|
-
trainer.join(prompts, labels + [{'id': 'a', 'gold': 'tier2'}]
|
|
76
|
+
trainer.join(prompts, labels + [{'id': 'a', 'gold': 'tier2'}])
|
|
38
77
|
raise SystemExit('duplicate labels must be rejected')
|
|
39
78
|
except ValueError:
|
|
40
79
|
pass
|
|
41
80
|
|
|
42
81
|
lengths = [10, 1024, 300, 5, 700, 1024, 50] * 20
|
|
43
|
-
|
|
44
|
-
|
|
82
|
+
assert trainer.TOKEN_BUDGET == 16384, trainer.TOKEN_BUDGET
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def batch_cost(items, lengths, n_options):
|
|
86
|
+
return len(items) * (max(lengths[i] for i in items) + n_options * trainer.OPTION_TOKENS)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
intent_batches = trainer.make_batches(lengths, 16384, 12, trainer.OPTION_TOKENS)
|
|
90
|
+
flat = sorted(i for b in intent_batches for i in b)
|
|
45
91
|
assert flat == list(range(len(lengths))), 'every example exactly once'
|
|
46
|
-
assert all(
|
|
47
|
-
assert
|
|
92
|
+
assert all(batch_cost(b, lengths, 12) <= 16384 for b in intent_batches), 'whole forward pass within the budget'
|
|
93
|
+
assert intent_batches == trainer.make_batches(lengths, 16384, 12, trainer.OPTION_TOKENS), 'deterministic'
|
|
94
|
+
print('PASS batches: 12 options count toward the budget, every example once, deterministic')
|
|
48
95
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
assert
|
|
96
|
+
# Default budget caps long-prompt batches tightly: a 1024-token prompt plus every option pass must fit.
|
|
97
|
+
long_prompts = [1024] * 64
|
|
98
|
+
one_option = trainer.make_batches(long_prompts, trainer.TOKEN_BUDGET, 1, trainer.OPTION_TOKENS)
|
|
99
|
+
twelve_options = trainer.make_batches(long_prompts, trainer.TOKEN_BUDGET, 12, trainer.OPTION_TOKENS)
|
|
100
|
+
assert max(len(b) for b in one_option) == 16384 // (1024 + 96), max(len(b) for b in one_option)
|
|
101
|
+
assert max(len(b) for b in twelve_options) == 16384 // (1024 + 1152), max(len(b) for b in twelve_options)
|
|
102
|
+
assert all(batch_cost(b, long_prompts, 1) <= trainer.TOKEN_BUDGET for b in one_option)
|
|
103
|
+
assert all(batch_cost(b, long_prompts, 12) <= trainer.TOKEN_BUDGET for b in twelve_options)
|
|
104
|
+
print('PASS batches: default 16384 budget caps 1024-token prompts at 14 examples (1 option) and 7 (12 options)')
|
|
54
105
|
|
|
55
106
|
with tempfile.TemporaryDirectory() as tmp:
|
|
56
107
|
p = Path(tmp) / 'rows.jsonl'
|
|
@@ -58,4 +109,45 @@ with tempfile.TemporaryDirectory() as tmp:
|
|
|
58
109
|
assert trainer.load_jsonl(p) == prompts
|
|
59
110
|
assert len(trainer.sha256_file(p)) == 64
|
|
60
111
|
|
|
112
|
+
# Holdout scoring must key scores by the trained catalog in manifest order, not the fixture's own options.
|
|
113
|
+
score_spec = importlib.util.spec_from_file_location('scorer', ROOT / 'scripts' / 'system-one-cycle' / 'score.py')
|
|
114
|
+
scorer = importlib.util.module_from_spec(score_spec)
|
|
115
|
+
score_spec.loader.exec_module(scorer)
|
|
116
|
+
assert 'torch' not in sys.modules, 'importing the scorer must not import torch'
|
|
117
|
+
|
|
118
|
+
stage_options = {'validity': ['invalid'], 'intent': [o['id'] for o in intent_catalog], 'tier': ['tier1', 'tier2', 'tier3']}
|
|
119
|
+
holdouts = {'validity': trainer.DEFAULT_HOLDOUT, 'intent': trainer.DEFAULT_INTENT_HOLDOUT, 'tier': trainer.DEFAULT_HOLDOUT}
|
|
120
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
121
|
+
manifest = Path(tmp) / 'manifest.json'
|
|
122
|
+
version_manifest = {
|
|
123
|
+
'schemaVersion': 1,
|
|
124
|
+
'version': 'fixture-v1',
|
|
125
|
+
'createdAt': '2026-01-01T00:00:00.000Z',
|
|
126
|
+
'stages': {task: {
|
|
127
|
+
'weights': f'{task}.safetensors',
|
|
128
|
+
'config': f'{task}.json',
|
|
129
|
+
'sha256': '0' * 64,
|
|
130
|
+
'options': ids,
|
|
131
|
+
'thresholds': {option_id: 0.5 for option_id in ids},
|
|
132
|
+
} for task, ids in stage_options.items()},
|
|
133
|
+
'evaluation': None,
|
|
134
|
+
}
|
|
135
|
+
manifest.write_text(json.dumps(version_manifest), encoding='utf-8')
|
|
136
|
+
weights = str(Path(tmp) / 'tier.safetensors')
|
|
137
|
+
for task, options in stage_options.items():
|
|
138
|
+
catalog = scorer.trained_catalog(weights, task, str(holdouts[task]))
|
|
139
|
+
assert [o['id'] for o in catalog] == options, (task, catalog)
|
|
140
|
+
assert {o['id']: o['text'] for o in catalog} == {
|
|
141
|
+
o['id']: o['text'] for o in trainer.catalog_for(task, str(holdouts[task]))
|
|
142
|
+
}, task
|
|
143
|
+
tier_ids = set(stage_options['tier'])
|
|
144
|
+
tier_cases = json.loads(trainer.DEFAULT_HOLDOUT.read_text(encoding='utf-8'))['cases']
|
|
145
|
+
assert all(scorer.eligible(c, 'tier', tier_ids) == (c['gold'] in tier_ids) for c in tier_cases)
|
|
146
|
+
assert any(not scorer.eligible(c, 'tier', tier_ids) for c in tier_cases), 'tier holdout must carry skipped cases'
|
|
147
|
+
intent_ids = set(stage_options['intent'])
|
|
148
|
+
intent_cases = json.loads(trainer.DEFAULT_INTENT_HOLDOUT.read_text(encoding='utf-8'))['cases']
|
|
149
|
+
assert all(scorer.eligible(c, 'intent', intent_ids) for c in intent_cases)
|
|
150
|
+
assert scorer.eligible({'gold': None}, 'validity', set())
|
|
151
|
+
print('PASS holdout scores use the trained catalog in manifest order; non-catalog golds are skipped')
|
|
152
|
+
|
|
61
153
|
print('system-one trainer data tests passed')
|