harness-everything 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +23 -0
  4. package/CHANGELOG.md +34 -0
  5. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
  6. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
  7. package/ci/mechanism-2am-observations-session-import.test.js +4 -1
  8. package/ci/mechanism-34-observations.test.js +127 -23
  9. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  10. package/ci/mechanism-handoff-file.test.js +121 -0
  11. package/ci/mechanism-system-one-contract.test.js +9 -2
  12. package/ci/mechanism-system-one-curves.test.js +206 -0
  13. package/ci/mechanism-system-one-cycle.test.js +585 -0
  14. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  15. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  16. package/ci/mechanism-system-one-install.test.js +202 -77
  17. package/ci/mechanism-system-one-live.test.js +361 -0
  18. package/ci/mechanism-system-one-relevance.test.js +11 -1
  19. package/ci/mechanism-system-one-train.test.js +136 -53
  20. package/ci/system-one-adapter-test.py +331 -0
  21. package/ci/system-one-train-test.py +116 -24
  22. package/docs/adr/EVID-001.md +123 -0
  23. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  24. package/docs/governed-index.md +2 -0
  25. package/docs/routing.md +2 -2
  26. package/docs/system-one-cycle.md +68 -0
  27. package/docs/system-one-observations.md +9 -8
  28. package/docs/system-one-routing.md +163 -115
  29. package/docs/system-one-suggestion-gates.md +6 -8
  30. package/docs/system-one-training.md +44 -7
  31. package/docs/workflow-runtime.md +19 -0
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +2 -1
  34. package/harness-everything/scripts/system-one/contract.js +19 -15
  35. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  36. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  37. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  38. package/harness-everything/scripts/system-one/install.js +281 -113
  39. package/harness-everything/scripts/system-one/manifest.js +58 -0
  40. package/harness-everything/scripts/system-one/provider.js +96 -2
  41. package/harness-everything/scripts/system-one/resident.js +47 -1
  42. package/harness-everything/scripts/system-one/router.js +80 -1
  43. package/harness-everything/scripts/tier-router.js +21 -6
  44. package/hooks/scripts/lib/observations.js +43 -4
  45. package/opencode-plugin/plugin.json +1 -1
  46. package/package.json +1 -1
  47. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  48. package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
  49. package/plugins/harness-everything/plugin.json +1 -1
  50. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  51. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  52. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  53. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  54. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  55. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  56. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  57. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  58. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  59. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  60. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  61. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  62. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  63. package/sbom.cdx.json +7 -7
  64. package/scripts/ci-change-scope.js +59 -0
  65. package/scripts/handoff-file.js +223 -0
  66. package/scripts/sync-openai-plugin.js +4 -0
  67. package/scripts/system-one-calibrate.js +108 -41
  68. package/scripts/system-one-curves.js +332 -0
  69. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  70. package/scripts/system-one-cycle/build.js +165 -0
  71. package/scripts/system-one-cycle/collect.js +50 -0
  72. package/scripts/system-one-cycle/common.js +137 -0
  73. package/scripts/system-one-cycle/engines.js +62 -0
  74. package/scripts/system-one-cycle/evaluate.js +70 -0
  75. package/scripts/system-one-cycle/judge.js +106 -0
  76. package/scripts/system-one-cycle/label.js +59 -0
  77. package/scripts/system-one-cycle/package.js +173 -0
  78. package/scripts/system-one-cycle/score.py +111 -0
  79. package/scripts/system-one-cycle/train.js +136 -0
  80. package/scripts/system-one-cycle.js +131 -0
  81. package/scripts/system-one-observations-export.js +29 -6
  82. package/scripts/system-one-observations-review.js +4 -5
  83. package/scripts/system-one-train.py +117 -61
@@ -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) {
@@ -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) || typeof raw.contextDependent !== 'boolean') return false;
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, contextDependent: raw.contextDependent, tier: raw.tier,
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 };
@@ -352,6 +352,44 @@ function detectHost(payload, hints) {
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
  }
@@ -651,7 +690,7 @@ function handle(payload, env = process.env) {
651
690
  }
652
691
 
653
692
  module.exports = {
654
- INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, classifyCommand, labelTier, contradictions,
693
+ INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, normalizeSystemOne, classifyCommand, labelTier, contradictions,
655
694
  normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
656
695
  expired, recordText, sweep,
657
696
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "0.51.0",
4
+ "version": "0.52.0",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -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) || typeof raw.contextDependent !== 'boolean') return false;
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, contextDependent: raw.contextDependent, tier: raw.tier,
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 };
@@ -352,6 +352,44 @@ function detectHost(payload, hints) {
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
  }
@@ -651,7 +690,7 @@ function handle(payload, env = process.env) {
651
690
  }
652
691
 
653
692
  module.exports = {
654
- INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, classifyCommand, labelTier, contradictions,
693
+ INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, normalizeSystemOne, classifyCommand, labelTier, contradictions,
655
694
  normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
656
695
  expired, recordText, sweep,
657
696
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "harness-everything",
4
- "version": "0.51.0",
4
+ "version": "0.52.0",
5
5
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
6
6
  "author": {
7
7
  "name": "Miya Daniel",
@@ -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 };
@@ -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
  }