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
@@ -1,8 +1,11 @@
1
1
  'use strict';
2
2
  const fs = require('node:fs');
3
+ const os = require('node:os');
3
4
  const path = require('node:path');
5
+ const { createHash } = require('node:crypto');
4
6
  const { spawnSync } = require('node:child_process');
5
- const { validateRequest } = require('./contract');
7
+ const { createRequest, validateRequest, validateResponse } = require('./contract');
8
+ const { STAGES, validateVersionManifest } = require('./manifest');
6
9
  // Upstream cua_s1 source revision documented in docs/system-one-routing.md.
7
10
  const PINNED_CUA_S1_REVISION = 'b7f7e2d8714609853a29c7d049140bc46aec0954';
8
11
  const ADAPTER = path.join(__dirname, 'cua_adapter.py');
@@ -14,6 +17,9 @@ const label = value => typeof value === 'string' && value.length > 0 && value.le
14
17
  const adapterName = value => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}\.py$/.test(value);
15
18
  // Thresholds calibrated on validation for this checkpoint (docs/system-one-training.md).
16
19
  const inRange = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi;
20
+ const LIVE_STAGES = STAGES;
21
+ const SAFE_ID = /^[a-z0-9._-]{1,80}$/;
22
+ const sha256 = value => createHash('sha256').update(value).digest('hex');
17
23
  // secondaryThreshold is optional and belongs to intent checkpoints (docs/system-one-intent.md#scoring).
18
24
  const validAcceptance = a => (exact(a, ['minConfidence', 'minMargin']) || (exact(a, ['minConfidence', 'minMargin', 'secondaryThreshold']) && inRange(a.secondaryThreshold, 0.05, 0.5)))
19
25
  && inRange(a.minConfidence, 0.5, 0.99) && inRange(a.minMargin, 0, 0.9);
@@ -112,4 +118,92 @@ function provenance(manifestPath) {
112
118
  try { return { status: 'recorded', provenance: validateProvenance(result.value) }; }
113
119
  catch (_) { return unavailable('provider-json'); }
114
120
  }
