harness-everything 0.51.0 → 0.53.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 (97) 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 +54 -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/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
  8. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
  9. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
  10. package/ci/mechanism-2am-observations-session-import.test.js +4 -1
  11. package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
  12. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
  13. package/ci/mechanism-338-opencode-async.test.js +20 -3
  14. package/ci/mechanism-34-observations.test.js +127 -23
  15. package/ci/mechanism-341-opencode-lane.test.js +7 -1
  16. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  17. package/ci/mechanism-397-cycle-import.test.js +399 -0
  18. package/ci/mechanism-397-host-acceptance.test.js +119 -0
  19. package/ci/mechanism-397-opencode-observations.test.js +1922 -0
  20. package/ci/mechanism-handoff-file.test.js +121 -0
  21. package/ci/mechanism-system-one-contract.test.js +9 -2
  22. package/ci/mechanism-system-one-curves.test.js +223 -0
  23. package/ci/mechanism-system-one-cycle.test.js +1204 -0
  24. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  25. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  26. package/ci/mechanism-system-one-install.test.js +202 -77
  27. package/ci/mechanism-system-one-live.test.js +361 -0
  28. package/ci/mechanism-system-one-relevance.test.js +11 -1
  29. package/ci/mechanism-system-one-train.test.js +136 -53
  30. package/ci/system-one-adapter-test.py +331 -0
  31. package/ci/system-one-train-test.py +116 -24
  32. package/docs/adr/EVID-001.md +123 -0
  33. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  34. package/docs/governed-index.md +2 -0
  35. package/docs/platform-capabilities.md +13 -6
  36. package/docs/routing.md +2 -2
  37. package/docs/system-one-cycle.md +77 -0
  38. package/docs/system-one-observations.md +43 -11
  39. package/docs/system-one-routing.md +163 -115
  40. package/docs/system-one-suggestion-gates.md +6 -8
  41. package/docs/system-one-training.md +44 -7
  42. package/docs/workflow-runtime.md +19 -0
  43. package/harness-everything/SKILL.md +1 -1
  44. package/harness-everything/scripts/kernel-router.js +2 -1
  45. package/harness-everything/scripts/system-one/contract.js +19 -15
  46. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  47. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  48. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  49. package/harness-everything/scripts/system-one/install.js +281 -113
  50. package/harness-everything/scripts/system-one/manifest.js +58 -0
  51. package/harness-everything/scripts/system-one/provider.js +96 -2
  52. package/harness-everything/scripts/system-one/resident.js +47 -1
  53. package/harness-everything/scripts/system-one/router.js +80 -1
  54. package/harness-everything/scripts/tier-router.js +21 -6
  55. package/hooks/scripts/lib/observations.js +48 -7
  56. package/opencode-plugin/README.md +22 -8
  57. package/opencode-plugin/index.mjs +424 -44
  58. package/opencode-plugin/plugin.json +1 -1
  59. package/package.json +1 -1
  60. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  61. package/plugins/harness-everything/hooks/scripts/lib/observations.js +48 -7
  62. package/plugins/harness-everything/plugin.json +1 -1
  63. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  64. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  65. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  66. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  67. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  68. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  69. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  70. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  71. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  72. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  73. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  74. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  75. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  76. package/sbom.cdx.json +7 -7
  77. package/scripts/ci-change-scope.js +59 -0
  78. package/scripts/handoff-file.js +223 -0
  79. package/scripts/sync-openai-plugin.js +4 -0
  80. package/scripts/system-one-calibrate.js +108 -41
  81. package/scripts/system-one-curves.js +472 -0
  82. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  83. package/scripts/system-one-cycle/build.js +165 -0
  84. package/scripts/system-one-cycle/collect.js +67 -0
  85. package/scripts/system-one-cycle/common.js +175 -0
  86. package/scripts/system-one-cycle/engines.js +62 -0
  87. package/scripts/system-one-cycle/evaluate.js +73 -0
  88. package/scripts/system-one-cycle/judge.js +106 -0
  89. package/scripts/system-one-cycle/label.js +59 -0
  90. package/scripts/system-one-cycle/package.js +173 -0
  91. package/scripts/system-one-cycle/score.py +111 -0
  92. package/scripts/system-one-cycle/train.js +136 -0
  93. package/scripts/system-one-cycle.js +136 -0
  94. package/scripts/system-one-observations-export.js +58 -6
  95. package/scripts/system-one-observations-import-store.js +128 -0
  96. package/scripts/system-one-observations-review.js +4 -5
  97. package/scripts/system-one-train.py +117 -61
