harness-everything 0.50.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 (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 +174 -115
  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-prb-outline-review.test.js +783 -107
  12. package/ci/mechanism-system-one-contract.test.js +9 -2
  13. package/ci/mechanism-system-one-curves.test.js +206 -0
  14. package/ci/mechanism-system-one-cycle.test.js +585 -0
  15. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  16. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  17. package/ci/mechanism-system-one-install.test.js +202 -77
  18. package/ci/mechanism-system-one-live.test.js +361 -0
  19. package/ci/mechanism-system-one-relevance.test.js +11 -1
  20. package/ci/mechanism-system-one-train.test.js +136 -53
  21. package/ci/release-unreleased-heading.test.js +24 -0
  22. package/ci/system-one-adapter-test.py +331 -0
  23. package/ci/system-one-train-test.py +116 -24
  24. package/docs/adr/EVID-001.md +123 -0
  25. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  26. package/docs/doc-workflow-reconciliation.md +29 -16
  27. package/docs/governed-index.md +2 -0
  28. package/docs/platform-capabilities.md +2 -0
  29. package/docs/routing.md +2 -2
  30. package/docs/system-one-cycle.md +68 -0
  31. package/docs/system-one-observations.md +9 -8
  32. package/docs/system-one-routing.md +163 -115
  33. package/docs/system-one-suggestion-gates.md +6 -8
  34. package/docs/system-one-training.md +44 -7
  35. package/docs/workflow-runtime.md +19 -0
  36. package/harness-everything/SKILL.md +1 -1
  37. package/harness-everything/scripts/kernel-router.js +2 -1
  38. package/harness-everything/scripts/system-one/contract.js +19 -15
  39. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  40. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  41. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  42. package/harness-everything/scripts/system-one/install.js +281 -113
  43. package/harness-everything/scripts/system-one/manifest.js +58 -0
  44. package/harness-everything/scripts/system-one/provider.js +96 -2
  45. package/harness-everything/scripts/system-one/resident.js +47 -1
  46. package/harness-everything/scripts/system-one/router.js +80 -1
  47. package/harness-everything/scripts/tier-router.js +21 -6
  48. package/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
  49. package/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
  50. package/hooks/scripts/lib/observations.js +43 -4
  51. package/hooks/scripts/lib/workflow-obligations.js +8 -4
  52. package/hooks/scripts/state-persist.js +26 -7
  53. package/hooks/scripts/w6-state-operations.js +239 -0
  54. package/opencode-plugin/plugin.json +1 -1
  55. package/package.json +2 -2
  56. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  57. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
  58. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
  59. package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
  60. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +8 -4
  61. package/plugins/harness-everything/hooks/scripts/state-persist.js +26 -7
  62. package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +239 -0
  63. package/plugins/harness-everything/plugin.json +1 -1
  64. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  65. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  66. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  67. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  68. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  69. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  70. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  71. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  72. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  73. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  74. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  75. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  76. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  77. package/sbom.cdx.json +7 -7
  78. package/scripts/ci-change-scope.js +59 -0
  79. package/scripts/handoff-file.js +223 -0
  80. package/scripts/sync-openai-plugin.js +4 -0
  81. package/scripts/system-one-calibrate.js +108 -41
  82. package/scripts/system-one-curves.js +332 -0
  83. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  84. package/scripts/system-one-cycle/build.js +165 -0
  85. package/scripts/system-one-cycle/collect.js +50 -0
  86. package/scripts/system-one-cycle/common.js +137 -0
  87. package/scripts/system-one-cycle/engines.js +62 -0
  88. package/scripts/system-one-cycle/evaluate.js +70 -0
  89. package/scripts/system-one-cycle/judge.js +106 -0
  90. package/scripts/system-one-cycle/label.js +59 -0
  91. package/scripts/system-one-cycle/package.js +173 -0
  92. package/scripts/system-one-cycle/score.py +111 -0
  93. package/scripts/system-one-cycle/train.js +136 -0
  94. package/scripts/system-one-cycle.js +131 -0
  95. package/scripts/system-one-observations-export.js +29 -6
  96. package/scripts/system-one-observations-review.js +4 -5
  97. package/scripts/system-one-train.py +117 -61
@@ -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
  };
