harness-everything 0.49.0 → 0.51.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 (29) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +0 -82
  4. package/.github/workflows/doc-governance.yml +91 -0
  5. package/.github/workflows/release.yml +5 -2
  6. package/CHANGELOG.md +150 -115
  7. package/ci/mechanism-2ax-doc-lifecycle.test.js +142 -12
  8. package/ci/mechanism-prb-outline-review.test.js +783 -107
  9. package/ci/release-unreleased-heading.test.js +24 -0
  10. package/docs/doc-workflow-reconciliation.md +29 -16
  11. package/docs/document-lifecycle.md +19 -0
  12. package/docs/platform-capabilities.md +2 -0
  13. package/docs/repository-contract.md +1 -0
  14. package/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
  15. package/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
  16. package/hooks/scripts/lib/workflow-obligations.js +8 -4
  17. package/hooks/scripts/state-persist.js +26 -7
  18. package/hooks/scripts/w6-state-operations.js +239 -0
  19. package/opencode-plugin/plugin.json +1 -1
  20. package/package.json +2 -2
  21. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  22. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
  23. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
  24. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +8 -4
  25. package/plugins/harness-everything/hooks/scripts/state-persist.js +26 -7
  26. package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +239 -0
  27. package/plugins/harness-everything/plugin.json +1 -1
  28. package/sbom.cdx.json +7 -7
  29. package/scripts/doc-governance-guard.js +31 -8
@@ -68,6 +68,7 @@ const OUTLINE_CAPTURE_MAPPING = Object.freeze({
68
68
  const OUTLINE_SEAM_SCHEMA = 'harness.outline-dispatch-seam.v1';
69
69
  const OUTLINE_HANDOFF_SCHEMA = 'harness.outline-handoff.v1';
70
70
  const OUTLINE_LEASE_SCHEMA = 'harness.outline-writer-lease.v1';
71
+ const W6_STATE_OPERATION_SCHEMA = 'harness.w6-state-operation.v1';
71
72
  const OUTLINE_WRITE_TOOLS = ['Write', 'Edit', 'apply_patch'];
72
73
  const OUTLINE_INVENTORY_SOURCE = '/Users/daniel.chang/Desktop/Skills/Harness-everything/.worktrees/packets/adr-e1-2026-10-27/report-inv.md';
73
74
  const OUTLINE_INVENTORY_SHA256 = '2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6';
@@ -81,6 +82,14 @@ const OUTLINE_INVENTORY_PIN = Object.freeze({
81
82
  sourceDomain: 'VERI', domain: 'EVID', approvalRef: 'https://github.com/dyphn1/Harness-everything/issues/325#issuecomment-6706805112' })]),
82
83
  retainedArtifactPath: `inventory/${OUTLINE_INVENTORY_SHA256}.md`,
83
84
  });
85
+ const W6_ROW17_REQUIREMENTS = Object.freeze([
86
+ Object.freeze({ id: 'adr-evid', stepType: 'doc-change',
87
+ summary: 'Draft the row-17 EVID-001 verification-evidence ADR.',
88
+ acceptance: 'A real proposed O is independently reviewed before the draft D; D is a strict descendant of O and changes only the ADR.' }),
89
+ Object.freeze({ id: 'verify-row17', stepType: 'verification',
90
+ summary: 'Generate the governed index and verify the final ADR through one combined registered check and independent review.',
91
+ acceptance: 'All four combined-check capabilities and the ADR-only final review are captured before normal Stop reconciliation.' }),
92
+ ]);
84
93
  const OUTLINE_MARKER = 'HARNESS_OUTLINE_DISPATCH_V1';
85
94
  const OUTLINE_TASK_ID = /^task-[A-Za-z0-9][A-Za-z0-9+._-]{0,127}$/;
86
95
  const OUTLINE_ATTEMPT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
@@ -189,6 +198,169 @@ function safeTokenize(command) {
189
198
  return { ok: true, tokens };
190
199
  }
191
200
 