@@ -7,6 +7,8 @@ Gold labels follow [system-one-corpus.md](system-one-corpus.md). The owner-revie
7
7
  holdout in that document is used only for evaluation. It is never used for training,
8
8
  threshold selection or labeler tuning.
9
9
 
10
+ For the owner-started monthly collection-to-package workflow, see [System One monthly training cycle](system-one-cycle.md).
11
+
10
12
  ## Pipeline
11
13
 
12
14
  1. **Collect**: copy the owner's own prompts from local assistant histories into a local
@@ -159,17 +161,25 @@ prompts written by an agent, not by the owner. VS Code terminal notifications
159
161
  same logits, which ranks the intents in relevance order, so the contract's
160
162
  probability vector and the calibration below stay as they are. Handing the absolute
161
163
  relevance bands to the skills stage is a separate contract change.
162
- - The `tinyx` path below is kept for comparison. Its first checkpoint learned little beyond
163
- class priors.
164
- - **Model** (`tinyx`): a new `cua_s1` `tinyx` scorer built with `make_system`.
164
+ - **CUA-S1 trainer**: `scripts/system-one-train.py` builds a new `cua_s1` `tinyx` scorer
165
+ with `make_system`. `--task {validity,intent,tier}` selects the head (default `tier`);
166
+ `--target {label,scores}` selects hard labels or scored intent labels (default `label`).
167
+ `--target scores` requires `--task intent` and reads `labels-intent-scores.jsonl`.
165
168
  - Config: `width` 128, `rank` 128, `layers` 2, `heads` 4, `context_tokens` 1024 and
166
169
  `option_tokens` 96.
167
170
  - Weights are initialized fresh, not from the forms checkpoint, whose domain and
168
171
  positional range differ.
169
- - **Target**: each example is the fixed tier catalog with the index of the gold option.
170
- `null` maps to `unclassified`.
171
- - **Optimization**:
172
- - Cross-entropy, AdamW, a fixed seed and CPU.
172
+ - **Targets**: each option is an independent binary target. The validity head uses all
173
+ `labels.jsonl` rows and scores one `invalid` option: a `null` tier gold maps to 1, and a
174
+ tier gold maps to 0. The tier head uses valid `labels.jsonl` rows, the three options
175
+ `tier1`, `tier2` and `tier3`, and a one-hot target. The intent head uses valid
176
+ `labels-intent.jsonl` rows and the fixed intent catalog; its hard target is multi-hot for
177
+ `gold` plus `secondary`. With `--target scores`, each intent's value from
178
+ `labels-intent-scores.jsonl` is its soft target.
179
+ - **Optimization**: per-option binary cross-entropy with logits, AdamW, a fixed seed and CPU.
180
+ Validation applies sigmoid independently to each option; `val-scores.jsonl` stores rows as
181
+ `{id, gold, scores: {option: probability}}`; option probabilities are independent and do
182
+ not have to sum to one.
173
183
  - The epoch with the lowest validation negative log-likelihood is kept.
174
184
  - The checkpoint metadata records the dataset hashes, the config and the validation metrics.
175
185
  - **Calibration**: `minConfidence` and `minMargin` are chosen on validation to maximize
@@ -191,3 +201,30 @@ prompts written by an agent, not by the owner. VS Code terminal notifications
191
201
  - **Release**: the `.safetensors` and `.json` files are attached to a GitHub release. The
192
202
  installer's pins gain the new model ID, revision, `domain: "harness-routing-v1"` and both
193
203
  SHA-256 values. Until every rollout gate passes, the router default stays `off`.