115
- module.exports = { score, scoreAsync, runProvider, validateManifest, readManifest, provenance, validateProvenance, decisionPolicy, PINNED_CUA_S1_REVISION };
121
+
122
+ function liveHome(env) {
123
+ return env.HARNESS_SYSTEM_ONE_HOME || path.join(os.homedir(), '.agents', 'harness-everything', 'system-one');
124
+ }
125
+ function readableFile(dir, name, extension) {
126
+ if (typeof name !== 'string' || !/^[A-Za-z0-9._-]+$/.test(name) || path.basename(name) !== name
127
+ || name === '.' || name === '..' || path.extname(name) !== extension) return null;
128
+ const file = path.join(dir, name);
129
+ try {
130
+ const stat = fs.lstatSync(file);
131
+ return stat.isFile() && !stat.isSymbolicLink() ? file : null;
132
+ } catch (_) { return null; }
133
+ }
134
+ function readActive(env = process.env) {
135
+ try {
136
+ const home = liveHome(env);
137
+ if (!path.isAbsolute(home)) return null;
138
+ const pointerPath = path.join(home, 'active.json');
139
+ const pointerStat = fs.lstatSync(pointerPath);
140
+ if (!pointerStat.isFile() || pointerStat.isSymbolicLink() || pointerStat.size > 65536) return null;
141
+ const pointer = JSON.parse(fs.readFileSync(pointerPath, 'utf8'));
142
+ if (!exact(pointer, ['schemaVersion', 'version', 'dir', 'previous', 'activatedAt']) || pointer.schemaVersion !== 1
143
+ || typeof pointer.version !== 'string' || !SAFE_ID.test(pointer.version)
144
+ || typeof pointer.dir !== 'string' || !path.isAbsolute(pointer.dir)
145
+ || !(pointer.previous === null || (typeof pointer.previous === 'string' && SAFE_ID.test(pointer.previous)))
146
+ || typeof pointer.activatedAt !== 'string' || !Number.isFinite(Date.parse(pointer.activatedAt))) return null;
147
+ const dir = pointer.dir;
148
+ const dirStat = fs.lstatSync(dir);
149
+ if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) return null;
150
+ const manifestPath = path.join(dir, 'manifest.json');
151
+ const manifestStat = fs.lstatSync(manifestPath);
152
+ if (!manifestStat.isFile() || manifestStat.isSymbolicLink() || manifestStat.size > 131072) return null;
153
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
154
+ validateVersionManifest(manifest, pointer.version);
155
+ const loadedStages = {};
156
+ for (const stageName of LIVE_STAGES) {
157
+ const stage = manifest.stages[stageName];
158
+ const weightsPath = readableFile(dir, stage.weights, '.safetensors');
159
+ const configPath = readableFile(dir, stage.config, '.json');
160
+ if (!weightsPath || !configPath || sha256(fs.readFileSync(weightsPath)) !== stage.sha256) return null;
161
+ loadedStages[stageName] = { ...stage, referenceOnly: stage.referenceOnly ?? [], weightsPath, configPath,
162
+ configSha256: sha256(fs.readFileSync(configPath)) };
163
+ }
164
+ const fingerprint = sha256(`${pointer.version}\0${dir}\0${LIVE_STAGES.map(stage => `${stage}\0${loadedStages[stage].sha256}\0${loadedStages[stage].configSha256}`).join('\0')}`);
165
+ const python = env.HARNESS_SYSTEM_ONE_PYTHON || env.PYTHON || path.join(home, 'venv', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
166
+ return { home, pointerPath, pointer, version: pointer.version, dir, manifest, stages: loadedStages,
167
+ fingerprint, python, sha256: loadedStages.tier.sha256.slice(0, 16) };
168
+ } catch (_) { return null; }
169
+ }
170
+ async function scoreLive(prompt, env = process.env, catalogs, scoreStage = (stage, request, active) =>
171
+ require('./resident').scoreActiveStage(active, stage, request)) {
172
+ const active = readActive(env);
173
+ if (!active || typeof prompt !== 'string' || !catalogs) return null;
174
+ const stageScores = { validity: null, intent: null, tier: null };
175
+ for (const stage of LIVE_STAGES) {
176
+ const catalog = catalogs[stage];
177
+ const ids = active.stages[stage].options;
178
+ // A packaged intent checkpoint may omit the non-selectable unclassified option (cycle/package.js legacyOptions).
179
+ const manifestIds = ids.filter(id => id !== 'unclassified');
180
+ const expectedIds = Array.isArray(catalog) ? catalog.map(option => option?.id)
181
+ .filter(id => !(stage === 'validity' && id === 'actionable')
182
+ && !((stage === 'intent' || stage === 'tier') && id === 'unclassified')) : [];
183
+ if (!Array.isArray(catalog) || manifestIds.length !== expectedIds.length
184
+ || manifestIds.some((id, index) => id !== expectedIds[index])) return null;
185
+ const options = ids.map(id => catalog.find(option => option?.id === id));
186
+ let result;
187
+ let request;
188
+ try {
189
+ request = createRequest(stage, prompt, options, stage === 'validity' ? { minOptions: 1 } : undefined);
190
+ result = await scoreStage(stage, request, active);
191
+ } catch (_) { result = null; }
192
+ if (!result || result.status !== 'scored' || !validateResponse(request, result.response)) {
193
+ if (stage === 'validity') break;
194
+ continue;
195
+ }
196
+ stageScores[stage] = Object.fromEntries(result.response.scores
197
+ .filter(score => !(stage === 'validity' && score.id === 'actionable'))
198
+ .map(score => [score.id, score.probability]));
199
+ if (stage === 'validity' && (active.stages.validity.referenceOnly.includes('invalid')
200
+ || stageScores.validity.invalid >= active.stages.validity.thresholds.invalid)) break;
201
+ }
202
+ const current = readActive(env);
203
+ if (!current || current.fingerprint !== active.fingerprint) return null;
204
+ return { version: active.version, sha256: active.sha256, stageScores,
205
+ thresholds: Object.fromEntries(LIVE_STAGES.map(stage => [stage, { ...active.stages[stage].thresholds }])),
206
+ referenceOnly: Object.fromEntries(LIVE_STAGES.map(stage => [stage, [...active.stages[stage].referenceOnly]])) };
207
+ }
208
+ module.exports = { score, scoreAsync, runProvider, validateManifest, readManifest, provenance, validateProvenance,
209
+ decisionPolicy, readActive, scoreLive, PINNED_CUA_S1_REVISION };
@@ -123,6 +123,51 @@ function start(manifest, files, deps) {
123
123
  }
124
124
  return unavailable('provider-starting');
125
125
  }
