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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/ci.yml +23 -0
- package/CHANGELOG.md +54 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
- package/ci/mechanism-2am-observations-session-import.test.js +4 -1
- package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
- package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
- package/ci/mechanism-338-opencode-async.test.js +20 -3
- package/ci/mechanism-34-observations.test.js +127 -23
- package/ci/mechanism-341-opencode-lane.test.js +7 -1
- package/ci/mechanism-349-ci-change-scope.test.js +260 -0
- package/ci/mechanism-397-cycle-import.test.js +399 -0
- package/ci/mechanism-397-host-acceptance.test.js +119 -0
- package/ci/mechanism-397-opencode-observations.test.js +1922 -0
- package/ci/mechanism-handoff-file.test.js +121 -0
- package/ci/mechanism-system-one-contract.test.js +9 -2
- package/ci/mechanism-system-one-curves.test.js +223 -0
- package/ci/mechanism-system-one-cycle.test.js +1204 -0
- package/ci/mechanism-system-one-evaluation.test.js +32 -5
- package/ci/mechanism-system-one-handoff-input.test.js +208 -0
- package/ci/mechanism-system-one-install.test.js +202 -77
- package/ci/mechanism-system-one-live.test.js +361 -0
- package/ci/mechanism-system-one-relevance.test.js +11 -1
- package/ci/mechanism-system-one-train.test.js +136 -53
- package/ci/system-one-adapter-test.py +331 -0
- package/ci/system-one-train-test.py +116 -24
- package/docs/adr/EVID-001.md +123 -0
- package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
- package/docs/governed-index.md +2 -0
- package/docs/platform-capabilities.md +13 -6
- package/docs/routing.md +2 -2
- package/docs/system-one-cycle.md +77 -0
- package/docs/system-one-observations.md +43 -11
- package/docs/system-one-routing.md +163 -115
- package/docs/system-one-suggestion-gates.md +6 -8
- package/docs/system-one-training.md +44 -7
- package/docs/workflow-runtime.md +19 -0
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/kernel-router.js +2 -1
- package/harness-everything/scripts/system-one/contract.js +19 -15
- package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/harness-everything/scripts/system-one/install.js +281 -113
- package/harness-everything/scripts/system-one/manifest.js +58 -0
- package/harness-everything/scripts/system-one/provider.js +96 -2
- package/harness-everything/scripts/system-one/resident.js +47 -1
- package/harness-everything/scripts/system-one/router.js +80 -1
- package/harness-everything/scripts/tier-router.js +21 -6
- package/hooks/scripts/lib/observations.js +48 -7
- package/opencode-plugin/README.md +22 -8
- package/opencode-plugin/index.mjs +424 -44
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +48 -7
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/scripts/handoff-file.js +223 -0
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
- package/sbom.cdx.json +7 -7
- package/scripts/ci-change-scope.js +59 -0
- package/scripts/handoff-file.js +223 -0
- package/scripts/sync-openai-plugin.js +4 -0
- package/scripts/system-one-calibrate.js +108 -41
- package/scripts/system-one-curves.js +472 -0
- package/scripts/system-one-cycle/adjudication-input.js +65 -0
- package/scripts/system-one-cycle/build.js +165 -0
- package/scripts/system-one-cycle/collect.js +67 -0
- package/scripts/system-one-cycle/common.js +175 -0
- package/scripts/system-one-cycle/engines.js +62 -0
- package/scripts/system-one-cycle/evaluate.js +73 -0
- package/scripts/system-one-cycle/judge.js +106 -0
- package/scripts/system-one-cycle/label.js +59 -0
- package/scripts/system-one-cycle/package.js +173 -0
- package/scripts/system-one-cycle/score.py +111 -0
- package/scripts/system-one-cycle/train.js +136 -0
- package/scripts/system-one-cycle.js +136 -0
- package/scripts/system-one-observations-export.js +58 -6
- package/scripts/system-one-observations-import-store.js +128 -0
- package/scripts/system-one-observations-review.js +4 -5
- 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
|
-
|
|
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,
|
|
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
|
|
351
|
-
explicit: profileLookup || Boolean(detectExplicitStrategy(userPrompt, detectFableModel(userPrompt))) }
|
|
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.
|
|
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
|
|
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
|
-
|
|
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) {
|
|
@@ -58,7 +58,7 @@ function tailBytes(text, bytes) {
|
|
|
58
58
|
|
|
59
59
|
function validLabel(raw) {
|
|
60
60
|
if (!raw || typeof raw !== 'object' || raw.v !== 1) return false;
|
|
61
|
-
if (!VALIDITY.includes(raw.validity)
|
|
61
|
+
if (!VALIDITY.includes(raw.validity)) return false;
|
|
62
62
|
if (!(raw.tier === null || TIERS.includes(raw.tier))) return false;
|
|
63
63
|
if (!Array.isArray(raw.intents) || raw.intents.length > 6 || !raw.intents.every(i => typeof i === 'string')) return false;
|
|
64
64
|
const known = raw.intents.filter(i => INTENTS.includes(i));
|
|
@@ -79,7 +79,7 @@ function parseLabelLine(text) {
|
|
|
79
79
|
if (!validLabel(raw)) return { label: null, reason: 'label-invalid' };
|
|
80
80
|
// Unknown intent ids are dropped, not fatal: the rest of the label is still the agent's judgement.
|
|
81
81
|
const unknownIntents = raw.intents.filter(i => !INTENTS.includes(i));
|
|
82
|
-
const label = { v: 1, validity: raw.validity,
|
|
82
|
+
const label = { v: 1, validity: raw.validity, tier: raw.tier,
|
|
83
83
|
intents: raw.intents.filter(i => INTENTS.includes(i)), workflow: raw.workflow, skills: raw.skills.map(skillName) };
|
|
84
84
|
if (unknownIntents.length) label.unknownIntents = unknownIntents;
|
|
85
85
|
return { label, reason: null };
|
|
@@ -345,13 +345,51 @@ function transcriptMessage(file, turnId) {
|
|
|
345
345
|
|
|
346
346
|
function detectHost(payload, hints) {
|
|
347
347
|
const direct = String(payload.host || payload.runtime || '').toLowerCase();
|
|
348
|
-
if (['claude', 'codex'].includes(direct)) return direct;
|
|
348
|
+
if (['claude', 'codex', 'opencode'].includes(direct)) return direct;
|
|
349
349
|
if (hints.codex || payload.turn_id || payload.last_agent_message) return 'codex';
|
|
350
350
|
if (process.env.CLAUDE_PLUGIN_ROOT || process.env.CLAUDECODE || process.env.CLAUDE_CODE_ENTRYPOINT || process.env.CLAUDE) return 'claude';
|
|
351
351
|
if (process.env.CODEX_HOME || process.env.CODEX_THREAD_ID) return 'codex';
|
|
352
352
|
return 'unknown';
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
+
function normalizeSystemOne(value) {
|
|
356
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
357
|
+
const fields = ['version', 'sha256', 'mode', 'validity', 'intents', 'tier', 'decision'];
|
|
358
|
+
if (!fields.every(key => Object.hasOwn(value, key))
|
|
359
|
+
|| typeof value.version !== 'string' || !value.version.trim()
|
|
360
|
+
|| typeof value.sha256 !== 'string' || !/^[a-f\d]{16}$/i.test(value.sha256)
|
|
361
|
+
|| !['off', 'live'].includes(value.mode)) return null;
|
|
362
|
+
|
|
363
|
+
const invalid = Symbol('invalid-system-one');
|
|
364
|
+
const probabilities = (source, allowed, limit = 12) => {
|
|
365
|
+
if (source === null) return null;
|
|
366
|
+
if (!source || typeof source !== 'object' || Array.isArray(source)) return invalid;
|
|
367
|
+
const entries = Object.entries(source).filter(([key]) => !allowed || allowed.has(key)).slice(0, limit);
|
|
368
|
+
const bounded = [];
|
|
369
|
+
for (const [key, score] of entries) {
|
|
370
|
+
if (!key || !Number.isFinite(score)) return invalid;
|
|
371
|
+
bounded.push([key.slice(0, 64), Math.max(0, Math.min(1, score))]);
|
|
372
|
+
}
|
|
373
|
+
return Object.fromEntries(bounded);
|
|
374
|
+
};
|
|
375
|
+
const validity = probabilities(value.validity, new Set(['invalid']), 1);
|
|
376
|
+
const intents = probabilities(value.intents, null);
|
|
377
|
+
const tier = probabilities(value.tier, new Set(TIERS), TIERS.length);
|
|
378
|
+
const decision = value.decision;
|
|
379
|
+
if (validity === invalid || intents === invalid || tier === invalid
|
|
380
|
+
|| !decision || typeof decision !== 'object' || Array.isArray(decision)
|
|
381
|
+
|| !['actionable', 'invalid', 'abstain'].includes(decision.validity)
|
|
382
|
+
|| !Array.isArray(decision.intents)
|
|
383
|
+
|| !decision.intents.every(id => typeof id === 'string' && id.length > 0)
|
|
384
|
+
|| !(decision.tier === null || TIERS.includes(decision.tier))) return null;
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
version: value.version.slice(0, 64), sha256: value.sha256.toLowerCase(), mode: value.mode,
|
|
388
|
+
validity, intents, tier,
|
|
389
|
+
decision: { validity: decision.validity, intents: decision.intents.slice(0, 12).map(id => id.slice(0, 64)), tier: decision.tier },
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
355
393
|
function routerState(payload) {
|
|
356
394
|
try {
|
|
357
395
|
const state = require('./harness-state');
|
|
@@ -364,7 +402,8 @@ function routerState(payload) {
|
|
|
364
402
|
const plan = run.workflowPlan && typeof run.workflowPlan === 'object' ? run.workflowPlan : run;
|
|
365
403
|
return { tier: plan.tier || run.tier || null, strategy: plan.strategy || run.strategy || null,
|
|
366
404
|
strategySelection: plan.strategySelection || run.strategySelection || null,
|
|
367
|
-
suggestedSkills: Array.isArray(plan.suggestedSkills) ? plan.suggestedSkills.slice(0, 12) : []
|
|
405
|
+
suggestedSkills: Array.isArray(plan.suggestedSkills) ? plan.suggestedSkills.slice(0, 12) : [],
|
|
406
|
+
systemOne: normalizeSystemOne(plan.systemOne) };
|
|
368
407
|
} catch (_) {
|
|
369
408
|
return null;
|
|
370
409
|
}
|
|
@@ -548,6 +587,8 @@ function collectEvents(root, sessionId, turn) {
|
|
|
548
587
|
function startTurn(payload, root) {
|
|
549
588
|
const file = sessionFile(root, payload.session_id);
|
|
550
589
|
const session = readJson(file, null) || { turn: 0, lastFinal: '', pending: null };
|
|
590
|
+
const turnId = String(payload.turn_id || payload.turnId || '');
|
|
591
|
+
if (session.pending && turnId && session.pending.turnId === turnId) return;
|
|
551
592
|
if (session.pending) finishPending(session, payload, root, { text: null, reason: 'stop-missing' });
|
|
552
593
|
if (!session.lastFinalAt || Date.now() - Date.parse(session.lastFinalAt) > RETENTION_MS) session.lastFinal = '';
|
|
553
594
|
// Events left from an earlier turn arrived after its Stop; they belong to no record.
|
|
@@ -555,7 +596,7 @@ function startTurn(payload, root) {
|
|
|
555
596
|
session.turn++;
|
|
556
597
|
session.pending = {
|
|
557
598
|
turn: session.turn,
|
|
558
|
-
turnId
|
|
599
|
+
turnId,
|
|
559
600
|
startedAt: new Date().toISOString(),
|
|
560
601
|
prompt: redact(typeof payload.prompt === 'string' ? payload.prompt : ''),
|
|
561
602
|
previous: session.lastFinal || '',
|
|
@@ -615,7 +656,7 @@ function finishPending(session, payload, root, final) {
|
|
|
615
656
|
selfReport: label,
|
|
616
657
|
selfReportReason: reason,
|
|
617
658
|
};
|
|
618
|
-
|
|
659
|
+
appendRecordDetailed(root, record, textExpired ? null : text, { dedupeById: true, dedupeByTurn: true });
|
|
619
660
|
fs.rmSync(eventsDir(root, payload.session_id, pending.turn), { recursive: true, force: true });
|
|
620
661
|
session.lastFinal = final.text ? redact(tailBytes(stripLabels(final.text), PREVIOUS_BYTES)) : '';
|
|
621
662
|
session.lastFinalAt = observedAt;
|
|
@@ -651,7 +692,7 @@ function handle(payload, env = process.env) {
|
|
|
651
692
|
}
|
|
652
693
|
|
|
653
694
|
module.exports = {
|
|
654
|
-
INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, classifyCommand, labelTier, contradictions,
|
|
695
|
+
INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, normalizeSystemOne, classifyCommand, labelTier, contradictions,
|
|
655
696
|
normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
|
|
656
697
|
expired, recordText, sweep,
|
|
657
698
|
};
|
|
@@ -15,9 +15,9 @@ only SUGGEST rules (soft guidance). This means:
|
|
|
15
15
|
|
|
16
16
|
## The plugin
|
|
17
17
|
|
|
18
|
-
**File:** `index.mjs` -
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
**File:** `index.mjs` - the ESM plugin entrypoint. The OpenCode 2 adapter uses
|
|
19
|
+
the documented prompt and context hooks; the V1 factory remains available for
|
|
20
|
+
existing OpenCode 1 installations. There is no manifest-to-script
|
|
21
21
|
mechanism; an earlier version of this plugin assumed one (a `plugin.json`
|
|
22
22
|
mapping event names to standalone scripts) and opencode never invoked it -
|
|
23
23
|
see issue #37 for how that was found and fixed. **Naming caveat (issue
|
|
@@ -26,7 +26,7 @@ must be copied to a `.js` name when installed - see Installation below.
|
|
|
26
26
|
|
|
27
27
|
It implements three lifecycle mechanisms across opencode's real hooks:
|
|
28
28
|
|
|
29
|
-
The
|
|
29
|
+
The V1 factory follows opencode's plugin contract directly: the named
|
|
30
30
|
`HarnessEnforcement` export is an async factory receiving the opencode context
|
|
31
31
|
(`client`, `directory`, `project`, `worktree`, and `$`) and returning the hook
|
|
32
32
|
map. Copying this one file into `.opencode/plugins/` under a `.js` name is
|
|
@@ -35,6 +35,9 @@ repository
|
|
|
35
35
|
inventory and is not an opencode runtime manifest. The hook callbacks use the
|
|
36
36
|
V1 `(input, output)` shape, including
|
|
37
37
|
`output.args` when the host supplies tool arguments only in the result object.
|
|
38
|
+
OpenCode 2's prompt injection and observation path resolves the canonical
|
|
39
|
+
`harness-everything/scripts/kernel-router.js` and
|
|
40
|
+
`hooks/scripts/lib/observations.js` from an ancestor Harness checkout/runtime.
|
|
38
41
|
|
|
39
42
|
### 1. Edit tracking (`tool.execute.after`)
|
|
40
43
|
|
|
@@ -102,8 +105,9 @@ new breaker failure. A reflection artifact itself does not count as a code edit.
|
|
|
102
105
|
|
|
103
106
|
## Installation
|
|
104
107
|
|
|
105
|
-
**OpenCode 2.x
|
|
106
|
-
`{ id: "harness.enforcement", setup(ctx) }` and registers
|
|
108
|
+
**OpenCode 2.x:** the module default-exports
|
|
109
|
+
`{ id: "harness.enforcement", setup(ctx) }` and registers
|
|
110
|
+
`ctx.session.hook("prompt|context")`, `ctx.tool.hook("execute.before|after")`,
|
|
107
111
|
plus `ctx.event.subscribe()` through the OpenCode 2 plugin context. OpenCode 2
|
|
108
112
|
never loads a named-export-only plugin: it fails with `Plugin must export a
|
|
109
113
|
default definition with an id and an effect or setup function`
|
|
@@ -114,11 +118,17 @@ available for OpenCode 1.x hosts: it receives the V1 context
|
|
|
114
118
|
adapter wraps that factory and maps the V2 hook events onto it, so the
|
|
115
119
|
enforcement logic is shared, not duplicated.
|
|
116
120
|
|
|
121
|
+
The prompt/context routing and System One observation hooks are V2-only. The
|
|
122
|
+
V1 factory keeps its existing enforcement hooks; it does not capture turns.
|
|
123
|
+
|
|
117
124
|
Direction:
|
|
118
125
|
named factory (V1 hosts/tests) → default-export setup adapter → V2 domains.
|
|
119
126
|
|
|
120
|
-
Copy `index.mjs` into opencode's plugin directory **under a `.js` filename
|
|
121
|
-
|
|
127
|
+
Copy `index.mjs` into opencode's plugin directory **under a `.js` filename**.
|
|
128
|
+
The router and observation hooks resolve from a Harness checkout above the
|
|
129
|
+
plugin, or from sibling `harness-everything/`, `hooks/scripts/`, and
|
|
130
|
+
`scripts/lib/` runtime directories. A project install inside the Harness
|
|
131
|
+
checkout already has those files.
|
|
122
132
|
|
|
123
133
|
```bash
|
|
124
134
|
mkdir -p .opencode/plugins
|
|
@@ -126,6 +136,10 @@ cp opencode-plugin/index.mjs .opencode/plugins/harness-enforcement.js # projec
|
|
|
126
136
|
# or
|
|
127
137
|
mkdir -p ~/.config/opencode/plugins
|
|
128
138
|
cp opencode-plugin/index.mjs ~/.config/opencode/plugins/harness-enforcement.js # global
|
|
139
|
+
mkdir -p ~/.config/opencode/hooks ~/.config/opencode/scripts
|
|
140
|
+
cp -R harness-everything ~/.config/opencode/
|
|
141
|
+
cp -R hooks/scripts ~/.config/opencode/hooks/
|
|
142
|
+
cp -R scripts/lib ~/.config/opencode/scripts/
|
|
129
143
|
```
|
|
130
144
|
|
|
131
145
|
Restart OpenCode after copying so the plugin is discovered at startup.
|