204
+
205
+ ## Evaluating a version over time
206
+
207
+ Run `scripts/system-one-curves.js` with a version directory, one or more validation score
208
+ files, an optional matching set of holdout score files, a history JSONL file and an output
209
+ directory. Each score row has `{id, gold, scores: {option: probability}}`. Options are
210
+ scored independently: log loss, Brier score and 10-bin ECE use every option-row pair, while
211
+ the confidence curve measures top-choice accuracy as its score threshold sweeps from 0 to 1.
212
+ The report also keeps reliability bins and five score quantiles per option.
213
+
214
+ ```mermaid
215
+ flowchart LR
216
+ V[Validation scores] --> C[Compare AUC, log loss and ECE]
217
+ H[Old holdout scores] --> F{Checked floor has no regression?}
218
+ C --> P{Candidate no worse on all curves?}
219
+ F --> P
220
+ P -->|yes| Promote[Promote]
221
+ P -->|no, two consecutive declines| Rollback[Rollback]
222
+ P -->|otherwise| Hold[Hold]
223
+ ```
224
+
225
+ Promotion requires the candidate to tie or improve the previous version on coverage-accuracy
226
+ area, log loss and ECE, and a checked old-holdout floor with no regression. Missing holdout
227
+ scores leave the floor unknown and block promotion. A rollback requires two consecutive
228
+ history comparisons where the active trend is dominated across those same curves. The
229
+ verdict is based on the whole curve; System One scores remain reference confidence, not
230
+ absolute answers.
@@ -101,6 +101,25 @@ Existing sessions may contain `budget.state = "budget-exhausted"`, old counters,
101
101
 
102
102
  Starting a fresh session remains the cleanest way to discard old evidence, but it is no longer required to recover from numeric budget exhaustion.
103
103
 
104
+ ## Agent hand-off files
105
+
106
+ When one agent hands another a work order, the file is generated by `scripts/handoff-file.js` so the format cannot drift, and its first bytes are a short YAML header that System One reads as its only input (#409 L0). The YAML subset is flat scalars and flat lists; the generator and parser are dependency-free. Keep the header within 2 KB.
107
+
108
+ ```yaml
109
+ ---
110
+ harness-handoff: 1
111
+ kind: implement
112
+ title: Cache fix
113
+ summary: Keep the read cache warm across restarts
114
+ writes: [a.js, b.js]
115
+ gate: node --test passes
116
+ report: reports/R.md
117
+ ---
118
+ ```
119
+
120
+ - `new --kind <implement|test|review|design|question|answer> --title "<text>" --summary "<≤200 chars>" --out <file.md> [--writes a,b] [--gate "<text>"] [--report <path>]` writes the header plus empty `## Scope anchor`, `## Task`, `## Write-set`, `## Verification` and `## Report` sections and a trailing pending-status comment.
121
+ - `header <file.md>` prints the header as JSON; `check <file.md>` validates the kind enum, the ≤ 200-character summary, the ≤ 2 KB header and unknown keys. Both read at most the first 2 KB and fail clearly when the header is absent or invalid.
122
+
104
123
  ## Testing contract
105
124
 
106
125
  Regression tests **MUST** prove:
@@ -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.48.0
7
+ version: 0.52.0
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -155,7 +155,8 @@ function activeExecutionFor(persisted, plan) {
155
155
  function printLabelContract() {
156
156
  console.log('\n=> TURN LABEL LINE (MUST, EVERY TURN — short answers, lookups and trivial edits included):');
157
157
  console.log(' - The last line of your final message MUST be one hidden label line with your own post-work judgement, not a copy of the router tier above:');
158
- console.log(' <!-- harness-label {"v":1,"validity":"actionable|invalid","contextDependent":true|false,"tier":"tier1|tier2|tier3|null","intents":["up to 3 of explain,discuss,git,fix,edit,feature,refactor,review,test,docs,plan,investigate"],"workflow":"strategy id or null","skills":["skills used"]} -->');
158
+ console.log(' <!-- harness-label {"v":1,"validity":"actionable|invalid","tier":"tier1|tier2|tier3|null","intents":["up to 3 of explain,discuss,git,fix,edit,feature,refactor,review,test,docs,plan,investigate"],"workflow":"strategy id or null","skills":["skills used"]} -->');
159
+ console.log(' - invalid means the prompt cannot be understood from its own text and needs conversation context; agent-written dispatches and worker instructions are ordinary prompts.');
159
160
  console.log(' - tier1: answer, lookup, status or git operation with no code change; tier2: bounded change; tier3: new feature, refactor, redefinition or cross-component work. Use null only when validity is invalid.');
160
161
  console.log(' - It is invisible in rendered Markdown and records local training data; it never gates routing.');
161
162
  }
@@ -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 };