harness-everything 0.51.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.
Files changed (83) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +23 -0
  4. package/CHANGELOG.md +34 -0
  5. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
  6. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
  7. package/ci/mechanism-2am-observations-session-import.test.js +4 -1
  8. package/ci/mechanism-34-observations.test.js +127 -23
  9. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  10. package/ci/mechanism-handoff-file.test.js +121 -0
  11. package/ci/mechanism-system-one-contract.test.js +9 -2
  12. package/ci/mechanism-system-one-curves.test.js +206 -0
  13. package/ci/mechanism-system-one-cycle.test.js +585 -0
  14. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  15. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  16. package/ci/mechanism-system-one-install.test.js +202 -77
  17. package/ci/mechanism-system-one-live.test.js +361 -0
  18. package/ci/mechanism-system-one-relevance.test.js +11 -1
  19. package/ci/mechanism-system-one-train.test.js +136 -53
  20. package/ci/system-one-adapter-test.py +331 -0
  21. package/ci/system-one-train-test.py +116 -24
  22. package/docs/adr/EVID-001.md +123 -0
  23. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  24. package/docs/governed-index.md +2 -0
  25. package/docs/routing.md +2 -2
  26. package/docs/system-one-cycle.md +68 -0
  27. package/docs/system-one-observations.md +9 -8
  28. package/docs/system-one-routing.md +163 -115
  29. package/docs/system-one-suggestion-gates.md +6 -8
  30. package/docs/system-one-training.md +44 -7
  31. package/docs/workflow-runtime.md +19 -0
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +2 -1
  34. package/harness-everything/scripts/system-one/contract.js +19 -15
  35. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  36. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  37. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  38. package/harness-everything/scripts/system-one/install.js +281 -113
  39. package/harness-everything/scripts/system-one/manifest.js +58 -0
  40. package/harness-everything/scripts/system-one/provider.js +96 -2
  41. package/harness-everything/scripts/system-one/resident.js +47 -1
  42. package/harness-everything/scripts/system-one/router.js +80 -1
  43. package/harness-everything/scripts/tier-router.js +21 -6
  44. package/hooks/scripts/lib/observations.js +43 -4
  45. package/opencode-plugin/plugin.json +1 -1
  46. package/package.json +1 -1
  47. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  48. package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
  49. package/plugins/harness-everything/plugin.json +1 -1
  50. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  51. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  52. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  53. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  54. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  55. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  56. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  57. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  58. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  59. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  60. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  61. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  62. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  63. package/sbom.cdx.json +7 -7
  64. package/scripts/ci-change-scope.js +59 -0
  65. package/scripts/handoff-file.js +223 -0
  66. package/scripts/sync-openai-plugin.js +4 -0
  67. package/scripts/system-one-calibrate.js +108 -41
  68. package/scripts/system-one-curves.js +332 -0
  69. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  70. package/scripts/system-one-cycle/build.js +165 -0
  71. package/scripts/system-one-cycle/collect.js +50 -0
  72. package/scripts/system-one-cycle/common.js +137 -0
  73. package/scripts/system-one-cycle/engines.js +62 -0
  74. package/scripts/system-one-cycle/evaluate.js +70 -0
  75. package/scripts/system-one-cycle/judge.js +106 -0
  76. package/scripts/system-one-cycle/label.js +59 -0
  77. package/scripts/system-one-cycle/package.js +173 -0
  78. package/scripts/system-one-cycle/score.py +111 -0
  79. package/scripts/system-one-cycle/train.js +136 -0
  80. package/scripts/system-one-cycle.js +131 -0
  81. package/scripts/system-one-observations-export.js +29 -6
  82. package/scripts/system-one-observations-review.js +4 -5
  83. package/scripts/system-one-train.py +117 -61
@@ -7,17 +7,30 @@ const text = (value, max = 4096) => typeof value === 'string' && value.trim().le
7
7
  const id = value => typeof value === 'string' && /^[a-z0-9._-]{1,80}$/.test(value);
8
8
  const probability = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;
9
9
  function fail(code) { throw Object.assign(new TypeError(code), { code }); }