@@ -668,10 +668,14 @@ function updateStep(context, stepId, disposition, options = {}) {
668
668
  throw new Error('resolve active-step bindings before passing the step: ' + ids.join(', '));
669
669
  }
670
670
  }
671
- if (disposition === 'pass' && step.stepType === 'verification'
672
- && require('./doc-reconciliation-pilot').assess(context, loaded.set).withhold) {
673
- withholdPilotVerification(context, loaded.set);
674
- throw new Error('document verification pending: S1 grants no document credit');
671
+ if (disposition === 'pass' && step.stepType === 'verification') {
672
+ const inFlightW6ToolUseId = require('./doc-reconciliation-provider').pendingW6VerificationInvocation(context);
673
+ const assessment = require('./doc-reconciliation-pilot').assess(context, loaded.set,
674
+ inFlightW6ToolUseId ? { allowInFlightW6ToolUseId: inFlightW6ToolUseId } : {});
675
+ if (assessment.withhold) {
676
+ withholdPilotVerification(context, loaded.set);
677
+ throw new Error('document verification pending: S1 grants no document credit');
678
+ }
675
679
  }
676
680
  // Review-mode refusal (pilot ON only): a self-authored or non-independent review PASS stays pending.
677
681
  if (disposition === 'pass' && step.stepType === 'review') {
@@ -86,6 +86,8 @@ function processState(payload) {
86
86
  const isSuccessEvent = hookEvent === 'PostToolUse';
87
87
  const isFailed = hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) || (!isSuccessEvent && exitCode === undefined && stderrSignal);
88
88
  const toolName = payload.tool_name || payload.tool || 'command';
89
+ let editAfterCapture = false;
90
+ let stateOnlyCandidate = false;
89
91
  if (isFailed) {
90
92
  let output = (stderrSignal ? stderr : stdout) || payload.output || '';
91
93
  if (output.length > 500) output = '...' + output.slice(-500);
@@ -99,20 +101,26 @@ function processState(payload) {
99
101
  const command = (payload.tool_input && payload.tool_input.command) || '';
100
102
  if (isShell) {
101
103
  const commandClass = classifyShell(command);
102
- const metadataStep = !isFailed && (isSuccessEvent || exitCode === 0)
104
+ const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
105
+ const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
106
+ stateOnlyCandidate = Boolean(docCheck && typeof payload.cwd === 'string' && payload.cwd
107
+ && docCheck.isW6StateCommand(command, payload.cwd, root,
108
+ { toolName, sessionId, agentId: payload.agent_id }));
109
+ const metadataStep = !stateOnlyCandidate && !isFailed && (isSuccessEvent || exitCode === 0)
103
110
  && isSuccessfulMetadataStep(command, cwdOf(payload, root));
104
- if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup') state.lastEditAt = Date.now();
111
+ if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup') {
112
+ if (stateOnlyCandidate) editAfterCapture = true;
113
+ else state.lastEditAt = Date.now();
114
+ }
105
115
  // Verification evidence needs a confirmed success: a PostToolUse event or an explicit zero exit.
106
116
  // Pilot ON only: a registered, argv-validated doc-check that resolves to this install's own runtime is the document
107
117
  // verification evidence, and only at the shipped pin (R3-02). Any other path earns no verification evidence. OFF stays legacy.
108
- const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
109
- const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
110
118
  const installedCheck = docCheck && docCheck.registeredInstalledCheck(command, cwdOf(payload, root));
111
119
  const docCheckCandidate = installedCheck && installedCheck.kind !== 'not-candidate';
112
120
  const pinCheckable = installedCheck && installedCheck.installed
113
121
  && (installedCheck.kind === 'accepted' || installedCheck.reason === 'implementation-pin-mismatch');
114
122
  // A non-candidate that is compound or names the checker is not generic verification (trustRisk); the scanner miss does not clear it.
115
- const verifies = docCheckCandidate
123
+ const verifies = stateOnlyCandidate ? false : docCheckCandidate
116
124
  ? Boolean(pinCheckable) && docCheck.fileDigest(installedCheck.installed) === docCheck.SHIPPED_DOC_CHECK_DIGEST
117
125
  : !(pilotEnabled && docCheck.trustRisk(command)) && isVerificationShell(command, { cwd: cwdOf(payload, root), root });
118
126
  if (!isFailed && (isSuccessEvent || exitCode === 0) && verifies) {
@@ -130,6 +138,17 @@ function processState(payload) {
130
138
  fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
131
139
  observeTool(payload);
132
140
  persistPilotCapture(payload, captureEventName, sessionId, root);
141
+ if (editAfterCapture) {
142
+ const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
143
+ const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
144
+ const captures = docCheck && docCheck.readCaptureView(getSessionDir(root, sessionId));
145
+ const verifiedStateOnly = stateOnlyCandidate && docCheck && captures && !captures.tampered
146
+ && docCheck.isVerifiedW6StateOperation(captures.records, getSessionDir(root, sessionId), payload.tool_use_id);
147
+ if (!verifiedStateOnly) {
148
+ state.lastEditAt = Date.now();
149
+ fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
150
+ }
151
+ }
133
152
  } catch (_) {}
134
153
  process.exit(0);
135
154
  }
@@ -142,9 +161,9 @@ function persistPilotCapture(payload, eventName, sessionId, root) {
142
161
  if (!payload || process.env.HARNESS_DOC_RECONCILIATION_PILOT !== '1') return;
143
162
  if (PILOT_CAPTURE_EVENT_NAMES.indexOf(eventName) === -1) return;
144
163
  const provider = require('./lib/doc-reconciliation-provider');
145
- const entry = provider.buildCaptureRecord(payload, eventName, root);
146
- if (!entry) return;
147
164
  const sessionDir = getSessionDir(root, sessionId);
165
+ const entry = provider.buildCaptureRecord(payload, eventName, root, { sessionDir });
166
+ if (!entry) return;
148
167
  // Observation-time identity: the workflow and pin in force when the host event was captured.
149
168
  const observed = provider.observedIdentityFor(sessionDir);
150
169
  if (observed) entry.observedIdentity = observed;
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('crypto');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
8
+ const { canonical } = require('./lib/workflow-isolation');
9
+
10
+ const INVENTORY_FILE = 'doc-reconciliation/outline-confirmation/inventory';
11
+ const APPROVED_INVENTORY = 'benchmarks/results/live-host/claude-341-outline-dispatch-2026-10-28/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md';
12
+
13
+ function git(root, args, buffer = false) {
14
+ const { execFileSync } = require('child_process');
15
+ return execFileSync('git', ['-C', root, ...args], { encoding: buffer ? null : 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
16
+ }
17
+
18
+ function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
19
+ function sha(bytes) { return crypto.createHash('sha256').update(bytes).digest('hex'); }
20
+ function jsonBytes(value) { return Buffer.from(JSON.stringify(value, null, 2) + '\n'); }
21
+ function same(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
22
+
23
+ function safeStatePath(sessionDir, relative, allowMissing = false) {
24
+ const sessionRoot = fs.realpathSync.native(sessionDir);
25
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/).some(part => !part || part === '.' || part === '..')) {
26
+ throw new Error('invalid-state-destination');
27
+ }
28
+ const destination = path.resolve(sessionRoot, relative);
29
+ const within = path.relative(sessionRoot, destination);
30
+ if (!within || within.startsWith('..' + path.sep) || within === '..' || path.isAbsolute(within)) throw new Error('state-destination-escape');
31
+ let cursor = sessionRoot;
32
+ const parts = relative.split(/[\\/]/);
33
+ for (let index = 0; index < parts.length; index += 1) {
34
+ cursor = path.join(cursor, parts[index]);
35
+ try {
36
+ const stat = fs.lstatSync(cursor);
37
+ if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory())
38
+ || (index === parts.length - 1 && !stat.isFile())) throw new Error('state-destination-not-regular');
39
+ } catch (error) {
40
+ if (error.code !== 'ENOENT') throw error;
41
+ if (!allowMissing) throw error;
42
+ break;
43
+ }
44
+ }
45
+ const parent = path.dirname(destination);
46
+ if (fs.existsSync(parent) && fs.realpathSync.native(parent) !== path.resolve(sessionRoot, path.dirname(relative))) {
47
+ throw new Error('state-destination-parent-alias');
48
+ }
49
+ return destination;
50
+ }
51
+
52
+ function writeNewStateFile(sessionDir, relative, bytes) {
53
+ const file = safeStatePath(sessionDir, relative, true);
54
+ fs.mkdirSync(path.dirname(file), { recursive: true });
55
+ safeStatePath(sessionDir, relative, true);
56
+ fs.writeFileSync(file, bytes, { flag: 'wx' });
57
+ if (fs.realpathSync.native(path.dirname(file)) !== path.resolve(fs.realpathSync.native(sessionDir), path.dirname(relative))) {
58
+ throw new Error('state-destination-parent-alias');
59
+ }
60
+ return file;
61
+ }
62
+
63
+ function loadProvider() { return require('./lib/doc-reconciliation-provider'); }
64
+
65
+ function hostInvocation(sessionId, operation) {
66
+ const root = canonical(getWorkspaceRoot());
67
+ const sessionDir = getSessionDir(root, sessionId);
68
+ const provider = loadProvider();
69
+ const captures = provider.readCaptureView(sessionDir);
70
+ if (captures.tampered) throw new Error('capture-view-tampered');
71
+ const script = fs.realpathSync.native(__filename);
72
+ const matched = captures.records.filter(record => {
73
+ if (!record || record.event !== 'PreToolUse' || record.tool_name !== 'Bash'
74
+ || record.session_id !== sessionId || record.agent_id !== undefined || !record.tool_use_id) return false;
75
+ let cwd;
76
+ try { cwd = canonical(record.cwd); } catch { return false; }
77
+ if (cwd !== root) return false;
78
+ const parsed = provider._internals.safeTokenize(record.command);
79
+ if (!parsed.ok || parsed.tokens.length !== 5 || !['node', 'nodejs'].includes(parsed.tokens[0])) return false;
80
+ let invoked;
81
+ try { invoked = fs.realpathSync.native(path.resolve(cwd, parsed.tokens[1])); } catch { return false; }
82
+ return invoked === script && parsed.tokens[2] === operation
83
+ && parsed.tokens[3] === '--session-id' && parsed.tokens[4] === sessionId;
84
+ });
85
+ if (matched.length !== 1) throw new Error('unique-correlated-pre-invocation-required');
86
+ const pre = matched[0];
87
+ if (captures.records.some(record => record && record.ref !== pre.ref && record.session_id === sessionId
88
+ && record.tool_use_id === pre.tool_use_id && ['PostToolUse', 'PostToolUseFailure'].includes(record.event))) {
89
+ throw new Error('operation-already-completed');
90
+ }
91
+ return { root, sessionDir, provider, captures: captures.records, pre };
92
+ }
93
+
94
+ function loadRow17State(root, sessionDir) {
95
+ const workflow = readJson(path.join(sessionDir, 'workflow-run.json'));
96
+ const task = workflow.docReconciliationTask;
97
+ const baseline = workflow.docReconciliationBaseline;
98
+ if (workflow.strategy !== 'iterative-single' || workflow.state !== 'running' || !Number.isInteger(workflow.revision)
99
+ || !task || task.schema !== 'harness.doc-reconciliation-task-pin.v1'
100
+ || !same(task.requirementIds, ['adr-evid', 'verify-row17']) || task.taskId !== 'task-adr-evid+verify-row17'
101
+ || task.sessionId !== workflow.sessionId || task.workflowId !== workflow.workflowId
102
+ || !baseline || canonical(baseline.root) !== root || task.baselineRoot !== baseline.root
103
+ || task.baselineCommit !== baseline.commit) throw new Error('row17-task-pin-invalid');
104
+ return { workflow, task, baseline };
105
+ }
106
+
107
+ function inventoryBytes(provider) {
108
+ const source = path.resolve(__dirname, '..', '..', APPROVED_INVENTORY);
109
+ if (fs.existsSync(source)) return fs.readFileSync(source);
110
+ const capture = path.join(__dirname, 'lib/doc-reconciliation-outline-capture.sanitized.jsonl');
111
+ for (const line of fs.readFileSync(capture, 'utf8').split(/\r?\n/)) {
112
+ if (!line) continue;
113
+ const record = JSON.parse(line);
114
+ const candidates = [record.tool_response?.content?.[0]?.text, record.tool_response?.file?.content, record.tool_response?.stdout];
115
+ for (const value of candidates) {
116
+ if (typeof value === 'string' && sha(Buffer.from(value)) === provider._internals.OUTLINE_INVENTORY_PIN.sha256) {
117
+ return Buffer.from(value);
118
+ }
119
+ }
120
+ }
121
+ throw new Error('pinned-inventory-bytes-unavailable');
122
+ }
123
+
124
+ function inventory({ sessionId }) {
125
+ const context = hostInvocation(sessionId, 'inventory');
126
+ const { root, sessionDir, provider } = context;
127
+ const { workflow, task, baseline } = loadRow17State(root, sessionDir);
128
+ const head = git(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
129
+ const tree = git(root, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
130
+ if (head !== baseline.commit || tree !== baseline.tree || git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], true).length) {
131
+ throw new Error('inventory-must-run-on-clean-baseline');
132
+ }
133
+ const expectedPin = provider._internals.OUTLINE_INVENTORY_PIN;
134
+ const bytes = inventoryBytes(provider);
135
+ const validated = provider._internals.validateOutlineInventoryPin({ bytes, pin: expectedPin, expectedPin });
136
+ const row = provider._internals.resolveInventoryRow({ parsed: validated.parsed, pin: expectedPin }, '17');
137
+ if (sha(bytes) !== expectedPin.sha256 || validated.state !== 'accepted' || row.state !== 'accepted' || row.row.domain !== 'EVID'
138
+ || expectedPin.rowDomainMappings[0].approvalRef !== 'https://github.com/dyphn1/Harness-everything/issues/325#issuecomment-6706805112') {
139
+ throw new Error('pinned-row17-inventory-invalid');
140
+ }
141
+ const inventoryRelative = `${INVENTORY_FILE}/${path.posix.basename(expectedPin.retainedArtifactPath)}`;
142
+ const pinRelative = `${INVENTORY_FILE}/inventory-pin.json`;
143
+ writeNewStateFile(sessionDir, inventoryRelative, bytes);
144
+ writeNewStateFile(sessionDir, pinRelative, jsonBytes(expectedPin));
145
+ return { operation: 'inventory', workflowId: workflow.workflowId, revision: workflow.revision, taskId: task.taskId,
146
+ destinations: [inventoryRelative, pinRelative], sha256: expectedPin.sha256 };
147
+ }
148
+
149
+ function seal({ sessionId }) {
150
+ const context = hostInvocation(sessionId, 'seal');
151
+ const { root, sessionDir, provider, captures } = context;
152
+ const { workflow, task, baseline } = loadRow17State(root, sessionDir);
153
+ const head = git(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
154
+ const tree = git(root, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
155
+ if (head === baseline.commit || git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], true).length
156
+ || git(root, ['merge-base', '--is-ancestor', baseline.commit, head]) !== '') throw new Error('seal-requires-clean-b-to-o-outline');
157
+ const expectedPin = provider._internals.OUTLINE_INVENTORY_PIN;
158
+ const inventoryRoot = path.join(sessionDir, INVENTORY_FILE);
159
+ const pinFile = path.join(inventoryRoot, 'inventory-pin.json');
160
+ const pinBytes = fs.readFileSync(pinFile);
161
+ const pin = JSON.parse(pinBytes.toString('utf8'));
162
+ const bytes = fs.readFileSync(path.join(inventoryRoot, path.posix.basename(expectedPin.retainedArtifactPath)));
163
+ const inventory = provider._internals.validateOutlineInventoryPin({ bytes, pin, expectedPin });
164
+ if (inventory.state !== 'accepted' || sha(pinBytes) !== sha(jsonBytes(expectedPin))) throw new Error('pinned-inventory-not-installed');
165
+ const inventoryPath = `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(expectedPin.retainedArtifactPath)}`;
166
+ const reviewEvents = captures.filter(record => record && record.event === 'SubagentStop' && record.agent_type === 'reviewer'
167
+ && record.reviewVerdict === 'approve' && record.reviewSummary);
168
+ const candidates = reviewEvents.filter(review => {
169
+ const targets = Object.keys(review.reviewedArtifactDigests || {}).filter(relative => relative !== inventoryPath);
170
+ return targets.length === 1 && review.reviewedArtifactDigests[inventoryPath] === sha(bytes);
171
+ });
172
+ if (candidates.length !== 1) throw new Error('unique-approved-outline-review-required');
173
+ const review = candidates[0];
174
+ const targetPaths = Object.keys(review.reviewedArtifactDigests).filter(relative => relative !== inventoryPath);
175
+ const target = targetPaths[0];
176
+ const targetBytes = git(root, ['show', `${head}:${target}`], true);
177
+ const citation = provider._internals.parseOutlineCitation(targetBytes, target);
178
+ const row = provider._internals.resolveInventoryRow(inventory, citation.rowId);
179
+ const targetBlob = git(root, ['rev-parse', `${head}:${target}`]).trim();
180
+ if (citation.state !== 'accepted' || citation.rowId !== '17' || citation.domain !== 'EVID'
181
+ || row.state !== 'accepted' || row.row.domain !== 'EVID'
182
+ || review.reviewedArtifactDigests[target] !== sha(targetBytes)) throw new Error('approved-outline-does-not-match-pinned-row17');
183
+ const start = captures.filter(record => record && record.event === 'SubagentStart' && record.agent_id === review.agent_id);
184
+ const launch = captures.filter(record => record && record.event === 'PostToolUse' && ['Task', 'Agent'].includes(record.tool_name)
185
+ && record.agent_id === review.agent_id);
186
+ if (start.length !== 1 || launch.length !== 1 || captures.indexOf(start[0]) >= captures.indexOf(review)
187
+ || captures.indexOf(launch[0]) >= captures.indexOf(review)
188
+ || start[0].outlineIdentity?.state !== 'accepted'
189
+ || start[0].outlineIdentity.identity.outlineCommit !== head || start[0].outlineIdentity.identity.outlineTree !== tree
190
+ || !provider.reviewRecordIndependent(review, captures, { author: sessionId,
191
+ executors: provider.journalExecutors(captures, sessionId) })) throw new Error('outline-review-lifecycle-or-identity-invalid');
192
+ const outlineDigests = { [target]: sha(targetBytes) };
193
+ const attemptId = 'attempt-' + sha(review.ref).slice(0, 16);
194
+ const attemptRelative = `doc-reconciliation/outline-confirmation/${task.taskId}/attempts/${attemptId}`;
195
+ const attemptDir = path.join(sessionDir, attemptRelative);
196
+ const lease = { schema: 'harness.outline-writer-lease.v1', id: 'lease-' + sha(review.ref).slice(0, 16),
197
+ taskId: task.taskId, attemptId, principalId: sessionId, root, exclusive: true, active: true };
198
+ const leaseRelative = `${attemptRelative}/writer-lease.json`;
199
+ const leaseBytes = jsonBytes(lease);
200
+ const leaseDigest = sha(leaseBytes);
201
+ const reviewDigest = provider._internals.captureDigest(review);
202
+ const handoff = {
203
+ schema: 'harness.outline-handoff.v1', handoffId: 'handoff-' + sha(review.ref).slice(0, 16),
204
+ taskId: task.taskId, attemptId, supersedesAttemptId: null, workspaceId: task.workspaceId,
205
+ workflowId: workflow.workflowId, workflowRevision: workflow.revision, sessionId, hostId: 'claude-code',
206
+ baseline: { root: baseline.root, commit: baseline.commit, tree: baseline.tree, configDigest: task.configDigest },
207
+ configDigest: task.configDigest, targetPaths, draftWorktreeRoot: root,
208
+ outline: { commit: head, tree, targetBlobs: { [target]: { blobOid: targetBlob, storedBytesSha256: sha(targetBytes) } } },
209
+ inventory: { ...expectedPin, rowId: '17', domain: 'EVID', targetPaths },
210
+ reviewCaptureRef: review.ref, reviewCaptureDigest: reviewDigest, reviewDigest: review.reviewDigest,
211
+ coordinatorPrincipal: sessionId, writerLeaseId: lease.id, writerLeaseDigest: leaseDigest,
212
+ draftDispatchToken: crypto.randomBytes(24).toString('hex'),
213
+ };
214
+ const validatedReview = provider._internals.validateOutlineReview({ handoff, attemptDir, captures, targetPaths,
215
+ outlineDigests, inventory, sessionId });
216
+ if (validatedReview.state !== 'accepted') throw new Error(validatedReview.reason || 'outline-review-invalid');
217
+ const handoffRelative = `${attemptRelative}/handoff.json`;
218
+ fs.mkdirSync(attemptDir, { recursive: true });
219
+ writeNewStateFile(sessionDir, leaseRelative, leaseBytes);
220
+ writeNewStateFile(sessionDir, handoffRelative, jsonBytes(handoff));
221
+ return { operation: 'seal', workflowId: workflow.workflowId, revision: workflow.revision, taskId: task.taskId,
222
+ attemptId, destinations: [leaseRelative, handoffRelative], handoff };
223
+ }
224
+
225
+ function main(argv) {
226
+ const [operation, flag, sessionId, extra] = argv;
227
+ if (!['inventory', 'seal'].includes(operation) || flag !== '--session-id' || !sessionId || extra !== undefined) {
228
+ throw new Error('Usage: w6-state-operations.js <inventory|seal> --session-id <id>');
229
+ }
230
+ const result = operation === 'inventory' ? inventory({ sessionId }) : seal({ sessionId });
231
+ process.stdout.write(JSON.stringify(result) + '\n');
232
+ }
233
+
234
+ if (require.main === module) {
235
+ try { main(process.argv.slice(2)); }
236
+ catch (error) { console.error('[W6 State Operation] ' + error.message); process.exitCode = 2; }
237
+ }
238
+
239
+ module.exports = { main };
@@ -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.50.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.50.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": {
@@ -23,7 +23,7 @@
23
23
  "test:docs:capabilities": "node ci/doc-capability-consistency.test.js",
24
24
  "test:references": "node ci/reference-check.js",
25
25
  "test:portability": "node ci/portability-lint.js",
26
- "test:release": "node ci/release-consistency-check.js && node ci/release-consistency-check.test.js && node ci/mechanism-2x-release-automation.test.js && node ci/mechanism-2x-release-commit-message.test.js && node ci/mechanism-2ap-sbom.test.js",
26
+ "test:release": "node ci/release-consistency-check.js && node ci/release-consistency-check.test.js && node ci/mechanism-2x-release-automation.test.js && node ci/mechanism-2x-release-commit-message.test.js && node ci/mechanism-2ap-sbom.test.js && node ci/release-unreleased-heading.test.js",
27
27
  "test:release:semantics": "node ci/semantic-release-analyzer.test.mjs",
28
28
  "test:install": "node scripts/verify-install.js",
29
29
  "system-one:install": "node harness-everything/scripts/system-one/install.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.50.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",
@@ -197,6 +197,7 @@ function creditChain(context, set, dependencies = {}) {
197
197
  principals,
198
198
  baseline,
199
199
  captures,
200
+ allowInFlightW6ToolUseId: dependencies.allowInFlightW6ToolUseId || null,
200
201
  };
201
202
  const originProvider = dependencies.originProvider || createOriginProvider(providerInput);
202
203
  const produced = produceDocSnapshot({
@@ -457,6 +458,17 @@ function assess(context, set, dependencies = {}) {
457
458
  report.unsatisfied.push({ obligationId: 'doc-change:scope', state: 'unavailable', reasonCode: reason });
458
459
  }
459
460
  }
461
+ if (!withhold && dependencies.allowInFlightW6ToolUseId) {
462
+ report.pilotCredit = false;
463
+ report.pilotStatus = 'pending';
464
+ report.creditedCapabilities = [];
465
+ report.acceptedRefs = [];
466
+ report.outlineEvidence = { status: 'pending', outcome: 'none', observation: 'pending',
467
+ acceptedRefs: [], recordRefs: [], diagnostics: [{ code: 'state-operation-in-flight',
468
+ message: 'the verification state operation has not completed its host result', obligationId: null }] };
469
+ report.diagnostics.push({ code: 'state-operation-in-flight',
470
+ message: 'the verification state operation has not completed its host result', obligationId: null });
471
+ }
460
472
  report.diagnostics = report.diagnostics.map(diagnosticOf);
461
473
  try { atomicWriteJson(path.join(context.sessionDir, 'doc-reconciliation-pilot.json'), report); }
462
474
  catch {