126
+ function activeStateFiles(active) {
127
+ const base = path.join(path.dirname(active.pointerPath), `system-one-active-resident-${active.fingerprint.slice(0, 16)}`);
128
+ return { state: `${base}.json`, lock: `${base}.starting` };
129
+ }
130
+ function defaultActiveCommand(active) {
131
+ return [active.python, [adapterPath({}), '--serve-active']];
132
+ }
133
+ function startActive(active, files, deps) {
134
+ const lock = lockInfo(files.lock);
135
+ if (lock && lock.ageMs < LOCK_TTL_MS) return unavailable(lock.failed ? 'provider-unavailable' : 'provider-starting');
136
+ if (lock) { try { fs.unlinkSync(files.lock); } catch (_) { /* another caller replaced it */ } }
137
+ try { fs.writeFileSync(files.lock, JSON.stringify({ createdAt: Date.now() }), { flag: 'wx', mode: 0o600 }); }
138
+ catch (_) { return unavailable('provider-starting'); }
139
+ let child = null;
140
+ try {
141
+ const [exe, prefix] = (deps.command || defaultActiveCommand)(active);
142
+ child = spawn(exe, [...prefix, active.pointerPath, files.state, files.lock, active.fingerprint],
143
+ { detached: true, stdio: 'ignore', windowsHide: true, shell: false,
144
+ env: { ...process.env, HARNESS_SYSTEM_ONE_NODE: process.execPath } });
145
+ child.on('error', () => { /* recorded synchronously below: a failed spawn has no pid */ });
146
+ child.unref();
147
+ } catch (_) { child = null; }
148
+ if (!child || !child.pid) {
149
+ try { fs.writeFileSync(files.lock, JSON.stringify({ createdAt: Date.now(), failed: 'spawn-failed' })); } catch (_) { /* best effort */ }
150
+ return unavailable('provider-unavailable');
151
+ }
152
+ return unavailable('provider-starting');
153
+ }
154
+ function activeOutcome(result, files, state, active, deps) {
155
+ if (result.reply) {
156
+ if (result.reply.ok === true && Object.hasOwn(result.reply, 'response')) return { status: 'scored', response: result.reply.response };
157
+ if (result.reply.reason === 'artifact-changed') removeIfSame(files.state, state);
158
+ return unavailable(result.reply.ok === false ? 'provider-unavailable' : 'provider-json');
159
+ }
160
+ if (result.error === 'refused') { removeIfSame(files.state, state); return startActive(active, files, deps); }
161
+ return unavailable({ timeout: 'provider-timeout', limit: 'provider-output-limit', json: 'provider-json' }[result.error] || 'provider-unavailable');
162
+ }
163
+ async function scoreActiveStage(active, stage, request, deps = {}) {
164
+ validateRequest(request);
165
+ if (!['validity', 'intent', 'tier'].includes(stage)) return unavailable('provider-config');
166
+ const files = activeStateFiles(active);
167
+ const state = liveState(files);
168
+ if (!state) return startActive(active, files, deps);
169
+ return activeOutcome(await callAsync(state.port, { token: state.token, op: 'score', stage, request }), files, state, active, deps);
170
+ }
126
171
  // Returns a live server state, or null after removing state that provably belongs to a dead server.