10
- function createRequest(task, context, options) {
11
- if (!id(task) || !text(context, 65536) || !Array.isArray(options) || options.length < 2 || options.length > 256
10
+ function createRequest(task, context, options, config) {
11
+ const minOptions = config === undefined ? 2 : exact(config, ['minOptions']) && config.minOptions === 1 ? 1 : null;
12
+ if (minOptions === null || !id(task) || !text(context, 65536) || !Array.isArray(options) || options.length < minOptions || options.length > 256
12
13
  || options.some(o => !exact(o, ['id', 'text']) || !id(o.id) || !text(o.text))
13
14
  || new Set(options.map(o => o.id)).size !== options.length) fail('invalid-request');
14
15
  const copy = options.map(o => ({ id: o.id, text: o.text }));
15
16
  const catalogHash = hash({ task, options: copy });
16
17
  return { schemaVersion: 1, task, context, options: copy, catalogHash, requestHash: hash({ catalogHash, context }) };
17
18
  }
19
+ function responseValid(req, res) {
20
+ return exact(res, ['schemaVersion', 'requestHash', 'catalogHash', 'model', 'scores'])
21
+ && res.schemaVersion === 1 && res.requestHash === req.requestHash && res.catalogHash === req.catalogHash
22
+ && exact(res.model, ['id', 'revision', 'domain']) && Object.values(res.model).every(v => text(v))
23
+ && Array.isArray(res.scores) && res.scores.length === req.options.length
24
+ && res.scores.every((s, i) => exact(s, ['id', 'probability']) && s.id === req.options[i].id && probability(s.probability));
25
+ }
26
+ function validateResponse(req, res) {
27
+ try { validateRequest(req); return responseValid(req, res); }
28
+ catch (_) { return false; }
29
+ }
18
30
  function validateRequest(req) {
19
31
  if (!exact(req, ['schemaVersion', 'task', 'context', 'options', 'catalogHash', 'requestHash']) || req.schemaVersion !== 1) fail('invalid-request');
20
- const rebuilt = createRequest(req.task, req.context, req.options);
32
+ const config = req.task === 'validity' && Array.isArray(req.options) && req.options.length === 1 ? { minOptions: 1 } : undefined;
33
+ const rebuilt = createRequest(req.task, req.context, req.options, config);
21
34
  if (req.catalogHash !== rebuilt.catalogHash || req.requestHash !== rebuilt.requestHash) fail('invalid-request');
22
35
  return true;
23
36
  }
@@ -28,12 +41,7 @@ function decide(req, res, policy = {}) {
28
41
  const { domain = 'harness-routing-v1', minConfidence = 0.9, minMargin = 0.2 } = policy;
29
42
  if (!text(domain) || !probability(minConfidence) || !probability(minMargin)) fail('invalid-policy');
30
43
  const empty = { status: 'invalid-output', reason: 'invalid-response', selectedId: null, confidence: null, margin: null, model: null };
31
- if (!exact(res, ['schemaVersion', 'requestHash', 'catalogHash', 'model', 'scores'])
32
- || res.schemaVersion !== 1 || res.requestHash !== req.requestHash || res.catalogHash !== req.catalogHash
33
- || !exact(res.model, ['id', 'revision', 'domain']) || !Object.values(res.model).every(v => text(v))
34
- || !Array.isArray(res.scores) || res.scores.length !== req.options.length
35
- || res.scores.some((s, i) => !exact(s, ['id', 'probability']) || s.id !== req.options[i].id || !probability(s.probability))
36
- || Math.abs(res.scores.reduce((s, o) => s + o.probability, 0) - 1) > 1e-6) return empty;
44
+ if (!responseValid(req, res) || Math.abs(res.scores.reduce((sum, score) => sum + score.probability, 0) - 1) > 1e-6) return empty;
37
45
  const ranked = [...res.scores].sort((a, b) => b.probability - a.probability);
38
46
  const confidence = ranked[0].probability;
39
47
  const margin = confidence - ranked[1].probability;
@@ -61,11 +69,7 @@ function decideIntents(req, res, policy = {}) {
61
69
  if (!text(domain)) fail('invalid-policy');
62
70
  const empty = { status: 'invalid-output', reason: 'invalid-response', selectedId: null,
63
71
  confidence: null, margin: null, model: null, intents: null };
64
- if (!exact(res, ['schemaVersion', 'requestHash', 'catalogHash', 'model', 'scores'])
65
- || res.schemaVersion !== 1 || res.requestHash !== req.requestHash || res.catalogHash !== req.catalogHash
66
- || !exact(res.model, ['id', 'revision', 'domain']) || !Object.values(res.model).every(v => text(v))
67
- || !Array.isArray(res.scores) || res.scores.length !== req.options.length
68
- || res.scores.some((s, i) => !exact(s, ['id', 'probability']) || s.id !== req.options[i].id || !probability(s.probability))) return empty;
72
+ if (!responseValid(req, res)) return empty;
69
73
  const model = { ...res.model };
70
74
  if (model.domain !== domain) {
71
75
  return { status: 'abstain', reason: 'domain-mismatch', selectedId: null,
@@ -86,4 +90,4 @@ function decideIntents(req, res, policy = {}) {
86
90
  return { status: 'accepted', reason: 'scored', selectedId: fired[0][0], confidence,
87
91
  margin: confidence - Math.max(...rest, 0), model, intents };
88
92
  }
89
- module.exports = { createRequest, validateRequest, decide, decideIntents };
93
+ module.exports = { createRequest, validateRequest, validateResponse, decide, decideIntents };
@@ -2,22 +2,31 @@
2
2
  import hashlib
3
3
  import hmac
4
4
  import json
5
+ import math
5
6
  import os
6
7
  from pathlib import Path
7
8
  import re
8
9
  import secrets
10
+ import shutil
9
11
  import socket
10
12
  import subprocess
11
13
  import sys
14
+ import tempfile
12
15
  import threading
13
16
  import time
14
17
 
18
+ ACTIVE_STAGES = ('validity', 'intent', 'tier')
19
+ LEGACY_ROUTING_METADATA = frozenset(('domain', 'bestEpoch', 'validation', 'datasets', 'seed', 'catalog'))
20
+
15
21
 
16
22
  def verify_artifacts(manifest):
17
23
  weights = Path(manifest['checkpoint'])
18
24
  if not weights.is_absolute() or weights.suffix != '.safetensors':
19
25
  raise ValueError('checkpoint-format')
20
- for file, key in [(weights, 'weightsSha256'), (weights.with_suffix('.json'), 'configSha256')]:
26
+ config = Path(manifest.get('config', weights.with_suffix('.json')))
27
+ if not config.is_absolute() or config.suffix != '.json':
28
+ raise ValueError('checkpoint-format')
29
+ for file, key in [(weights, 'weightsSha256'), (config, 'configSha256')]:
21
30
  with file.open('rb') as handle:
22
31
  digest = hashlib.file_digest(handle, 'sha256').hexdigest()
23
32
  if digest != manifest[key]:
@@ -32,19 +41,65 @@ def check_limits(request, config):
32
41
  raise ValueError('input-too-long')
33
42
 
34
43
 
44
+ def _score_semantics(weights, manifest):
45
+ config_path = Path(manifest.get('config', Path(weights).with_suffix('.json')))
46
+ try:
47
+ document = json.loads(config_path.read_text(encoding='utf-8'))
48
+ except (OSError, TypeError, ValueError):
49
+ raise ValueError('checkpoint-semantics') from None
50
+ if not isinstance(document, dict):
51
+ raise ValueError('checkpoint-semantics')
52
+ metadata = document.get('metadata', {})
53
+ if not isinstance(metadata, dict):
54
+ raise ValueError('checkpoint-semantics')
55
+ if manifest.get('modelId') == 'cua-ai/cua-s1-forms' and manifest.get('domain') == 'forms-v1':
56
+ loss = metadata.get('loss')
57
+ if metadata.get('domain') not in (None, 'forms-v1') or loss not in (None, 'cross_entropy'):
58
+ raise ValueError('checkpoint-semantics')
59
+ return 'categorical', 'tier'
60
+ if manifest.get('domain') == 'harness-routing-v1' and metadata.get('domain') == 'harness-routing-v1':
61
+ if metadata.get('task') in ACTIVE_STAGES and metadata.get('loss') == 'binary_cross_entropy':
62
+ return 'independent', metadata['task']
63
+ # The old tier trainer emitted this exact sidecar shape after categorical cross-entropy training.
64
+ validation = metadata.get('validation')
65
+ datasets = metadata.get('datasets')
66
+ if (set(metadata) == LEGACY_ROUTING_METADATA and metadata.get('catalog') == ['tier1', 'tier2', 'tier3']
67
+ and isinstance(metadata.get('bestEpoch'), int) and not isinstance(metadata['bestEpoch'], bool)
68
+ and metadata['bestEpoch'] > 0 and isinstance(metadata.get('seed'), int) and not isinstance(metadata['seed'], bool)
69
+ and isinstance(validation, dict) and set(validation) == {'nll', 'accuracy'}
70
+ and all(isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) for value in validation.values())
71
+ and isinstance(datasets, dict) and {'prompts.jsonl', 'labels.jsonl'} <= datasets.keys()
72
+ and all(isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value) for value in datasets.values())):
73
+ return 'categorical', 'tier'
74
+ raise ValueError('checkpoint-semantics')
75
+
76
+
35
77
  def load_scorer(weights, manifest):
36
- """Load the verified checkpoint once; return (score(request) -> probabilities, config)."""
78
+ """Load a verified checkpoint and apply its declared training objective."""
79
+ semantics, task = _score_semantics(weights, manifest)
37
80
  import torch
38
81
  from cua_s1.model import ChoiceExample, load_checkpoint
39
82
 
40
83
  torch.set_num_threads(1)
41
84
  torch.use_deterministic_algorithms(True)
42
- model, collator, config = load_checkpoint(weights, 'cpu')
85
+ config_path = Path(manifest.get('config', Path(weights).with_suffix('.json')))
86
+ if config_path != Path(weights).with_suffix('.json'):
87
+ with tempfile.TemporaryDirectory() as root:
88
+ shutil.copyfile(weights, Path(root) / 'model.safetensors')
89
+ shutil.copyfile(config_path, Path(root) / 'config.json')
90
+ model, collator, config = load_checkpoint(root, 'cpu')
91
+ else:
92
+ model, collator, config = load_checkpoint(weights, 'cpu')
43
93
 
44
94
  def score(request):
95
+ if request.get('task') != task:
96
+ raise ValueError('checkpoint-semantics')
45
97
  example = ChoiceExample(context=request['context'], options=tuple(o['text'] for o in request['options']), label=0)
46
98
  with torch.inference_mode():
47
- return model(collator([example])).softmax(-1)[0].tolist()
99
+ logits = model(collator([example]))
100
+ return (logits.softmax(-1) if semantics == 'categorical' else logits.sigmoid())[0].tolist()
101
+ score.score_semantics = semantics
102
+ score.training_task = task
48
103
  return score, config
49
104
 
50
105
 
@@ -63,6 +118,107 @@ def infer(request, manifest):
63
118
  return build_response(request, manifest, score(request))
64
119
 
65
120
 
121
+ def validate_shared_manifest(manifest):
122
+ node = os.environ.get('HARNESS_SYSTEM_ONE_NODE') or shutil.which('node')
123
+ if not node:
124
+ raise ValueError('active-manifest')
125
+ validator = Path(__file__).with_name('manifest.js')
126
+ try:
127
+ result = subprocess.run([node, str(validator)], input=json.dumps(manifest), text=True,
128
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5,
129
+ shell=False, check=False)
130
+ except (OSError, subprocess.SubprocessError):
131
+ raise ValueError('active-manifest') from None
132
+ if result.returncode != 0:
133
+ raise ValueError('active-manifest')
134
+
135
+
136
+ def _active_artifact(directory, name, suffix):
137
+ if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9._-]+', name) or name in ('.', '..') or Path(name).name != name or '\\' in name or Path(name).suffix != suffix:
138
+ raise ValueError('checkpoint-format')
139
+ file = directory / name
140
+ if file.is_symlink() or not file.is_file():
141
+ raise ValueError('checkpoint-format')
142
+ return file
143
+
144
+
145
+ def _active_fingerprint(version, directory, scorers):
146
+ values = [version, str(directory)]
147
+ for stage in ACTIVE_STAGES:
148
+ entry = scorers[stage]
149
+ values.extend((stage, entry['sha256'], entry['manifest']['configSha256']))
150
+ return hashlib.sha256('\0'.join(values).encode('utf-8')).hexdigest()
151
+
152
+
153
+ def _active_stamp(bundle):
154
+ paths = [Path(bundle['activePath']), Path(bundle['manifestPath'])]
155
+ for stage in ACTIVE_STAGES:
156
+ paths.extend((bundle['scorers'][stage]['weights'], bundle['scorers'][stage]['configPath']))
157
+ return [(file.stat().st_size, file.stat().st_mtime_ns) for file in paths]
158
+
159
+
160
+ def _active_unchanged(bundle, stamp):
161
+ try:
162
+ return _active_stamp(bundle) == stamp
163
+ except OSError:
164
+ return False
165
+
166
+
167
+ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=None):
168
+ """Read one active pointer and load its three verified stage checkpoints."""
169
+ active_path = Path(active_path)
170
+ if not active_path.is_absolute() or active_path.is_symlink() or not active_path.is_file() or active_path.stat().st_size > 65536:
171
+ raise ValueError('active-pointer')
172
+ pointer = json.loads(active_path.read_text(encoding='utf-8'))
173
+ if (not isinstance(pointer, dict) or set(pointer) != {'schemaVersion', 'version', 'dir', 'previous', 'activatedAt'}
174
+ or pointer.get('schemaVersion') != 1 or not isinstance(pointer.get('version'), str)
175
+ or not ID_PATTERN.fullmatch(pointer['version']) or not isinstance(pointer.get('dir'), str)
176
+ or not Path(pointer['dir']).is_absolute()
177
+ or (pointer.get('previous') is not None and (not isinstance(pointer['previous'], str) or not ID_PATTERN.fullmatch(pointer['previous'])))
178
+ or not isinstance(pointer.get('activatedAt'), str)):
179
+ raise ValueError('active-pointer')
180
+ directory = Path(pointer['dir'])
181
+ if directory.is_symlink() or not directory.is_dir():
182
+ raise ValueError('active-pointer')
183
+ manifest_path = directory / 'manifest.json'
184
+ if manifest_path.is_symlink() or not manifest_path.is_file() or manifest_path.stat().st_size > 131072:
185
+ raise ValueError('active-manifest')
186
+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
187
+ validate_shared_manifest(manifest)
188
+ if manifest['version'] != pointer['version']:
189
+ raise ValueError('active-manifest')
190
+ scorers = {}
191
+ loader = scorer_loader or load_scorer
192
+ for stage in ACTIVE_STAGES:
193
+ entry = manifest['stages'][stage]
194
+ weights = _active_artifact(directory, entry['weights'], '.safetensors')
195
+ config_path = _active_artifact(directory, entry['config'], '.json')
196
+ if hashlib.sha256(weights.read_bytes()).hexdigest() != entry['sha256']:
197
+ raise ValueError('artifact-hash')
198
+ stage_manifest = {
199
+ 'checkpoint': str(weights),
200
+ 'config': str(config_path),
201
+ 'weightsSha256': entry['sha256'],
202
+ 'configSha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
203
+ 'modelId': pointer['version'],
204
+ 'revision': pointer['version'],
205
+ 'domain': 'harness-routing-v1',
206
+ }
207
+ score, config = loader(weights, stage_manifest)
208
+ if scorer_loader is None and (score.score_semantics != 'independent' or score.training_task != stage):
209
+ raise ValueError('active-stage')
210
+ scorers[stage] = {**entry, 'manifest': stage_manifest, 'score': score, 'config': config,
211
+ 'weights': weights, 'configPath': config_path}
212
+ fingerprint = _active_fingerprint(pointer['version'], pointer['dir'], scorers)
213
+ if expected_fingerprint is not None and fingerprint != expected_fingerprint:
214
+ raise ValueError('active-changed')
215
+ bundle = {'activePath': str(active_path), 'manifestPath': str(manifest_path), 'pointer': pointer,
216
+ 'manifest': manifest, 'version': pointer['version'], 'dir': pointer['dir'],
217
+ 'fingerprint': fingerprint, 'scorers': scorers}
218
+ bundle['stamp'] = _active_stamp(bundle)
219
+ return bundle
220
+
221
+
66
222
  MAX_REQUEST_BYTES = 2 * 1024 * 1024
67
223
  MAX_OPTIONS = 256
68
224
  MAX_CLIENTS = 64
@@ -152,7 +308,7 @@ def _valid_score_request(request):
152
308
  or not all(isinstance(request[k], str) and HASH_PATTERN.fullmatch(request[k]) for k in ('catalogHash', 'requestHash'))):
153
309
  return False
154
310
  options = request['options']
155
- if not isinstance(options, list) or not 2 <= len(options) <= MAX_OPTIONS:
311
+ if not isinstance(options, list) or not 1 <= len(options) <= MAX_OPTIONS:
156
312
  return False
157
313
  if any(not isinstance(o, dict) or set(o) != {'id', 'text'} or not isinstance(o['id'], str)
158
314
  or not ID_PATTERN.fullmatch(o['id']) or not isinstance(o['text'], str) for o in options):
@@ -160,7 +316,7 @@ def _valid_score_request(request):
160
316
  return len({o['id'] for o in options}) == len(options)
161
317
 
162
318
 
163
- def _handle(conn, token, manifest, weights, stamp, score, config):
319
+ def _handle(conn, token, manifest, weights, stamp, score, config, active_bundle=None):
164
320
  """Return (reply, stop). Errors carry bounded reason codes only: no prompt, path, or traceback."""
165
321
  invalid = {'ok': False, 'reason': 'invalid-request'}
166
322
  try:
@@ -180,35 +336,50 @@ def _handle(conn, token, manifest, weights, stamp, score, config):
180
336
  return {'ok': False, 'reason': 'unauthorized'}, False
181
337
  op = message.get('op')
182
338
  if op == 'ping':
183
- return {'ok': True, 'pid': os.getpid(), 'model': {'id': manifest['modelId'], 'revision': manifest['revision'], 'domain': manifest['domain']}}, False
339
+ model = {'id': active_bundle['version'], 'revision': active_bundle['version'], 'domain': 'harness-routing-v1'} if active_bundle else {
340
+ 'id': manifest['modelId'], 'revision': manifest['revision'], 'domain': manifest['domain']}
341
+ return {'ok': True, 'pid': os.getpid(), 'model': model}, False
184
342
  if op == 'shutdown':
185
343
  return {'ok': True}, True
186
- if op != 'score' or not _valid_score_request(message.get('request')):
344
+ stage = message.get('stage') if active_bundle else None
345
+ if (op != 'score' or (active_bundle and set(message) != {'token', 'op', 'stage', 'request'})
346
+ or (not active_bundle and not _valid_score_request(message.get('request')))
347
+ or (active_bundle and (not isinstance(stage, str) or stage not in active_bundle['scorers']
348
+ or not _valid_score_request(message.get('request'))))):
187
349
  return invalid, False
188
350
  try:
189
- changed = _artifact_stamp(weights) != stamp
351
+ changed = not _active_unchanged(active_bundle, stamp) if active_bundle else _artifact_stamp(weights) != stamp
190
352
  except OSError:
191
353
  changed = True
192
354
  if changed:
193
355
  return {'ok': False, 'reason': 'artifact-changed'}, True
194
356
  request = message['request']
357
+ selected = active_bundle['scorers'][stage] if active_bundle else None
358
+ if active_bundle and (request['task'] != stage or [option['id'] for option in request['options']] != selected['options']):
359
+ return invalid, False
195
360
  try:
196
- check_limits(request, config)
361
+ check_limits(request, selected['config'] if active_bundle else config)
197
362
  except ValueError:
198
363
  return {'ok': False, 'reason': 'input-too-long'}, False
199
364
  try:
200
- return {'ok': True, 'response': build_response(request, manifest, score(request))}, False
365
+ response = build_response(request, selected['manifest'], score(request, stage)) if active_bundle else build_response(request, manifest, score(request))
366
+ return {'ok': True, 'response': response}, False
201
367
  except Exception:
202
368
  return {'ok': False, 'reason': 'score-failed'}, False
203
369
 
204
370
 
205
- def serve(manifest, state_path, lock_path, scorer_factory=None, idle_timeout_s=None):
371
+ def serve(manifest, state_path, lock_path, scorer_factory=None, idle_timeout_s=None, active_bundle=None):
206
372
  """Resident loopback scorer: verify, load once, publish state, serve until idle/shutdown/artifact change."""
207
373
  state_path, lock_path = Path(state_path), Path(lock_path)
208
374
  try:
209
- weights = verify_artifacts(manifest)
210
- stamp = _artifact_stamp(weights)
211
- score, config = (scorer_factory or load_scorer)(weights, manifest)
375
+ if active_bundle:
376
+ weights = None
377
+ stamp = active_bundle['stamp']
378
+ score = config = None
379
+ else:
380
+ weights = verify_artifacts(manifest)
381
+ stamp = _artifact_stamp(weights)
382
+ score, config = (scorer_factory or load_scorer)(weights, manifest)
212
383
  except Exception as exc:
213
384
  reason = str(exc) if str(exc) in STARTUP_REASONS else 'load-failed'
214
385
  try:
@@ -227,6 +398,10 @@ def serve(manifest, state_path, lock_path, scorer_factory=None, idle_timeout_s=N
227
398
  with score_lock:
228
399
  return score(request)
229
400
 
401
+ def guarded_active_score(request, stage):
402
+ with score_lock:
403
+ return active_bundle['scorers'][stage]['score'](request)
404
+
230
405
  def send(conn, reply):
231
406
  try:
232
407
  conn.sendall((json.dumps(reply, allow_nan=False) + '\n').encode('utf-8'))
@@ -237,7 +412,8 @@ def serve(manifest, state_path, lock_path, scorer_factory=None, idle_timeout_s=N
237
412
  try:
238
413
  with conn:
239
414
  conn.settimeout(READ_DEADLINE_S)
240
- reply, halt = _handle(conn, token, manifest, weights, stamp, guarded_score, config)
415
+ reply, halt = _handle(conn, token, manifest, weights, stamp,
416
+ guarded_active_score if active_bundle else guarded_score, config, active_bundle)
241
417
  send(conn, reply)
242
418
  if halt:
243
419
  stop.set()
@@ -256,7 +432,8 @@ def serve(manifest, state_path, lock_path, scorer_factory=None, idle_timeout_s=N
256
432
  pass
257
433
  last = time.monotonic()
258
434
  # A server whose state file no longer names it is undiscoverable (replaced or corrupted): exit, never orphan.
259
- while not stop.is_set() and time.monotonic() - last <= idle and _owns_state(state_path, pid, token):
435
+ while not stop.is_set() and time.monotonic() - last <= idle and _owns_state(state_path, pid, token) \
436
+ and (active_bundle is None or _active_unchanged(active_bundle, stamp)):
260
437
  try:
261
438
  conn, _ = server.accept()
262
439
  except socket.timeout:
@@ -301,6 +478,21 @@ def serve_main(argv, scorer_factory=None):
301
478
  return serve(json.loads(argv[0]), argv[1], argv[2], scorer_factory=scorer_factory)
302
479
 
303
480
 
481
+ def serve_active_main(argv):
482
+ if len(argv) != 4:
483
+ return 2
484
+ active_path, state_path, lock_path, fingerprint = argv
485
+ try:
486
+ bundle = load_active_bundle(active_path, expected_fingerprint=fingerprint)
487
+ except Exception:
488
+ try:
489
+ _write_private_json(Path(lock_path), {'failed': 'load-failed', 'at': time.time()})
490
+ except OSError:
491
+ pass
492
+ return 1
493
+ return serve(bundle['manifest'], state_path, lock_path, active_bundle=bundle)
494
+
495
+
304
496
  def source_revision(direct_url_text):
305
497
  """Return the PEP 610 VCS commit recorded at install time, or None when unprovable."""
306
498
  try:
@@ -335,6 +527,8 @@ def main():
335
527
  return 0
336
528
  if sys.argv[1:2] == ['--serve']:
337
529
  return serve_main(sys.argv[2:])
530
+ if sys.argv[1:2] == ['--serve-active']:
531
+ return serve_active_main(sys.argv[2:])
338
532
  manifest = json.loads(sys.argv[1])
339
533
  raw = sys.stdin.buffer.read(2 * 1024 * 1024 + 1)
340
534
  if len(raw) > 2 * 1024 * 1024:
@@ -41,7 +41,7 @@ function checkScores(decision, scores, labels) {
41
41
  const scored = ['accepted', 'abstain'].includes(decision.status);
42
42
  if (!scored) { if (scores !== null) fail(); return; }
43
43
  if (!Array.isArray(scores) || scores.length !== labels.length
44
- || scores.some(p => !finite(p) || p < 0 || p > 1) || Math.abs(scores.reduce((s, p) => s + p, 0) - 1) > 1e-6) fail();
44
+ || scores.some(p => !finite(p) || p < 0 || p > 1)) fail();
45
45
  const ranked = [...scores].sort((a, b) => b - a);
46
46
  if (decision.confidence !== ranked[0] || decision.margin !== ranked[0] - ranked[1]) fail();
47
47
  }
@@ -121,10 +121,7 @@ function gradeRelevance(cases, byId, labels, thresholds) {
121
121
  weakPrecision: supported.length ? Math.min(...supported.map(([, t]) => t.precision)) : 0,
122
122
  };
123
123
  }
124
- // Relevance-native promotion gates. Thresholds are the reviewed numbers in
125
- // docs/system-one-intent-gates.md; policy/live-host evidence stays reported
126
- // (false) until independently produced, so rolloutReady is red by
127
- // construction pre-production.
124
+ // Gate values are recorded for comparison; they do not block the opt-in launch.
128
125
  function relevanceGates(multi, evidence) {
129
126
  const supported = Object.values(multi.perIntent).filter(t => t.support >= 10);
130
127
  const gates = {
@@ -141,9 +138,7 @@ function relevanceGates(multi, evidence) {
141
138
  policyEvidence: false,
142
139
  liveHostEvidence: false,
143
140
  };
144
- // rolloutReady stays false until policy/live-host evidence exists; the
145
- // gates above are necessary but not sufficient pre-production.
146
- return { ...gates, rolloutReady: false };
141
+ return gates;
147
142
  }
148
143
  // sourceEvidence is the provider provenance result; only the pinned cua_s1 revision satisfies the gate.
149
144
  function evaluate(corpus, records, sourceEvidence = null, { secondaryThreshold } = {}) {
@@ -190,6 +185,6 @@ function evaluate(corpus, records, sourceEvidence = null, { secondaryThreshold }
190
185
  policyEvidence: false,
191
186
  liveHostEvidence: false,
192
187
  };
193
- return { schemaVersion: 1, cases: cases.length, baseline, model, ...families, agreement, latency, gates, rolloutReady: Object.values(gates).every(Boolean) };
188
+ return { schemaVersion: 1, cases: cases.length, baseline, model, ...families, agreement, latency, gates };
194
189
  }
195
190
  module.exports = { validateCorpus, evaluate, gradeRelevance, relevanceGates };
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const MAX_PATHS = 3;
7
+ const MAX_FILE_BYTES = 1024 * 1024;
8
+ const HANDOFF_READER_PATHS = [
9
+ path.resolve(__dirname, '../../../scripts/handoff-file.js'),
10
+ path.resolve(__dirname, '../../../../scripts/handoff-file.js'),
11
+ ];
12
+ let loadHeader;
13
+
14
+ function pathCandidates(prompt) {
15
+ const candidates = [];
16
+ const tokens = /"([^"]*)"|'([^']*)'|`([^`]*)`|(\S+)/g;
17
+ let match;
18
+ while (candidates.length < MAX_PATHS && (match = tokens.exec(prompt))) {
19
+ let value = match[1] ?? match[2] ?? match[3] ?? match[4];
20
+ value = value.replace(/^\[[^\]]*\]\((.*)\)$/, '$1')
21
+ .replace(/^[<([{]+/, '').replace(/[>)\]},.;!?]+$/, '');
22
+ if (!value || /^(?:https?|file):\/\//i.test(value)) continue;
23
+ if (path.isAbsolute(value) || value.includes('/') || value.includes('\\')
24
+ || /\.[A-Za-z0-9_-]{1,16}$/.test(value)) candidates.push(value);
25
+ }
26
+ return candidates;
27
+ }
28
+
29
+ function isWithin(root, target) {
30
+ const relative = path.relative(root, target);
31
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
32
+ }
33
+
34
+ function reader() {
35
+ if (!loadHeader) {
36
+ const file = HANDOFF_READER_PATHS.find(candidate => fs.existsSync(candidate));
37
+ if (!file) throw new Error('handoff reader unavailable');
38
+ ({ loadHeader } = require(file));
39
+ }
40
+ return loadHeader;
41
+ }
42
+
43
+ function oneLine(value) {
44
+ return String(value).replace(/\s+/g, ' ').trim();
45
+ }
46
+
47
+ function prepareHandoffInput(prompt, cwd = process.cwd()) {
48
+ const original = typeof prompt === 'string' ? prompt : String(prompt ?? '');
49
+ const lines = [];
50
+ try {
51
+ const root = fs.realpathSync.native(path.resolve(cwd));
52
+ for (const value of pathCandidates(original)) {
53
+ try {
54
+ const absolute = path.isAbsolute(value);
55
+ const candidate = path.resolve(root, value);
56
+ if (!absolute && !isWithin(root, candidate)) continue;
57
+ const file = fs.realpathSync.native(candidate);
58
+ if (!absolute && !isWithin(root, file)) continue;
59
+ const stat = fs.statSync(file);
60
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) continue;
61
+ const header = reader()(file);
62
+ lines.push(`[handoff] kind=${header.kind} title=${oneLine(header.title)} summary=${oneLine(header.summary)}`);
63
+ } catch (_) {
64
+ // Missing files and invalid headers do not affect the lexical route.
65
+ }
66
+ }
67
+ } catch (_) {
68
+ // Path resolution is advisory; keep the original scorer input on any error.
69
+ }
70
+ return {
71
+ input: lines.length ? `${original}${original.endsWith('\n') ? '' : '\n'}${lines.join('\n')}` : original,
72
+ handoffFiles: lines.length,
73
+ };
74
+ }
75
+
76
+ module.exports = { prepareHandoffInput };