201
+ function stateSnapshot(sessionDir) {
202
+ const files = {};
203
+ const ignored = new Set(['doc-reconciliation-capture', 'doc-reconciliation-capture.json', 'handoff-state.json']);
204
+ function visit(directory, relative = '') {
205
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => compareKeys(a.name, b.name))) {
206
+ const rel = relative ? `${relative}/${entry.name}` : entry.name;
207
+ if (!relative && ignored.has(entry.name)) continue;
208
+ const full = path.join(directory, entry.name);
209
+ const stat = fs.lstatSync(full);
210
+ if (stat.isSymbolicLink()) files[rel] = { kind: 'symlink', digest: digestText(fs.readlinkSync(full)) };
211
+ else if (stat.isDirectory()) { files[rel] = { kind: 'directory' }; visit(full, rel); }
212
+ else if (stat.isFile()) {
213
+ const bytes = fs.readFileSync(full);
214
+ const item = { kind: 'file', digest: crypto.createHash('sha256').update(bytes).digest('hex') };
215
+ if (['workflow-run.json', 'workflow-obligations.json', 'doc-reconciliation-pilot.json',
216
+ 'inventory-pin.json', 'handoff.json', 'writer-lease.json'].includes(path.posix.basename(rel))
217
+ && bytes.length <= 1024 * 1024) {
218
+ try { item.json = JSON.parse(bytes.toString('utf8')); } catch { item.jsonInvalid = true; }
219
+ }
220
+ if (rel.startsWith('doc-reconciliation/outline-confirmation/inventory/') && rel.endsWith('.md')) {
221
+ item.content = bytes.toString('base64');
222
+ }
223
+ files[rel] = item;
224
+ } else files[rel] = { kind: 'other' };
225
+ }
226
+ }
227
+ try { visit(sessionDir); } catch { return null; }
228
+ return files;
229
+ }
230
+
231
+ function stateGitSnapshot(root) {
232
+ try {
233
+ const run = args => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
234
+ const head = run(['rev-parse', '--verify', 'HEAD^{commit}']).trim();
235
+ const tree = run(['rev-parse', '--verify', 'HEAD^{tree}']).trim();
236
+ const status = execFileSync('git', ['-C', root, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
237
+ encoding: null, stdio: ['ignore', 'pipe', 'pipe'],
238
+ });
239
+ const indexPath = run(['rev-parse', '--git-path', 'index']).trim();
240
+ const resolvedIndex = path.resolve(root, indexPath);
241
+ const indexDigest = fs.existsSync(resolvedIndex) ? crypto.createHash('sha256').update(fs.readFileSync(resolvedIndex)).digest('hex') : null;
242
+ return { head, tree, statusDigest: crypto.createHash('sha256').update(status).digest('hex'), indexDigest };
243
+ } catch { return null; }
244
+ }
245
+
246
+ function w6AttemptId(reviewRef) { return 'attempt-' + digestText(reviewRef).slice(0, 16); }
247
+
248
+ function outlineReviewCandidates(captures, inventoryPath) {
249
+ return (Array.isArray(captures) ? captures : []).filter(item => recordOf(item) && item.event === 'SubagentStop'
250
+ && item.agent_type === 'reviewer' && item.reviewVerdict === 'approve' && textOf(item.ref)
251
+ && Object.prototype.hasOwnProperty.call(item.reviewedArtifactDigests || {}, inventoryPath)
252
+ && Object.keys(item.reviewedArtifactDigests || {}).filter(relative => relative !== inventoryPath).length === 1);
253
+ }
254
+
255
+ function parseW6StateCommand(item, root, captures = []) {
256
+ const { getSessionDir } = require('./harness-state');
257
+ if (!recordOf(item) || !['Bash', 'PowerShell'].includes(item.tool_name) || !textOf(item.session_id)
258
+ || textOf(item.agent_id) || !textOf(item.cwd)) return null;
259
+ let cwd;
260
+ try { cwd = canonicalPath(item.cwd); } catch { return null; }
261
+ if (cwd !== canonicalPath(root)) return null;
262
+ const parsed = safeTokenize(item.command);
263
+ if (!parsed.ok || parsed.tokens.length < 3 || parsed.tokens[0] !== 'node') return null;
264
+ let script;
265
+ try { script = canonicalPath(path.resolve(cwd, parsed.tokens[1])); } catch { return null; }
266
+ const controller = canonicalPath(path.resolve(__dirname, '..', 'workflow-disposition.js'));
267
+ const producer = canonicalPath(path.resolve(__dirname, '..', 'w6-state-operations.js'));
268
+ const tokens = parsed.tokens;
269
+ let operation;
270
+ let arguments_ = {};
271
+ let destinations = [];
272
+ if (script === controller && tokens[2] === 'plan' && tokens.length === 11
273
+ && tokens[3] === '--session-id' && tokens[5] === '--strategy' && tokens[6] === 'iterative-single'
274
+ && tokens[7] === '--requirements-json' && tokens[9] === '--evidence' && textOf(tokens[10])) {
275
+ let requirements;
276
+ try { requirements = JSON.parse(tokens[8]); } catch { return null; }
277
+ if (captureJson(requirements) !== captureJson(W6_ROW17_REQUIREMENTS)) return null;
278
+ operation = 'plan'; arguments_ = { sessionId: tokens[4], evidence: tokens[10] };
279
+ destinations = ['workflow-run.json', 'workflow-obligations.json'];
280
+ } else if (script === controller && tokens[2] === 'start' && tokens.length === 5
281
+ && tokens[3] === '--session-id') {
282
+ operation = 'start'; arguments_ = { sessionId: tokens[4] };
283
+ destinations = ['workflow-run.json', 'workflow-obligations.json'];
284
+ } else if (script === controller && tokens[2] === 'binding' && tokens.length === 13
285
+ && tokens[3] === '--session-id' && tokens[5] === '--step-id' && tokens[6] === 'verify-row17'
286
+ && tokens[7] === '--binding-id' && tokens[8] === 'verification-loop'
287
+ && tokens[9] === '--disposition' && tokens[10] === 'loaded'
288
+ && tokens[11] === '--evidence' && textOf(tokens[12])) {
289
+ operation = 'binding-verify'; arguments_ = { sessionId: tokens[4], evidence: tokens[12] };
290
+ destinations = ['workflow-obligations.json'];
291
+ } else if (script === controller && tokens[2] === 'step' && tokens.length === 11
292
+ && tokens[3] === '--session-id' && tokens[5] === '--step-id'
293
+ && ['adr-evid', 'verify-row17'].includes(tokens[6])
294
+ && tokens[7] === '--disposition' && tokens[8] === 'pass'
295
+ && tokens[9] === '--evidence' && textOf(tokens[10])) {
296
+ operation = tokens[6] === 'adr-evid' ? 'step-adr' : 'step-verify';
297
+ arguments_ = { sessionId: tokens[4], stepId: tokens[6], evidence: tokens[10] };
298
+ destinations = ['workflow-obligations.json', ...(operation === 'step-verify' ? ['doc-reconciliation-pilot.json'] : [])];
299
+ } else if (script === producer && ['inventory', 'seal'].includes(tokens[2]) && tokens.length === 5
300
+ && tokens[3] === '--session-id') {
301
+ operation = tokens[2]; arguments_ = { sessionId: tokens[4] };
302
+ if (operation === 'inventory') {
303
+ destinations = [
304
+ `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(OUTLINE_INVENTORY_PIN.retainedArtifactPath)}`,
305
+ 'doc-reconciliation/outline-confirmation/inventory/inventory-pin.json',
306
+ ];
307
+ } else {
308
+ const inventoryPath = `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(OUTLINE_INVENTORY_PIN.retainedArtifactPath)}`;
309
+ const reviews = outlineReviewCandidates(captures, inventoryPath);
310
+ if (reviews.length === 1) {
311
+ const taskId = (() => {
312
+ try { return JSON.parse(fs.readFileSync(path.join(getSessionDir(cwd, item.session_id), 'workflow-run.json'), 'utf8')).docReconciliationTask?.taskId; }
313
+ catch { return null; }
314
+ })();
315
+ if (taskId) {
316
+ const attemptId = w6AttemptId(reviews[0].ref);
317
+ const attemptRoot = `doc-reconciliation/outline-confirmation/${taskId}/attempts/${attemptId}`;
318
+ destinations = [`${attemptRoot}/writer-lease.json`, `${attemptRoot}/handoff.json`];
319
+ }
320
+ }
321
+ }
322
+ } else return null;
323
+ if (arguments_.sessionId !== item.session_id) return null;
324
+ const sessionDir = getSessionDir(cwd, item.session_id);
325
+ let workflow = null;
326
+ try { workflow = JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8')); } catch { /* identity stays absent */ }
327
+ return {
328
+ schema: W6_STATE_OPERATION_SCHEMA, operation, invocationId: item.tool_use_id || '', commandDigest: digestText(item.command),
329
+ sessionId: item.session_id, principalId: item.session_id, workspaceRoot: cwd, cwd,
330
+ workflowId: workflow?.workflowId || null, workflowRevision: Number.isInteger(workflow?.revision) ? workflow.revision : null,
331
+ taskId: workflow?.docReconciliationTask?.taskId || null,
332
+ phase: ['plan', 'start', 'inventory'].includes(operation) ? 'before-o'
333
+ : operation === 'seal' ? 'review-to-dispatch' : 'post-final-review',
334
+ destinations, arguments: arguments_,
335
+ };
336
+ }
337
+
338
+ function isW6StateCommand(command, cwd, root, context = {}) {
339
+ if (typeof cwd !== 'string' || !cwd || !textOf(context.sessionId)) return false;
340
+ return Boolean(parseW6StateCommand({ tool_name: context.toolName || 'Bash', session_id: context.sessionId,
341
+ agent_id: context.agentId, cwd, command }, root, []));
342
+ }
343
+
344
+ function captureW6StateOperation(payload, eventName, record, sessionDir, workspaceRoot) {
345
+ if (!sessionDir || !workspaceRoot || !payload || !payload.tool_use_id || !payload.session_id
346
+ || typeof payload.cwd !== 'string' || !payload.cwd) return null;
347
+ const candidate = parseW6StateCommand({ ...record, event: eventName }, workspaceRoot, readCaptureView(sessionDir).records);
348
+ if (!candidate) return null;
349
+ const snapshot = stateSnapshot(sessionDir);
350
+ const git = stateGitSnapshot(workspaceRoot);
351
+ if (eventName === 'PreToolUse') return { ...candidate, state: 'pre', ref: record.ref, snapshot, git };
352
+ const records = readCaptureView(sessionDir).records;
353
+ const pres = records.filter(item => item && item.event === 'PreToolUse' && item.tool_use_id === record.tool_use_id
354
+ && item.session_id === record.session_id && item.command === record.command && item.cwd === record.cwd
355
+ && item.stateOperation?.schema === W6_STATE_OPERATION_SCHEMA);
356
+ if (pres.length !== 1) return { ...candidate, state: 'unresolved', preRef: null, snapshotAfter: snapshot, gitAfter: git };
357
+ const pre = pres[0];
358
+ return { ...pre.stateOperation, state: 'post', preRef: pre.ref, postRef: record.ref,
359
+ snapshotAfter: snapshot, gitAfter: git,
360
+ hostResult: { event: eventName, interrupted: record.interrupted, exitCode: record.exitCode,
361
+ failureDisposition: record.failureDisposition || null } };
362
+ }
363
+
192
364
  function skipHereDocBodies(command, newlineIndex, hereDocs) {
193
365
  const afterLineBreak = index => command[index] === '\r' && command[index + 1] === '\n' ? index + 2 : index + 1;
194
366
  let index = afterLineBreak(newlineIndex);
@@ -555,10 +727,18 @@ function journalExecutors(captures, author) {
555
727
  return [...executors].sort(compareKeys);
556
728
  }
557
729
 
558
- // The Agent/Task result surface that names this reviewer: a PostToolUse of the launch tool whose agent_id is the reviewer.
559
- function agentResultSurface(captures, reviewer) {
560
- return (Array.isArray(captures) ? captures : []).some(item => recordOf(item) && item.event === 'PostToolUse'
561
- && (item.tool_name === 'Agent' || item.tool_name === 'Task') && item.agent_id === reviewer);
730
+ function finalReviewResultDecision(captures, reviewer, sessionId) {
731
+ const journal = Array.isArray(captures) ? captures : [];
732
+ const results = journal.filter(item => recordOf(item) && item.event === 'PostToolUse'
733
+ && ['Agent', 'Task'].includes(item.tool_name) && item.session_id === sessionId && item.agent_id === reviewer);
734
+ if (results.length !== 1) return { accepted: false, reason: 'missing-or-ambiguous' };
735
+ const result = results[0];
736
+ if (!textOf(result.session_id) || !textOf(result.tool_use_id)) return { accepted: false, result, reason: 'missing-or-ambiguous' };
737
+ if (journal.some(item => recordOf(item) && item.event === 'PostToolUseFailure'
738
+ && item.session_id === result.session_id && item.tool_use_id === result.tool_use_id)) {
739
+ return { accepted: false, result, reason: 'matching-failure' };
740
+ }
741
+ return { accepted: true, result };
562
742
  }
563
743
 
564
744
  // A reviewed path must be a relative governed path; its digest must be a sha256 of the observed bytes.
@@ -1444,6 +1624,366 @@ function possibleWriterCapture(item) {
1444
1624
  return !['read-only', 'worktree-setup'].includes(classifyShell(item.command));
1445
1625
  }
1446
1626
 
1627
+ function stateJson(snapshot, relative) {
1628
+ const item = recordOf(snapshot) && snapshot[relative];
1629
+ return item?.kind === 'file' && recordOf(item.json) ? item.json : null;
1630
+ }
1631
+
1632
+ function row17RequirementsValid(set) {
1633
+ if (!recordOf(set) || !Array.isArray(set.requirements) || set.requirements.length !== 2) return false;
1634
+ const [adr, verify] = set.requirements;
1635
+ return adr.id === 'adr-evid' && adr.stepType === 'doc-change' && adr.status === 'pending'
1636
+ && Array.isArray(adr.requiredBindings) && adr.requiredBindings.length === 0
1637
+ && verify.id === 'verify-row17' && verify.stepType === 'verification' && verify.status === 'pending'
1638
+ && Array.isArray(verify.requiredBindings) && verify.requiredBindings.length === 1
1639
+ && verify.requiredBindings[0].id === 'verification-loop' && verify.requiredBindings[0].required === true
1640
+ && verify.requiredBindings[0].path === 'verification-loop/SKILL.md';
1641
+ }
1642
+
1643
+ function validRow17Task(workflow, root, expectedBaseline) {
1644
+ const task = workflow?.docReconciliationTask;
1645
+ const baseline = workflow?.docReconciliationBaseline;
1646
+ return recordOf(task) && task.schema === 'harness.doc-reconciliation-task-pin.v1'
1647
+ && captureJson(task.requirementIds) === captureJson(['adr-evid', 'verify-row17'])
1648
+ && task.taskId === 'task-adr-evid+verify-row17'
1649
+ && task.requirementDigest === digestText(JSON.stringify(['adr-evid', 'verify-row17']))
1650
+ && task.sessionId === workflow.sessionId && task.workflowId === workflow.workflowId
1651
+ && task.baselineCommit === baseline?.commit && samePathKey(task.baselineRoot, baseline?.root)
1652
+ && task.workflowId === workflow.workflowId && task.workspaceId === outlineWorkspaceId(root)
1653
+ && HEX64.test(String(task.configDigest || ''))
1654
+ && samePathKey(baseline?.root, root)
1655
+ && (!expectedBaseline || (baseline?.commit === expectedBaseline.head && baseline?.tree === expectedBaseline.tree));
1656
+ }
1657
+
1658
+ function taskScopedFinalReviewBoundary(captures, review, taskId, dispositionPre = null) {
1659
+ const journal = Array.isArray(captures) ? captures : [];
1660
+ const fail = reason => ({ scoped: true, accepted: false, reason });
1661
+ if (!textOf(taskId)) return { scoped: false, accepted: true };
1662
+ const dispatches = journal.filter(item => recordOf(item) && item.event === 'PreToolUse'
1663
+ && ['Agent', 'Task'].includes(item.tool_name) && item.outlineDispatch?.state === 'accepted'
1664
+ && item.outlineDispatch.taskId === taskId);
1665
+ if (!dispatches.length) return { scoped: false, accepted: true };
1666
+ if (dispatches.length !== 1) return fail('outline-worker-dispatch-missing-or-ambiguous');
1667
+ const dispatchPre = dispatches[0];
1668
+ const dispatchIndex = journal.indexOf(dispatchPre);
1669
+ const reviewIndex = journal.indexOf(review);
1670
+ if (dispatchIndex < 0 || reviewIndex < 0) return fail('final-review-journal-position-unavailable');
1671
+ if (reviewIndex < dispatchIndex) return { scoped: false, accepted: true };
1672
+ const worker = correlateOutlineDispatch(journal, dispatchPre);
1673
+ if (worker.state !== 'accepted') return fail(worker.reason || 'outline-worker-completion-unresolved');
1674
+ const workerStopIndex = journal.indexOf(worker.stop);
1675
+ const workerResultIndex = journal.indexOf(worker.result);
1676
+ if (workerStopIndex < 0 || workerResultIndex < 0) return fail('outline-worker-journal-position-unavailable');
1677
+ // Stop and Agent result are independent host callbacks; require both before the next phase without ordering them.
1678
+ const workerClosed = Math.max(workerStopIndex, workerResultIndex);
1679
+ const reviewer = review?.agent_id;
1680
+ if (!textOf(reviewer) || review.event !== 'SubagentStop' || review.agent_type !== 'reviewer') {
1681
+ return fail('final-review-principal-missing-or-invalid');
1682
+ }
1683
+ const resultDecision = finalReviewResultDecision(journal, reviewer, dispatchPre.session_id);
1684
+ const result = resultDecision.result;
1685
+ const starts = journal.filter(item => recordOf(item) && item.event === 'SubagentStart'
1686
+ && item.session_id === dispatchPre.session_id && item.agent_id === reviewer);
1687
+ const stops = journal.filter(item => recordOf(item) && item.event === 'SubagentStop'
1688
+ && item.session_id === dispatchPre.session_id && item.agent_id === reviewer);
1689
+ if (!resultDecision.accepted || !result || starts.length !== 1 || stops.length !== 1 || stops[0] !== review
1690
+ || starts[0].agent_type !== 'reviewer' || result.interrupted !== false
1691
+ || outlineResultStatus(result).value !== 'completed') {
1692
+ if (resultDecision.reason === 'matching-failure') return fail('final-review-result-failed');
1693
+ return fail('final-review-lifecycle-missing-or-ambiguous');
1694
+ }
1695
+ const launchPres = journal.filter(item => recordOf(item) && item.event === 'PreToolUse'
1696
+ && ['Agent', 'Task'].includes(item.tool_name) && item.tool_use_id === result.tool_use_id);
1697
+ if (launchPres.length > 1 || (launchPres.length === 1 && launchPres[0].session_id !== dispatchPre.session_id)) {
1698
+ return fail('final-review-launch-missing-or-ambiguous');
1699
+ }
1700
+ const launchPre = launchPres[0] || null;
1701
+ const expectedIdentity = dispatchPre.observedIdentity;
1702
+ if (!recordOf(expectedIdentity) || !recordOf(expectedIdentity.taskPin)
1703
+ || expectedIdentity.taskPin.taskId !== taskId) return fail('final-review-task-identity-unavailable');
1704
+ const sameTask = item => item?.session_id === dispatchPre.session_id && recordOf(item.observedIdentity)
1705
+ && item.observedIdentity.workflowId === expectedIdentity.workflowId
1706
+ && item.observedIdentity.workflowRevision === expectedIdentity.workflowRevision
1707
+ && sameOutlineTaskBinding(item.observedIdentity.taskPin, expectedIdentity.taskPin)
1708
+ && item.observedIdentity.baselinePin?.commit === expectedIdentity.baselinePin?.commit
1709
+ && samePathKey(item.observedIdentity.baselinePin?.root, expectedIdentity.baselinePin?.root);
1710
+ if (![review, result, starts[0], ...(launchPre ? [launchPre] : [])].every(sameTask)) {
1711
+ return fail('final-review-task-correlation-mismatch');
1712
+ }
1713
+ const reviewRoot = launchPre?.cwd || starts[0].cwd;
1714
+ if (!textOf(reviewRoot) || !path.isAbsolute(reviewRoot)
1715
+ || !samePathKey(reviewRoot, dispatchPre.cwd)
1716
+ || ![review, result, starts[0], ...(launchPre ? [launchPre] : [])]
1717
+ .every(item => textOf(item.cwd) && path.isAbsolute(item.cwd) && samePathKey(item.cwd, reviewRoot))) {
1718
+ return fail('final-review-root-correlation-mismatch');
1719
+ }
1720
+ const startIndex = journal.indexOf(starts[0]);
1721
+ const resultIndex = journal.indexOf(result);
1722
+ if (startIndex <= workerClosed || resultIndex <= startIndex || reviewIndex <= startIndex) {
1723
+ return fail('final-review-before-worker-closure');
1724
+ }
1725
+ if (launchPre) {
1726
+ const launchPreIndex = journal.indexOf(launchPre);
1727
+ if (launchPre.tool_name !== result.tool_name || launchPreIndex < 0 || launchPreIndex >= startIndex
1728
+ || launchPreIndex <= workerClosed) return fail('final-review-before-worker-closure');
1729
+ }
1730
+ const reviewClosed = Math.max(resultIndex, reviewIndex);
1731
+ if (dispositionPre) {
1732
+ const dispositionIndex = journal.indexOf(dispositionPre);
1733
+ if (dispositionIndex <= reviewClosed || dispositionPre.session_id !== dispatchPre.session_id
1734
+ || !samePathKey(dispositionPre.cwd, dispatchPre.cwd)
1735
+ || dispositionPre.stateOperation?.taskId !== taskId) return fail('final-review-not-closed-before-disposition');
1736
+ }
1737
+ return { scoped: true, accepted: true, workerClosed, reviewClosed, dispatchPre, worker };
1738
+ }
1739
+
1740
+ function validW6Phase(operation, captures, pre, requireCompletePath = false) {
1741
+ const index = captures.indexOf(pre);
1742
+ const outliner = captures.find(item => recordOf(item) && item.event === 'SubagentStop'
1743
+ && item.agent_type === 'reviewer' && item.reviewVerdict === 'approve'
1744
+ && Object.keys(item.reviewedArtifactDigests || {}).some(target => target !== `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(OUTLINE_INVENTORY_PIN.retainedArtifactPath)}`));
1745
+ const outlineStart = outliner && captures.find(item => item.event === 'SubagentStart' && item.agent_id === outliner.agent_id);
1746
+ const outlineIndex = outliner ? captures.indexOf(outliner) : -1;
1747
+ const outlineStartIndex = outlineStart ? captures.indexOf(outlineStart) : -1;
1748
+ const dispatchIndex = captures.findIndex(item => recordOf(item) && item.event === 'PreToolUse'
1749
+ && ['Agent', 'Task'].includes(item.tool_name) && item.outlineDispatch?.state === 'accepted');
1750
+ const taskId = pre?.stateOperation?.taskId;
1751
+ const finalReviewCandidates = captures.filter(item => recordOf(item) && item.event === 'SubagentStop' && item.agent_type === 'reviewer'
1752
+ && item.reviewVerdict === 'approve' && item.agent_id !== outliner?.agent_id);
1753
+ const taskReviews = finalReviewCandidates.map(review => ({ review,
1754
+ boundary: taskScopedFinalReviewBoundary(captures, review, taskId, pre) })).filter(item => item.boundary.scoped);
1755
+ const finalReview = taskReviews.length === 1 && taskReviews[0].boundary.accepted ? taskReviews[0].review : null;
1756
+ const finalReviewBoundary = taskReviews.length === 1 ? taskReviews[0].boundary : null;
1757
+ const finalReviewIndex = finalReview ? captures.indexOf(finalReview) : -1;
1758
+ const finalReviewPaths = finalReview ? Object.keys(finalReview.reviewedArtifactDigests || {}) : [];
1759
+ const finalReviewValid = Boolean(finalReview && finalReviewBoundary?.accepted && finalReviewPaths.length === 1
1760
+ && validOutlineTarget(finalReviewPaths[0])
1761
+ && (() => {
1762
+ try { return shaBytes(fs.readFileSync(path.join(pre.cwd, ...finalReviewPaths[0].split('/')))) === finalReview.reviewedArtifactDigests[finalReviewPaths[0]]
1763
+ && reviewRecordIndependent(finalReview, captures, { author: pre.session_id,
1764
+ executors: journalExecutors(captures, pre.session_id) }); }
1765
+ catch { return false; }
1766
+ })());
1767
+ if (['plan', 'start', 'inventory'].includes(operation)) {
1768
+ return index >= 0 && (requireCompletePath
1769
+ ? outlineStartIndex > index && dispatchIndex > outlineIndex
1770
+ : outlineStartIndex < 0 && dispatchIndex < 0);
1771
+ }
1772
+ if (operation === 'seal') return outlineIndex >= 0 && index > outlineIndex
1773
+ && (requireCompletePath ? index < dispatchIndex : dispatchIndex < 0);
1774
+ return finalReviewValid && finalReviewIndex >= 0 && index > finalReviewBoundary.reviewClosed;
1775
+ }
1776
+
1777
+ function allowedW6SnapshotChanges(operation, destinations) {
1778
+ const allowed = new Set();
1779
+ for (const destination of destinations) {
1780
+ allowed.add(destination);
1781
+ const parts = destination.split('/');
1782
+ while (parts.length > 1) { parts.pop(); allowed.add(parts.join('/')); }
1783
+ }
1784
+ if (operation === 'step-verify') allowed.add('doc-reconciliation-pilot.json');
1785
+ return allowed;
1786
+ }
1787
+
1788
+ function snapshotChanges(before, after) {
1789
+ if (!recordOf(before) || !recordOf(after)) return null;
1790
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
1791
+ return [...keys].filter(relative => captureJson(before[relative] ?? null) !== captureJson(after[relative] ?? null)).sort(compareKeys);
1792
+ }
1793
+
1794
+ function operationTransitionValid(operation, preOp, postOp, preCapture, sessionDir, root) {
1795
+ const before = preOp.snapshot;
1796
+ const after = postOp.snapshotAfter;
1797
+ const preWorkflow = stateJson(before, 'workflow-run.json');
1798
+ const postWorkflow = stateJson(after, 'workflow-run.json');
1799
+ const preSet = stateJson(before, 'workflow-obligations.json');
1800
+ const postSet = stateJson(after, 'workflow-obligations.json');
1801
+ const preTask = preWorkflow?.docReconciliationTask;
1802
+ const postTask = postWorkflow?.docReconciliationTask;
1803
+ const changed = snapshotChanges(before, after);
1804
+ if (!changed) return false;
1805
+ const allowed = allowedW6SnapshotChanges(operation, preOp.destinations);
1806
+ if (changed.some(relative => !allowed.has(relative)) || preOp.destinations.some(relative => !changed.includes(relative))) return false;
1807
+ if (operation !== 'plan' && !validRow17Task(preWorkflow, root)) return false;
1808
+ if (!postWorkflow || postWorkflow.sessionId !== preCapture.session_id
1809
+ || postWorkflow.workflowId !== preOp.workflowId) return false;
1810
+
1811
+ if (operation === 'plan') {
1812
+ const expected = preOp.git;
1813
+ return ['pending', 'active'].includes(preWorkflow?.state)
1814
+ && !preTask
1815
+ && textOf(preWorkflow.workflowPlan?.strategy)
1816
+ && postWorkflow.pendingPlan?.strategy === 'iterative-single'
1817
+ && postWorkflow.sessionId === preCapture.session_id
1818
+ && postTask?.taskId === 'task-adr-evid+verify-row17'
1819
+ && validRow17Task(postWorkflow, root, expected)
1820
+ && row17RequirementsValid(postSet)
1821
+ && !postWorkflow.workflowStages?.length;
1822
+ }
1823
+ if (operation === 'start') {
1824
+ return preWorkflow?.state !== 'running' && postWorkflow.state === 'running'
1825
+ && postWorkflow.revision === preWorkflow.revision + 1
1826
+ && postWorkflow.workflowPlan?.strategy === 'iterative-single' && !postWorkflow.pendingPlan
1827
+ && validRow17Task(postWorkflow, root, preOp.git)
1828
+ && row17RequirementsValid({ ...postSet, requirements: postSet?.requirements?.map(item => ({ ...item, status: 'pending' })) });
1829
+ }
1830
+ if (operation === 'inventory') {
1831
+ const expectedPin = OUTLINE_INVENTORY_PIN;
1832
+ const pinRel = 'doc-reconciliation/outline-confirmation/inventory/inventory-pin.json';
1833
+ const artifactRel = `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(expectedPin.retainedArtifactPath)}`;
1834
+ const pin = stateJson(after, pinRel);
1835
+ const artifact = after[artifactRel];
1836
+ const bytes = artifact?.content ? Buffer.from(artifact.content, 'base64') : null;
1837
+ const validated = bytes && validateOutlineInventoryPin({ bytes, pin, expectedPin });
1838
+ return validRow17Task(preWorkflow, root) && preWorkflow.state === 'running'
1839
+ && preOp.git?.head === preTask?.baselineCommit && preOp.git?.tree === preWorkflow.docReconciliationBaseline?.tree
1840
+ && captureJson(pin) === captureJson(expectedPin) && validated?.state === 'accepted'
1841
+ && resolveInventoryRow(validated, '17').row?.domain === 'EVID';
1842
+ }
1843
+ if (operation === 'seal') {
1844
+ const handoffRel = preOp.destinations.find(relative => relative.endsWith('/handoff.json'));
1845
+ const leaseRel = preOp.destinations.find(relative => relative.endsWith('/writer-lease.json'));
1846
+ const handoff = stateJson(after, handoffRel);
1847
+ const lease = stateJson(after, leaseRel);
1848
+ const inventoryRel = `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(OUTLINE_INVENTORY_PIN.retainedArtifactPath)}`;
1849
+ const pinRel = 'doc-reconciliation/outline-confirmation/inventory/inventory-pin.json';
1850
+ const inventoryBytes = after[inventoryRel]?.content && Buffer.from(after[inventoryRel].content, 'base64');
1851
+ const inventory = inventoryBytes && validateOutlineInventoryPin({ bytes: inventoryBytes, pin: stateJson(after, pinRel), expectedPin: OUTLINE_INVENTORY_PIN });
1852
+ const attemptDir = handoffRel && path.posix.dirname(handoffRel);
1853
+ const expectedReview = outlineReviewCandidates(capturesFromSnapshotContext(preCapture, sessionDir), inventoryRel);
1854
+ const review = expectedReview.length === 1 ? expectedReview[0] : null;
1855
+ const target = handoff?.targetPaths?.[0];
1856
+ let targetBytes = null;
1857
+ try { if (target) targetBytes = outlineGit(root, ['show', `${handoff.outline.commit}:${target}`], true); } catch { /* fail closed below */ }
1858
+ return Boolean(handoff && lease && review && inventory?.state === 'accepted'
1859
+ && handoff.schema === OUTLINE_HANDOFF_SCHEMA && handoff.taskId === postTask?.taskId
1860
+ && handoff.attemptId === path.posix.basename(attemptDir) && handoff.workflowId === postWorkflow.workflowId
1861
+ && handoff.workflowRevision === postWorkflow.revision && handoff.sessionId === preCapture.session_id
1862
+ && handoff.baseline?.commit === preWorkflow.docReconciliationBaseline?.commit
1863
+ && handoff.baseline?.tree === preWorkflow.docReconciliationBaseline?.tree
1864
+ && handoff.outline?.commit === preOp.git?.head && handoff.outline?.tree === preOp.git?.tree
1865
+ && handoff.reviewCaptureRef === review.ref && handoff.reviewDigest === review.reviewDigest
1866
+ && handoff.reviewCaptureDigest === captureDigest(review) && lease.schema === OUTLINE_LEASE_SCHEMA
1867
+ && lease.taskId === handoff.taskId && lease.attemptId === handoff.attemptId && lease.principalId === preCapture.session_id
1868
+ && lease.exclusive === true && lease.active === true && sameCanonicalPath(lease.root, root)
1869
+ && targetBytes && shaBytes(targetBytes) === handoff.outline.targetBlobs?.[target]?.storedBytesSha256
1870
+ && captureJson(handoff.targetPaths) === captureJson([target]));
1871
+ }
1872
+ if (operation === 'binding-verify') {
1873
+ const beforeVerify = preSet?.requirements?.find(item => item.id === 'verify-row17');
1874
+ const afterVerify = postSet?.requirements?.find(item => item.id === 'verify-row17');
1875
+ return postWorkflow.state === 'running' && beforeVerify?.status === 'pending'
1876
+ && preSet?.requirements?.[0]?.status === 'pass'
1877
+ && afterVerify?.status === 'pending' && afterVerify.requiredBindings?.length === 1
1878
+ && afterVerify.requiredBindings[0].id === 'verification-loop'
1879
+ && afterVerify.requiredBindings[0].status === 'loaded'
1880
+ && afterVerify.requiredBindings[0].availability === 'available'
1881
+ && afterVerify.requiredBindings[0].path === 'verification-loop/SKILL.md';
1882
+ }
1883
+ if (operation === 'step-adr' || operation === 'step-verify') {
1884
+ const stepId = operation === 'step-adr' ? 'adr-evid' : 'verify-row17';
1885
+ const beforeStep = preSet?.requirements?.find(item => item.id === stepId);
1886
+ const afterStep = postSet?.requirements?.find(item => item.id === stepId);
1887
+ const report = operation === 'step-verify' ? stateJson(after, 'doc-reconciliation-pilot.json') : null;
1888
+ return postWorkflow.state === 'running' && beforeStep?.status === 'pending' && afterStep?.status === 'pass'
1889
+ && textOf(afterStep.evidence) && (operation === 'step-adr'
1890
+ ? postSet.requirements.find(item => item.id === 'verify-row17')?.status === 'pending'
1891
+ : preSet.requirements.find(item => item.id === 'adr-evid')?.status === 'pass'
1892
+ && preSet.requirements.find(item => item.id === 'verify-row17')?.requiredBindings?.[0]?.status === 'loaded'
1893
+ && report?.pilotCredit === false && report?.pilotStatus === 'pending');
1894
+ }
1895
+ return false;
1896
+ }
1897
+
1898
+ function capturesFromSnapshotContext(preCapture, sessionDir) {
1899
+ return readCaptureView(sessionDir).records.filter(item => item.ref && item.ref !== preCapture.ref);
1900
+ }
1901
+
1902
+ function shaBytes(bytes) { return crypto.createHash('sha256').update(bytes).digest('hex'); }
1903
+
1904
+ function validateW6StateOperationPair(captures, pre, sessionDir, options = {}) {
1905
+ const op = pre?.stateOperation;
1906
+ if (!recordOf(op) || op.schema !== W6_STATE_OPERATION_SCHEMA || op.state !== 'pre'
1907
+ || pre.event !== 'PreToolUse' || !pre.tool_use_id || op.invocationId !== pre.tool_use_id
1908
+ || pre.session_id !== op.sessionId || pre.session_id !== op.principalId || textOf(pre.agent_id)
1909
+ || !sameCanonicalPath(pre.cwd, op.workspaceRoot)
1910
+ || op.phase !== (['plan', 'start', 'inventory'].includes(op.operation) ? 'before-o'
1911
+ : op.operation === 'seal' ? 'review-to-dispatch' : 'post-final-review')) return { accepted: false };
1912
+ const pairPosts = captures.filter(item => recordOf(item) && item.event === 'PostToolUse'
1913
+ && item.session_id === pre.session_id && item.tool_use_id === pre.tool_use_id);
1914
+ const failures = captures.filter(item => recordOf(item) && item.event === 'PostToolUseFailure'
1915
+ && item.session_id === pre.session_id && item.tool_use_id === pre.tool_use_id);
1916
+ if (!pairPosts.length && !failures.length && options.allowInFlightToolUseId === pre.tool_use_id
1917
+ && op.operation === 'step-verify' && validW6Phase(op.operation, captures, pre)
1918
+ && stateJson(op.snapshot, 'workflow-obligations.json')?.requirements?.find(item => item.id === 'verify-row17')?.status === 'pending') {
1919
+ return { accepted: true, inFlight: true, operation: op.operation, pre, toolUseId: pre.tool_use_id };
1920
+ }
1921
+ if (pairPosts.length !== 1 || failures.length || pairPosts[0].stateOperation?.schema !== W6_STATE_OPERATION_SCHEMA
1922
+ || pairPosts[0].stateOperation.state !== 'post' || pairPosts[0].stateOperation.preRef !== pre.ref
1923
+ || pairPosts[0].stateOperation.operation !== op.operation || pairPosts[0].tool_name !== pre.tool_name
1924
+ || pairPosts[0].command !== pre.command || pairPosts[0].cwd !== pre.cwd
1925
+ || pairPosts[0].interrupted !== false || (pairPosts[0].exitCode !== undefined && pairPosts[0].exitCode !== 0)) {
1926
+ return { accepted: false, operation: op.operation, pre, reason: 'host-result-incomplete' };
1927
+ }
1928
+ const postOp = pairPosts[0].stateOperation;
1929
+ if (postOp.workflowId !== op.workflowId || postOp.workspaceRoot !== op.workspaceRoot
1930
+ || postOp.workflowRevision !== op.workflowRevision || postOp.taskId !== op.taskId
1931
+ || !Array.isArray(postOp.destinations) || captureJson(postOp.destinations) !== captureJson(op.destinations)
1932
+ || captureJson(postOp.arguments) !== captureJson(op.arguments)
1933
+ || !postOp.snapshotAfter || !postOp.gitAfter || captureJson(op.git) !== captureJson(postOp.gitAfter)
1934
+ || postOp.git?.head !== op.git?.head || postOp.git?.tree !== op.git?.tree
1935
+ || !validW6Phase(op.operation, captures, pre, options.requireCompletePath === true)
1936
+ || !operationTransitionValid(op.operation, op, postOp, pre, sessionDir, op.workspaceRoot)) {
1937
+ return { accepted: false, operation: op.operation, pre, post: pairPosts[0], reason: 'state-transition-invalid' };
1938
+ }
1939
+ return { accepted: true, operation: op.operation, pre, post: pairPosts[0], toolUseId: pre.tool_use_id };
1940
+ }
1941
+
1942
+ function evaluateW6StateOperations(captures, sessionDir, options = {}) {
1943
+ const records = Array.isArray(captures) ? captures : [];
1944
+ const taskState = outlineTaskState(sessionDir);
1945
+ const required = taskState.state === 'accepted'
1946
+ && captureJson(taskState.taskBinding.requirementIds) === captureJson(['adr-evid', 'verify-row17']);
1947
+ if (!required) return { required: false, acceptedToolUseIds: new Set(), operations: [], complete: true };
1948
+ const candidates = records.filter(item => recordOf(item) && item.event === 'PreToolUse'
1949
+ && item.stateOperation?.schema === W6_STATE_OPERATION_SCHEMA);
1950
+ const results = candidates.map(pre => validateW6StateOperationPair(records, pre, sessionDir,
1951
+ { ...options, requireCompletePath: true }));
1952
+ const accepted = results.filter(item => item.accepted);
1953
+ const byOperation = operation => accepted.filter(item => item.operation === operation);
1954
+ const expected = ['plan', 'start', 'inventory', 'seal', 'step-adr', 'binding-verify', 'step-verify'];
1955
+ const countsValid = expected.every(operation => byOperation(operation).length === 1)
1956
+ && accepted.length === expected.length;
1957
+ const ordered = expected.map(operation => byOperation(operation)[0]).filter(Boolean);
1958
+ const orderValid = ordered.every((item, index) => index === 0 || records.indexOf(ordered[index - 1].pre) < records.indexOf(item.pre));
1959
+ const inFlightAllowed = options.allowInFlightToolUseId
1960
+ && results.some(item => item.accepted && item.inFlight && item.toolUseId === options.allowInFlightToolUseId);
1961
+ const complete = countsValid && orderValid && !accepted.some(item => item.inFlight);
1962
+ return { required: true, complete, inFlightAllowed: Boolean(inFlightAllowed),
1963
+ readyForAssessment: countsValid && orderValid && (complete || Boolean(inFlightAllowed)), operations: accepted,
1964
+ acceptedToolUseIds: new Set(accepted.map(item => item.toolUseId)), results };
1965
+ }
1966
+
1967
+ function isVerifiedW6StateOperation(captures, sessionDir, toolUseId) {
1968
+ const records = Array.isArray(captures) ? captures : [];
1969
+ const pre = records.find(item => item?.event === 'PreToolUse' && item.tool_use_id === toolUseId
1970
+ && item.stateOperation?.schema === W6_STATE_OPERATION_SCHEMA);
1971
+ return Boolean(pre && validateW6StateOperationPair(records, pre, sessionDir).accepted);
1972
+ }
1973
+
1974
+ function pendingW6VerificationInvocation(context) {
1975
+ const captures = readCaptureView(context.sessionDir);
1976
+ if (captures.tampered) return null;
1977
+ const records = captures.records;
1978
+ const pending = records.filter(item => item?.event === 'PreToolUse' && item.stateOperation?.schema === W6_STATE_OPERATION_SCHEMA
1979
+ && item.stateOperation.operation === 'step-verify' && item.stateOperation.state === 'pre');
1980
+ if (pending.length !== 1) return null;
1981
+ const checked = validateW6StateOperationPair(records, pending[0], context.sessionDir, {
1982
+ allowInFlightToolUseId: pending[0].tool_use_id,
1983
+ });
1984
+ return checked.accepted && checked.inFlight ? checked.toolUseId : null;
1985
+ }
1986
+
1447
1987
  function writeTargetsOf(toolName, toolInput) {
1448
1988
  if (toolName === 'apply_patch') {
1449
1989
  const patch = typeof toolInput === 'string' ? toolInput : (recordOf(toolInput) ? String(toolInput.patch || toolInput.input || '') : '');
@@ -1611,7 +2151,10 @@ function outlineGitTreeHasRegularBlob(root, tree, target) {
1611
2151
  // target-bound git add or simple git commit before review; the correlated draft worker
1612
2152
  // between dispatch and its Stop. Everything else, including any coordinator state write after review, stays ambiguous.
1613
2153
  function outlineWriterAllowed(item, { index, sessionId, root, targets, worker, workerRoot, reviewStartIndex, reviewStopIndex,
1614
- dispatchIndex, workerStopIndex, captures }) {
2154
+ dispatchIndex, workerStopIndex, captures, stateOperationToolUseIds = new Set() }) {
2155
+ if (item?.stateOperation?.schema === W6_STATE_OPERATION_SCHEMA
2156
+ && stateOperationToolUseIds.has(item.tool_use_id) && item.session_id === sessionId && !textOf(item.agent_id)
2157
+ && ['PreToolUse', 'PostToolUse'].includes(item.event) && sameCanonicalPath(item.cwd, root)) return true;
1615
2158
  const phase = index < reviewStartIndex ? 'b-to-o' : index <= reviewStopIndex ? 'review'
1616
2159
  : index < dispatchIndex ? 'review-to-dispatch' : index <= workerStopIndex ? 'dispatch-to-draft' : 'after-draft';
1617
2160
  if (phase === 'dispatch-to-draft') return item.agent_id === worker.agent_id && sameCanonicalPath(item.cwd, workerRoot);
@@ -1807,6 +2350,11 @@ function resolveOutlineEvidence({ safeInput, capture, captures, request, originR
1807
2350
  || (textOf(item.tool_use_id) && reviewLaunchIds.has(item.tool_use_id)))),
1808
2351
  reviewStopIndex: journal.indexOf(review.review), dispatchIndex, workerStopIndex: journal.indexOf(correlation.stop),
1809
2352
  };
2353
+ const stateOperations = evaluateW6StateOperations(journal, sessionDir, {
2354
+ allowInFlightToolUseId: safeInput.allowInFlightW6ToolUseId,
2355
+ });
2356
+ if (stateOperations.required && !stateOperations.readyForAssessment) return fail('outline-state-operation-unresolved');
2357
+ writerWindow.stateOperationToolUseIds = stateOperations.required ? stateOperations.acceptedToolUseIds : new Set();
1810
2358
  const unattributedWriters = journal.filter((item, index) => possibleWriterCapture(item)
1811
2359
  && !outlineWriterAllowed(item, { ...writerWindow, index }));
1812
2360
  if (unattributedWriters.length) return fail('outline-writer-activity-ambiguous');
@@ -2306,8 +2854,17 @@ const createClaudeOriginProvider = input => {
2306
2854
  return rejected('reviewer-not-independent', 'the reviewer agent_id equals an executor principal; not independent');
2307
2855
  }
2308
2856
  // An approval needs its own correlated Agent/Task result surface, never a bare SubagentStop (F5).
2309
- if (!agentResultSurface(captures, reviewer)) {
2310
- return rejected('agent-result-missing', 'no correlated Agent/Task result names this reviewer agent_id; without that surface the review is not approved');
2857
+ const resultDecision = finalReviewResultDecision(captures, reviewer, cap.session_id);
2858
+ if (!resultDecision.accepted) {
2859
+ const code = resultDecision.reason === 'matching-failure' ? 'agent-result-failed' : 'agent-result-missing';
2860
+ return rejected(code, 'a correlated Agent/Task result for this review session must exist without a matching launch failure');
2861
+ }
2862
+ if (capability === 'quality-review') {
2863
+ const taskId = safeInput.taskBinding?.taskId || safeInput.taskId;
2864
+ const boundary = taskScopedFinalReviewBoundary(captures, cap, taskId);
2865
+ if (boundary.scoped && !boundary.accepted) {
2866
+ return rejected('final-review-before-worker-closure', 'an outline-backed final review must launch after the correlated worker Stop and completed Agent result');
2867
+ }
2311
2868
  }
2312
2869
  if (!HEX64.test(String(cap.reviewDigest === undefined ? '' : cap.reviewDigest))) {
2313
2870
  return rejected('review-digest-missing', 'SubagentStop without a bound final review artifact digest cannot close a review');
@@ -2493,7 +3050,7 @@ const createOpencodeOriginProvider = input => {
2493
3050
  // supported capture event.
2494
3051
  let captureSequence = 0;
2495
3052
 
2496
- function buildCaptureRecord(payload, eventName, workspaceRoot) {
3053
+ function buildCaptureRecord(payload, eventName, workspaceRoot, options = {}) {
2497
3054
  if (!recordOf(payload)) return null;
2498
3055
  const event = typeof eventName === 'string' ? eventName : (payload.hook_event_name || payload.hookEventName || '');
2499
3056
  if (['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'SubagentStart', 'SubagentStop'].indexOf(event) === -1) return null;
@@ -2501,6 +3058,7 @@ function buildCaptureRecord(payload, eventName, workspaceRoot) {
2501
3058
  if (event === 'PreToolUse' && PRE_CAPTURE_TOOLS.indexOf(payload.tool_name) === -1) return null;
2502
3059
  const toolInput = recordOf(payload.tool_input) ? payload.tool_input : {};
2503
3060
  const toolResponse = payload.tool_response;
3061
+ const rawExitCode = recordOf(toolResponse) ? (toolResponse.exitCode ?? toolResponse.exit_code) : payload.exitCode;
2504
3062
  const outlinePre = event === 'PreToolUse' && ['Task', 'Agent'].includes(payload.tool_name);
2505
3063
  const outlineResult = event === 'PostToolUse' && ['Task', 'Agent'].includes(payload.tool_name);
2506
3064
  // Demonstrated alias mapping (doc: "Host result aliases such as agentId
@@ -2520,6 +3078,7 @@ function buildCaptureRecord(payload, eventName, workspaceRoot) {
2520
3078
  responseDigest: captureDigest(toolResponse),
2521
3079
  responseRef: `host-payload/${event}/${captureId}`,
2522
3080
  };
3081
+ if (typeof rawExitCode === 'number') record.exitCode = rawExitCode;
2523
3082
  const parsedWriterCommand = event === 'PreToolUse' && payload.tool_name === 'Bash'
2524
3083
  ? safeTokenize(record.command.trim()) : null;
2525
3084
  const writerMayNeedCwd = OUTLINE_WRITE_TOOLS.includes(payload.tool_name)
@@ -2631,6 +3190,8 @@ function buildCaptureRecord(payload, eventName, workspaceRoot) {
2631
3190
  record.reviewedArtifactDigests = verdict ? verdict.reviewedArtifactDigests : {};
2632
3191
  if (payload.agent_transcript_path !== undefined) record.agentTranscriptPath = payload.agent_transcript_path;
2633
3192
  }
3193
+ const stateOperation = captureW6StateOperation(payload, event, record, options.sessionDir, workspaceRoot);
3194
+ if (stateOperation) record.stateOperation = stateOperation;
2634
3195
  return record;
2635
3196
  }
2636
3197
 
@@ -2723,7 +3284,7 @@ function reviewRecordIndependent(cap, captures, principals) {
2723
3284
  const executors = [...new Set([...(recordOf(principals) && Array.isArray(principals.executors) ? principals.executors : []),
2724
3285
  ...journalExecutors(captures, principals.author)])];
2725
3286
  if (cap.agent_id === principals.author || executors.includes(cap.agent_id)) return false;
2726
- if (!agentResultSurface(captures, cap.agent_id)) return false;
3287
+ if (!finalReviewResultDecision(captures, cap.agent_id, cap.session_id).accepted) return false;
2727
3288
  if (!HEX64.test(String(cap.reviewDigest === undefined ? '' : cap.reviewDigest))) return false;
2728
3289
  if (!reviewedDigestsValid(cap.reviewedArtifactDigests)) return false;
2729
3290
  return cap.reviewVerdict === 'approve' && textOf(cap.reviewSummary);
@@ -2734,8 +3295,10 @@ module.exports = { createClaudeOriginProvider, createOpencodeOriginProvider, bui
2734
3295
  registeredInstalledCheck: resolveDocCheckInvocation, installedDocCheck,
2735
3296
  fileDigest, SHIPPED_DOC_CHECK_DIGEST, trustRisk, journalExecutors, reviewRecordIndependent,
2736
3297
  captureOutlineDispatch, captureOutlineStartIdentity, writeImmutableEvent, rebuildJournalView, readCaptureView,
2737
- readOpencodeCaptureView, observedIdentityFor,
2738
- _internals: { validateOutlineIdentity, captureJson, captureDigest, digestText, canonicalCapture, parseOutlineDispatchPrompt,
3298
+ readOpencodeCaptureView, observedIdentityFor, isW6StateCommand, isVerifiedW6StateOperation, pendingW6VerificationInvocation,
3299
+ _internals: { validateOutlineIdentity, captureJson, captureDigest, digestText, canonicalCapture, safeTokenize, parseOutlineDispatchPrompt,
2739
3300
  parseInventoryPinRows, validateOutlineInventoryPin, resolveInventoryRow, parseOutlineCitation, resolveOutlineAttempt,
3301
+ validateOutlineReview,
2740
3302
  captureOutlineDispatch, resolveOutlineEvidence, verifyOutlineMergeCorrespondence, validateOutlineCaptureQualification,
2741
- outlineCaptureMappingValid, correlateOutlineDispatch, OUTLINE_CAPTURE_MAPPING, OUTLINE_INVENTORY_PIN } };
3303
+ outlineCaptureMappingValid, correlateOutlineDispatch, evaluateW6StateOperations, validateW6StateOperationPair,
3304
+ OUTLINE_CAPTURE_MAPPING, OUTLINE_INVENTORY_PIN, W6_STATE_OPERATION_SCHEMA, W6_ROW17_REQUIREMENTS } };