127
172
  function liveState(files) {
128
173
  const state = readState(files.state);
@@ -202,4 +247,5 @@ if (require.main === module) {
202
247
  if (op === 'stop') stop(manifest, manifestPath);
203
248
  process.stdout.write(`${JSON.stringify(status(manifest, manifestPath))}\n`);
204
249
  }
205
- module.exports = { stateFiles, readState, callSync, callAsync, score, scoreAsync, ensureReady, status, stop, defaultCommand, LOCK_TTL_MS, CALL_TIMEOUT_MS };
250
+ module.exports = { stateFiles, readState, callSync, callAsync, score, scoreAsync, scoreActiveStage,
251
+ activeStateFiles, defaultActiveCommand, ensureReady, status, stop, defaultCommand, LOCK_TTL_MS, CALL_TIMEOUT_MS };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
  const { createRequest, decide } = require('./contract');
3
3
  const provider = require('./provider');
4
+ const { prepareHandoffInput } = require('./handoff-input');
4
5
  const TIER_OPTIONS = Object.freeze([
5
6
  { id: 'tier1', text: 'A small bounded edit or operation with clear scope.' },
6
7
  { id: 'tier2', text: 'Implementation or bug fix needing iterative testing.' },
@@ -9,6 +10,84 @@ const TIER_OPTIONS = Object.freeze([
9
10
  ].map(Object.freeze));
10
11
  const LABELS = { tier1: 'Tier 1 (Trivial)', tier2: 'Tier 2 (Standard Task)', tier3: 'Tier 3 (Macro Task)' };
11
12
  const RANK = { tier1: 1, tier2: 2, tier3: 3 };
13
+ const VALIDITY_OPTIONS = Object.freeze([
14
+ { id: 'actionable', text: 'The current prompt contains an actionable request.' },
15
+ { id: 'invalid', text: 'The request needs conversation context to understand.' },
16
+ ].map(Object.freeze));
17
+ const isProbability = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;
18
+ function liveOptions() {
19
+ const { INTENT_OPTIONS } = require('./catalogs');
20
+ return { validity: VALIDITY_OPTIONS, intent: INTENT_OPTIONS, tier: TIER_OPTIONS };
21
+ }
22
+ function exactScores(value, ids) {
23
+ return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === ids.length
24
+ && ids.every(id => Object.hasOwn(value, id) && isProbability(value[id]));
25
+ }
26
+ function routeLive(input, result) {
27
+ if (!result || typeof result.version !== 'string' || !result.version
28
+ || typeof result.sha256 !== 'string' || !/^[a-f0-9]{16}$/.test(result.sha256)) {
29
+ return { tier: input.tier, reference: { available: false } };
30
+ }
31
+ const options = liveOptions();
32
+ const stages = result.stageScores || {};
33
+ const thresholds = result.thresholds || {};
34
+ const referenceOnly = Object.fromEntries(['validity', 'intent', 'tier'].map(stage => [stage,
35
+ Array.isArray(result.referenceOnly?.[stage]) ? result.referenceOnly[stage].filter(id => typeof id === 'string') : []]));
36
+ const validityScores = exactScores(stages.validity, ['invalid'])
37
+ && isProbability(thresholds.validity?.invalid) ? { invalid: stages.validity.invalid } : null;
38
+ const validity = validityScores === null || referenceOnly.validity.includes('invalid') ? 'abstain'
39
+ : validityScores.invalid >= thresholds.validity.invalid ? 'invalid' : 'actionable';
40
+ const intentCatalogIds = options.intent.map(option => option.id).filter(id => id !== 'unclassified');
41
+ // A packaged checkpoint may omit the non-selectable unclassified option from its intent scores.
42
+ const intentScores = stages.intent && typeof stages.intent === 'object' && !Array.isArray(stages.intent)
43
+ ? Object.fromEntries(Object.entries(stages.intent).filter(([id]) => id !== 'unclassified')) : null;
44
+ const intents = validity === 'actionable' && exactScores(intentScores, intentCatalogIds)
45
+ && intentCatalogIds.every(id => isProbability(thresholds.intent?.[id])) ? intentScores : null;
46
+ const tierIds = ['tier1', 'tier2', 'tier3'];
47
+ const tierScores = validity === 'actionable' && exactScores(stages.tier, tierIds)
48
+ && tierIds.every(id => isProbability(thresholds.tier?.[id])) ? stages.tier : null;
49
+ const selectedIntents = intents ? intentCatalogIds.filter(id => !referenceOnly.intent.includes(id) && intents[id] >= thresholds.intent[id])
50
+ .sort((a, b) => (intents[b] - intents[a]) || (intentCatalogIds.indexOf(a) - intentCatalogIds.indexOf(b))).slice(0, 3) : [];
51
+ const rankedTiers = tierScores ? tierIds.filter(id => !referenceOnly.tier.includes(id)).sort((a, b) => (tierScores[b] - tierScores[a])
52
+ || (tierIds.indexOf(a) - tierIds.indexOf(b))) : [];
53
+ const bestTier = rankedTiers[0];
54
+ const selectedTier = bestTier && tierScores[bestTier] >= thresholds.tier[bestTier]
55
+ && (rankedTiers.length === 1 || tierScores[bestTier] !== tierScores[rankedTiers[1]]) ? bestTier : null;
56
+ const systemOne = {
57
+ version: result.version,
58
+ sha256: result.sha256,
59
+ mode: 'live',
60
+ inputEnrichment: { handoffFiles: Number.isSafeInteger(result.inputEnrichment?.handoffFiles)
61
+ ? result.inputEnrichment.handoffFiles : 0 },
62
+ referenceOnly,
63
+ validity: validityScores,
64
+ intents,
65
+ tier: tierScores,
66
+ decision: { validity, intents: selectedIntents, tier: selectedTier },
67
+ };
68
+ const top = (stage, scores) => scores ? Object.entries(scores).sort((a, b) => b[1] - a[1]
69
+ || Object.keys(scores).indexOf(a[0]) - Object.keys(scores).indexOf(b[0])).slice(0, 3)
70
+ .map(([id, probability]) => ({ stage, id, probability })) : [];
71
+ const referenceOnlyOptions = Object.entries(referenceOnly).flatMap(([stage, ids]) => ids
72
+ .filter(id => isProbability(stages[stage]?.[id]))
73
+ .map(id => ({ stage, id, probability: stages[stage][id] })));
74
+ const reference = { version: result.version, sha256: result.sha256,
75
+ topOptions: [...top('validity', validityScores), ...top('intent', intents), ...top('tier', tierScores)],
76
+ referenceOnlyOptions };
77
+ const floorValid = input.floor == null || Object.hasOwn(RANK, input.floor);
78
+ const belowFloor = selectedTier && input.floor != null && RANK[selectedTier] < RANK[input.floor];
79
+ const applied = floorValid && validity === 'actionable' && selectedTier !== null && !input.explicit && !belowFloor;
80
+ return { tier: applied ? LABELS[selectedTier] : input.tier, systemOne, reference, applied };
81
+ }
82
+ async function prescoreLive(prompt, env = process.env, score = provider.scoreLive, cwd = process.cwd()) {
83
+ if (env.HARNESS_SYSTEM_ONE_MODE !== 'live') return null;
84
+ try {
85
+ const prepared = prepareHandoffInput(prompt, cwd);
86
+ const result = await score(prepared.input, env, liveOptions());
87
+ return result ? { ...result, inputEnrichment: { handoffFiles: prepared.handoffFiles } } : result;
88
+ }
89
+ catch (_) { return null; }
90
+ }
12
91
  // input.floor is the deterministic structural minimum; a scorer may raise the tier, never lower it below the floor.
13
92
  function selectTier(input, env = process.env, scorer = provider.score) {
14
93
  const mode = env.HARNESS_SYSTEM_ONE_MODE || 'off';
@@ -50,4 +129,4 @@ async function prescoreTier(prompt, env = process.env, scoreAsync = provider.sco
50
129
  return result;
51
130
  };
52
131
  }
53
- module.exports = { selectTier, prescoreTier, TIER_OPTIONS };
132
+ module.exports = { selectTier, prescoreTier, prescoreLive, routeLive, TIER_OPTIONS, VALIDITY_OPTIONS };
@@ -344,15 +344,24 @@ function run(userPrompt, context, options = {}) {
344
344
  }
345
345
  }
346
346
 
347
- const { selectTier } = require('./system-one/router');
347
+ const { selectTier, routeLive } = require('./system-one/router');
348
348
  const structuralFloor = hasMacroSignal ? 'tier3'
349
349
  : !isTrivialDocsEdit && hasMultipleTasks && hasMultipleSentences ? 'tier2' : null;
350
- const semantic = selectTier({ prompt: userPrompt, tier: recommendedTier, floor: structuralFloor,
351
- explicit: profileLookup || Boolean(detectExplicitStrategy(userPrompt, detectFableModel(userPrompt))) }, process.env, options.systemOneScorer || undefined);
350
+ const routeInput = { prompt: userPrompt, tier: recommendedTier, floor: structuralFloor,
351
+ explicit: profileLookup || Boolean(detectExplicitStrategy(userPrompt, detectFableModel(userPrompt))) };
352
+ const liveMode = process.env.HARNESS_SYSTEM_ONE_MODE === 'live';
353
+ const semantic = liveMode ? routeLive(routeInput, options.systemOneResult)
354
+ : selectTier(routeInput, process.env, options.systemOneScorer || undefined);
352
355
  if (semantic.diagnostic) console.log(`\n=> SYSTEM ONE: ${JSON.stringify(semantic.diagnostic)}`);
353
- if (semantic.diagnostic?.applied) {
356
+ if (liveMode && semantic.reference?.available === false) {
357
+ console.log('\n=> SYSTEM ONE REFERENCE CONFIDENCE unavailable; lexical routing retained.');
358
+ } else if (liveMode && semantic.reference) {
359
+ console.log(`\n=> SYSTEM ONE REFERENCE CONFIDENCE (not a verdict): ${JSON.stringify(semantic.reference)}`);
360
+ }
361
+ const systemOneApplied = liveMode ? semantic.applied : semantic.diagnostic?.applied;
362
+ if (systemOneApplied) {
354
363
  recommendedTier = semantic.tier;
355
- rationale = 'System One selected a tier from the fixed catalog; deterministic policy remains authoritative.';
364
+ rationale = 'System One reference confidence informed the default tier; deterministic routing constraints remain authoritative.';
356
365
  reasonCodes.splice(loadedConfig.reasonCodes.length);
357
366
  addReason(reasonCodes, 'system-one-tier');
358
367
  }
@@ -466,6 +475,8 @@ function run(userPrompt, context, options = {}) {
466
475
  },
467
476
  });
468
477
 
478
+ if (semantic.systemOne) contract.workflowPlan.systemOne = semantic.systemOne;
479
+
469
480
  if (knowledgeSignals.length > 0) {
470
481
  console.log(`\n=> KNOWLEDGE SIGNALS (STEP INPUT ONLY): ${knowledgeSignals.join(', ')}`);
471
482
  console.log(' These normalized prompt signals help compose requirement steps; they do not select or load documents.');
@@ -508,7 +519,11 @@ async function main(prompt, context) {
508
519
  if (['shadow', 'prefer'].includes(process.env.HARNESS_SYSTEM_ONE_MODE)) {
509
520
  try { systemOneScorer = await require('./system-one/router').prescoreTier(prompt); } catch (_) { /* the sync path still scores */ }
510
521
  }
511
- run(prompt, context, { systemOneScorer });
522
+ let systemOneResult = null;
523
+ if (process.env.HARNESS_SYSTEM_ONE_MODE === 'live') {
524
+ try { systemOneResult = await require('./system-one/router').prescoreLive(prompt); } catch (_) { /* lexical route remains available */ }
525
+ }
526
+ run(prompt, context, { systemOneScorer, systemOneResult });
512
527
  }
513
528
 
514
529
  if (require.main === module) {
package/sbom.cdx.json CHANGED
@@ -2,23 +2,23 @@
2
2
  "$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.7",
5
- "serialNumber": "urn:uuid:b8bf6ee5-f127-5813-a3c9-1284d50c66c0",
5
+ "serialNumber": "urn:uuid:afabb965-abc6-52fb-92e7-1220041eadbf",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-11T03:11:38.812Z",
8
+ "timestamp": "2026-11-18T03:27:42.456Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "0.51.0"
13
+ "version": "0.53.0"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@0.51.0",
18
+ "bom-ref": "pkg:npm/harness-everything@0.53.0",
19
19
  "name": "harness-everything",
20
- "version": "0.51.0",
21
- "purl": "pkg:npm/harness-everything@0.51.0"
20
+ "version": "0.53.0",
21
+ "purl": "pkg:npm/harness-everything@0.53.0"
22
22
  }
23
23
  },
24
24
  "components": [
@@ -2033,7 +2033,7 @@
2033
2033
  ]
2034
2034
  },
2035
2035
  {
2036
- "ref": "pkg:npm/harness-everything@0.51.0",
2036
+ "ref": "pkg:npm/harness-everything@0.53.0",
2037
2037
  "dependsOn": [
2038
2038
  "pkg:npm/%40commitlint/cli@19.8.1",
2039
2039
  "pkg:npm/%40commitlint/config-conventional@19.8.1",
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { execFileSync } = require('node:child_process');
5
+ const { TextDecoder } = require('node:util');
6
+
7
+ const ALLOWED_PREFIXES = [
8
+ 'docs/',
9
+ 'benchmarks/results/',
10
+ '.agents/harness-everything/errors/',
11
+ ];
12
+
13
+ function parsePaths(bytes) {
14
+ if (!Buffer.isBuffer(bytes) || bytes.length === 0 || bytes[bytes.length - 1] !== 0) return null;
15
+ let text;
16
+ try {
17
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
18
+ } catch {
19
+ return null;
20
+ }
21
+ const paths = text.slice(0, -1).split('\0');
22
+ if (!paths.length || paths.some(file => !file || file.startsWith('/') || file.includes('\\') ||
23
+ file.split('/').some(part => !part || part === '.' || part === '..'))) return null;
24
+ return paths;
25
+ }
26
+
27
+ function isAllowed(file) {
28
+ return file === 'CHANGELOG.md' || ALLOWED_PREFIXES.some(prefix => file.startsWith(prefix));
29
+ }
30
+
31
+ function classifyPaths(bytes) {
32
+ const paths = parsePaths(bytes);
33
+ return paths && paths.every(isAllowed) ? 'docs-only' : 'full';
34
+ }
35
+
36
+ function classifyChangeSet(eventName, baseSha, headSha, options = {}) {
37
+ if (eventName !== 'pull_request' ||
38
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(baseSha || '') ||
39
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(headSha || '')) return 'full';
40
+
41
+ const cwd = options.cwd || process.cwd();
42
+ const runGit = options.runGit || ((args, settings) => execFileSync('git', args, settings));
43
+ try {
44
+ const mergeBase = runGit(['merge-base', baseSha, headSha], { cwd, windowsHide: true }).toString('ascii').trim();
45
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(mergeBase)) return 'full';
46
+ // Disabling rename detection makes both endpoints part of the path set.
47
+ const paths = runGit(['diff', '--no-renames', '--name-only', '-z', mergeBase, headSha], { cwd, windowsHide: true });
48
+ return classifyPaths(paths);
49
+ } catch {
50
+ return 'full';
51
+ }
52
+ }
53
+
54
+ if (require.main === module) {
55
+ const [, , eventName, baseSha, headSha] = process.argv;
56
+ process.stdout.write(`${classifyChangeSet(eventName, baseSha, headSha)}\n`);
57
+ }
58
+
59
+ module.exports = { classifyPaths, classifyChangeSet };
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Agents hand each other Markdown work orders, and script-generating them keeps
5
+ // the format from drifting. The file begins with a tiny YAML front matter
6
+ // header; System One reads only that header as input (#409 L0). The YAML subset
7
+ // is flat scalars and flat lists, emitted and parsed here with no dependency.
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ const HEADER_LIMIT = 2048;
13
+ const KINDS = ['implement', 'test', 'review', 'design', 'question', 'answer'];
14
+ const KEY_ORDER = ['harness-handoff', 'kind', 'title', 'summary', 'writes', 'gate', 'report'];
15
+ const RESERVED = new Set(['true', 'false', 'null', 'yes', 'no', 'on', 'off', '~', 'nan', 'inf']);
16
+
17
+ const BODY = [
18
+ '## Scope anchor',
19
+ '',
20
+ '## Task',
21
+ '',
22
+ '## Write-set',
23
+ '',
24
+ '## Verification',
25
+ '',
26
+ '## Report',
27
+ '',
28
+ '<!-- STATUS: <pending> -->',
29
+ '',
30
+ ].join('\n');
31
+
32
+ function fail(message) {
33
+ throw new Error(message);
34
+ }
35
+
36
+ function usage() {
37
+ const error = new Error([
38
+ 'Usage:',
39
+ ' handoff-file.js new --kind <implement|test|review|design|question|answer>',
40
+ ' --title "<text>" --summary "<text>" --out <file.md>',
41
+ ' [--writes a,b] [--gate "<text>"] [--report <path>]',
42
+ ' handoff-file.js header <file.md>',
43
+ ' handoff-file.js check <file.md>',
44
+ '',
45
+ ].join('\n'));
46
+ error.code = 'HANDOFF_USAGE';
47
+ throw error;
48
+ }
49
+
50
+ function plainSafe(value) {
51
+ if (!value || value !== value.trim()) return false;
52
+ if (RESERVED.has(value.toLowerCase())) return false;
53
+ return /^[A-Za-z0-9_/][A-Za-z0-9 _.@/()+-]*$/.test(value);
54
+ }
55
+
56
+ function yamlScalar(value) {
57
+ const s = String(value);
58
+ if (plainSafe(s)) return s;
59
+ return `"${s
60
+ .replace(/\\/g, '\\\\')
61
+ .replace(/"/g, '\\"')
62
+ .replace(/\n/g, '\\n')
63
+ .replace(/\r/g, '\\r')
64
+ .replace(/\t/g, '\\t')}"`;
65
+ }
66
+
67
+ function unquote(raw) {
68
+ const s = raw.trim();
69
+ if (s.length < 2 || s[0] !== '"' || s[s.length - 1] !== '"') return s;
70
+ let out = '';
71
+ for (let i = 1; i < s.length - 1; i += 1) {
72
+ if (s[i] !== '\\') {
73
+ out += s[i];
74
+ continue;
75
+ }
76
+ const next = s[i + 1];
77
+ if (next === 'n') out += '\n';
78
+ else if (next === 'r') out += '\r';
79
+ else if (next === 't') out += '\t';
80
+ else out += next === undefined ? '\\' : next;
81
+ i += 1;
82
+ }
83
+ return out;
84
+ }
85
+
86
+ function parseValue(raw) {
87
+ if (raw === undefined) return '';
88
+ const s = raw.trim();
89
+ if (s.startsWith('[') && s.endsWith(']')) {
90
+ const inner = s.slice(1, -1).trim();
91
+ return inner === '' ? [] : inner.split(',').map(unquote);
92
+ }
93
+ return unquote(s);
94
+ }
95
+
96
+ function renderHeader(header) {
97
+ const lines = ['---'];
98
+ for (const key of KEY_ORDER) {
99
+ if (!(key in header)) continue;
100
+ const value = header[key];
101
+ const rendered = key === 'writes' ? `[${value.map(yamlScalar).join(', ')}]` : yamlScalar(value);
102
+ lines.push(`${key}: ${rendered}`);
103
+ }
104
+ lines.push('---');
105
+ return lines.join('\n');
106
+ }
107
+
108
+ function parseHeader(file) {
109
+ let text;
110
+ try {
111
+ const fd = fs.openSync(file, 'r');
112
+ const buf = Buffer.alloc(HEADER_LIMIT);
113
+ const read = fs.readSync(fd, buf, 0, HEADER_LIMIT, 0);
114
+ fs.closeSync(fd);
115
+ text = buf.subarray(0, read).toString('utf8');
116
+ } catch (err) {
117
+ fail(`cannot read ${file}: ${err.message}`);
118
+ }
119
+ if (!/^---(\r?\n|$)/.test(text)) fail(`${file}: no handoff header (file must start with '---')`);
120
+ const block = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
121
+ if (!block) fail(`${file}: header exceeds ${HEADER_LIMIT} bytes or is unterminated`);
122
+ if (Buffer.byteLength(block[0], 'utf8') > HEADER_LIMIT) {
123
+ fail(`${file}: header exceeds ${HEADER_LIMIT} bytes`);
124
+ }
125
+ const header = {};
126
+ for (const line of block[1].split(/\r?\n/)) {
127
+ if (line === '') continue;
128
+ const kv = /^([A-Za-z][A-Za-z0-9-]*):(?:[ ](.*))?$/.exec(line);
129
+ if (!kv) fail(`${file}: malformed header line ${JSON.stringify(line)}`);
130
+ if (kv[1] in header) fail(`${file}: duplicate header key ${kv[1]}`);
131
+ header[kv[1]] = parseValue(kv[2]);
132
+ }
133
+ return header;
134
+ }
135
+
136
+ function normalize(header) {
137
+ const out = {};
138
+ for (const key of KEY_ORDER) {
139
+ if (key in header) out[key] = key === 'harness-handoff' ? Number(header[key]) : header[key];
140
+ }
141
+ return out;
142
+ }
143
+
144
+ function validate(file, header) {
145
+ const unknown = Object.keys(header).filter((key) => !KEY_ORDER.includes(key));
146
+ if (unknown.length) fail(`${file}: unknown header key(s): ${unknown.join(', ')}`);
147
+ if (Number(header['harness-handoff']) !== 1) fail(`${file}: harness-handoff must be 1`);
148
+ if (!KINDS.includes(header.kind)) fail(`${file}: kind must be one of ${KINDS.join('|')}`);
149
+ if (typeof header.title !== 'string' || header.title === '') fail(`${file}: title is required`);
150
+ if (typeof header.summary !== 'string' || header.summary === '') fail(`${file}: summary is required`);
151
+ if ([...header.summary].length > 200) fail(`${file}: summary must be at most 200 characters`);
152
+ if ('writes' in header && !Array.isArray(header.writes)) fail(`${file}: writes must be a list`);
153
+ for (const key of ['gate', 'report']) {
154
+ if (key in header && typeof header[key] !== 'string') fail(`${file}: ${key} must be a string`);
155
+ }
156
+ }
157
+
158
+ function loadHeader(file) {
159
+ const header = parseHeader(file);
160
+ validate(file, header);
161
+ return normalize(header);
162
+ }
163
+
164
+ function parseFlags(args, allowed) {
165
+ const opts = {};
166
+ for (let i = 0; i < args.length; i += 1) {
167
+ const flag = args[i];
168
+ if (!flag.startsWith('--')) fail(`unexpected argument ${JSON.stringify(flag)}`);
169
+ const name = flag.slice(2);
170
+ if (!allowed.includes(name)) fail(`unknown flag ${flag}`);
171
+ const value = args[i + 1];
172
+ if (value === undefined || value.startsWith('--')) fail(`${flag} requires a value`);
173
+ opts[name] = value;
174
+ i += 1;
175
+ }
176
+ return opts;
177
+ }
178
+
179
+ function createHandoff(args) {
180
+ const opts = parseFlags(args, ['kind', 'title', 'summary', 'out', 'writes', 'gate', 'report']);
181
+ for (const key of ['kind', 'title', 'summary', 'out']) {
182
+ if (!opts[key]) fail(`new requires --${key}`);
183
+ }
184
+ const header = { 'harness-handoff': 1, kind: opts.kind, title: opts.title, summary: opts.summary };
185
+ if (opts.writes !== undefined) {
186
+ // shortcut: a comma inside one write path splits it into two items, upgrade if a path may hold one
187
+ header.writes = opts.writes.split(',').map((item) => item.trim()).filter((item) => item !== '');
188
+ }
189
+ if (opts.gate !== undefined) header.gate = opts.gate;
190
+ if (opts.report !== undefined) header.report = opts.report;
191
+ validate(opts.out, header);
192
+ const rendered = renderHeader(header);
193
+ if (Buffer.byteLength(rendered, 'utf8') > HEADER_LIMIT) fail(`${opts.out}: header exceeds ${HEADER_LIMIT} bytes`);
194
+ const target = path.resolve(opts.out);
195
+ fs.mkdirSync(path.dirname(target), { recursive: true });
196
+ fs.writeFileSync(target, `${rendered}\n${BODY}`, 'utf8');
197
+ process.stdout.write(`${target}\n`);
198
+ }
199
+
200
+ function main() {
201
+ try {
202
+ const [command, ...rest] = process.argv.slice(2);
203
+ if (command === 'new') {
204
+ createHandoff(rest);
205
+ } else if (command === 'header' || command === 'check') {
206
+ const file = rest[0];
207
+ if (!file) fail(`${command} requires <file.md>`);
208
+ const header = loadHeader(file);
209
+ process.stdout.write(
210
+ command === 'header' ? `${JSON.stringify(header, null, 2)}\n` : `${file}: ok (kind=${header.kind})\n`,
211
+ );
212
+ } else {
213
+ usage();
214
+ }
215
+ } catch (error) {
216
+ process.stderr.write(error.code === 'HANDOFF_USAGE' ? error.message : `handoff-file: ${error.message}\n`);
217
+ process.exitCode = 1;
218
+ }
219
+ }
220
+
221
+ if (require.main === module) main();
222
+
223
+ module.exports = { loadHeader };
@@ -57,6 +57,10 @@ for (const name of fs.readdirSync(pluginSkillsRoot)) {
57
57
  if (!expected.has(name)) fs.rmSync(path.join(pluginSkillsRoot, name), { recursive: true, force: true });
58
58
  }
59
59
 
60
+ // The System One router uses the hand-off reader as a shared runtime module.
61
+ syncTree(path.join(ROOT, 'scripts', 'handoff-file.js'),
62
+ path.join(pluginRoot, 'scripts', 'handoff-file.js'));
63
+
60
64
  // The Claude hook definitions are host-specific, but their enforcement
61
65
  // scripts are shared. Package the scripts plus the small runtime libraries
62
66
  // they require so every OpenAI hook is self-contained under PLUGIN_ROOT.