harness-everything 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +14 -0
- package/behavioral-evals/ledger-pairs/README.md +53 -0
- package/behavioral-evals/ledger-pairs/arm.js +359 -0
- package/behavioral-evals/ledger-pairs/fixture.js +138 -0
- package/behavioral-evals/ledger-pairs/preflight.js +96 -0
- package/behavioral-evals/ledger-pairs/score.js +155 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/README.md +108 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-result.json +28 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-result.json +35 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-result.json +56 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-result.json +56 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-result.json +56 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-result.json +56 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-result.json +49 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-result.json +49 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-result.json +49 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-plan.json +13 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-result.json +56 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-result.json +44 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/receipt.jsonl +17 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-result.json +41 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/receipt.jsonl +58 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-result.json +50 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/receipt.jsonl +101 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-result.json +44 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/receipt.jsonl +29 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-result.json +44 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/receipt.jsonl +23 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-result.json +34 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/receipt.jsonl +24 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-result.json +47 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/receipt.jsonl +69 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-plan.json +14 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-result.json +44 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/receipt.jsonl +65 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/run-order.sh +18 -0
- package/benchmarks/results/live-host/ledger-pairs-2026-11-28/score.json +1032 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/README.md +50 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/collect-rerun.txt +3 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/export-report.json +22 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/host-version.txt +1 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-1.json +18 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-2.json +18 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/labels-observed-excerpt.jsonl +2 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/observations-index-excerpt.json +26 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/plugin-load-lines.txt +1 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/README.md +46 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/observations-index-excerpt.json +16 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/plugin-load-lines.txt +2 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/run-marks.txt +6 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-probe.js +16 -0
- package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-trace.jsonl +167 -0
- package/ci/archive/325-prep/README.md +9 -2
- package/ci/archive/325-prep/doc-reconciliation-red.js +34 -8
- package/ci/fixtures/553-t2a/body-edit/base/.agents/harness-everything/project-docs.json +11 -0
- package/ci/fixtures/553-t2a/body-edit/base/docs/a.md +6 -0
- package/ci/fixtures/553-t2a/body-edit/base/docs/b.md +1 -0
- package/ci/fixtures/553-t2a/body-edit/candidate/docs/a.md +6 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/adr/EVID-001-verify-all-evidence.md +11 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/governed-index.md +19 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/adr/EVID-001-verify-all-evidence.md +11 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/governed-index.md +19 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/config.json +17 -0
- package/ci/fixtures/doc-obligations/derive/regression-pins.json +153 -0
- package/ci/fixtures/state-persist-post-tool-use/harness.js +206 -0
- package/ci/fixtures/state-persist-post-tool-use/off-handoff-golden.json +16 -0
- package/ci/fixtures/state-persist-post-tool-use/payload-post-tool-use-success.json +13 -0
- package/ci/fixtures/stop/fail-session-writes.js +109 -0
- package/ci/fixtures/workflow-contract/cases.json +3355 -0
- package/ci/fixtures/workflow-contract/wiring-cases.json +560 -0
- package/ci/lib/doc-reconciliation-prep-fixtures.js +4 -9
- package/ci/mechanism-2an-workflow-replay.test.js +324 -0
- package/ci/mechanism-2ax-doc-lifecycle.test.js +132 -0
- package/ci/mechanism-325-3a-doc-evidence.test.js +73 -0
- package/ci/mechanism-325-3a-doc-obligations.test.js +61 -0
- package/ci/mechanism-325-3b-preparation.test.js +208 -49
- package/ci/mechanism-325-3b-s1-review.test.js +20 -828
- package/ci/mechanism-325-3b-s3-providers.test.js +59 -0
- package/ci/mechanism-325-f3-derived-views.test.js +140 -0
- package/ci/mechanism-332-fable-directive.test.js +180 -0
- package/ci/mechanism-341-opencode-lane.test.js +164 -284
- package/ci/mechanism-35-verification-contract.test.js +246 -0
- package/ci/mechanism-365-step-edit-accounting.test.js +5 -6
- package/ci/mechanism-383-doc-glob-line-terminators.test.js +0 -30
- package/ci/mechanism-397-opencode-observations.test.js +151 -18
- package/ci/mechanism-552-ledger-pairs.test.js +159 -0
- package/ci/mechanism-553-e1-unhook-credit.test.js +328 -0
- package/ci/mechanism-553-p2a-claude-hooks.test.js +98 -0
- package/ci/mechanism-553-p3-plan-start.test.js +212 -0
- package/ci/mechanism-553-state-persist-post-tool-use.test.js +307 -0
- package/ci/mechanism-553-stop.test.js +427 -0
- package/ci/mechanism-553-t2a-derive.test.js +110 -0
- package/ci/mechanism-553-t2c-derive.test.js +94 -0
- package/ci/mechanism-e1-derived-regenerate.test.js +45 -206
- package/ci/mechanism-outline-sanitizer.test.js +0 -8
- package/ci/mechanism-pr-a-conflict-check.test.js +38 -305
- package/ci/mechanism-prb-outline-review.test.js +101 -3283
- package/ci/router-workflow-plan.test.js +61 -21
- package/docs/adr/DOCS-006-reconciliation-pilot.md +4 -2
- package/docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md +3 -3
- package/docs/doc-workflow-reconciliation.md +17 -2
- package/docs/document-lifecycle.md +6 -2
- package/docs/platform-capabilities.md +63 -16
- package/docs/platform-compatibility.json +5 -5
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/routing-keywords.json +0 -2
- package/harness-everything/scripts/tier-router.js +105 -11
- package/hooks/hooks.json +0 -46
- package/hooks/scripts/lib/workflow-obligations.js +0 -55
- package/hooks/scripts/state-persist.js +7 -95
- package/hooks/scripts/workflow-disposition.js +0 -2
- package/hooks/scripts/workflow-stop-gate.js +17 -30
- package/opencode-plugin/index.mjs +6 -70
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +0 -55
- package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -95
- package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +0 -2
- package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +17 -30
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/rules/AGENTS.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +0 -2
- package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +105 -11
- package/sbom.cdx.json +7 -7
- package/ci/fixtures/doc-obligations/reconciliation-s1/cases.json +0 -6854
- package/ci/fixtures/doc-obligations/reconciliation-s1/fail-session-writes.js +0 -116
- package/ci/fixtures/doc-obligations/reconciliation-s2a/harness.js +0 -507
- package/ci/fixtures/doc-obligations/reconciliation-s2a/run13-workflow-requirements.json +0 -42
- package/ci/fixtures/doc-obligations/reconciliation-s2a/vectors.json +0 -617
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/harness.js +0 -415
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-post-tool-use-success-minimal.json +0 -9
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-start.json +0 -7
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-freetext-reject.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-reject.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-task-result.json +0 -19
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-capture-only.json +0 -99
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-legacy.json +0 -67
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-concurrent-writers.json +0 -62
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-lookalikes-runtime-mutations.json +0 -67
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-malformed.json +0 -85
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-normal-session.json +0 -74
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-runtime-drift-later-npm-test.json +0 -58
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-valid-direct-quoted-review.json +0 -85
- package/ci/fixtures/doc-obligations/reconciliation-s2b/f4/cases.json +0 -2267
- package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/cases.json +0 -1110
- package/ci/lib/doc-reconciliation-file-spy.js +0 -23
- package/ci/lib/doc-reconciliation-qualification-preload.js +0 -37
- package/ci/lib/doc-reconciliation-replay.js +0 -104
- package/ci/lib/doc-reconciliation-staged-tree.js +0 -102
- package/ci/mechanism-325-3b-h1-qualification.test.js +0 -206
- package/ci/mechanism-325-3b-s1.test.js +0 -188
- package/ci/mechanism-325-3b-s2a-core.test.js +0 -840
- package/ci/mechanism-325-3b-s2a-producer.test.js +0 -564
- package/ci/mechanism-325-3b-s2b-capture.test.js +0 -566
- package/ci/mechanism-325-3b-s2b-wiring.test.js +0 -679
- package/ci/mechanism-325-f4-invariants.test.js +0 -606
- package/ci/mechanism-325-f4-projections.test.js +0 -392
- package/ci/mechanism-325-f4-qualification.test.js +0 -228
- package/ci/mechanism-325-f4-trust-boundary.test.js +0 -880
- package/ci/mechanism-e1-dependency-artifact-scope.test.js +0 -657
- package/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
- package/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
- package/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
- package/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
- package/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
- package/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
- package/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
- package/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
- package/hooks/scripts/w6-state-operations.js +0 -239
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
- package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +0 -239
- package/scripts/system-one-eval-laya.js +0 -112
- /package/ci/fixtures/{doc-obligations/reconciliation-s2b/capture → state-persist-post-tool-use}/payload-post-tool-use-failure.json +0 -0
- /package/ci/fixtures/{doc-obligations/reconciliation-s2b/wiring → workflow-contract}/legacy-off-golden.json +0 -0
|
@@ -1,3304 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
// S2b Claude origin provider (docs/doc-workflow-reconciliation.md § S2b, "Claude
|
|
4
|
-
// capture and origin-provider contract" and "Retained live-capture gate";
|
|
5
|
-
// owner decision rows 1 and 2 are reproduced verbatim there as the binding
|
|
6
|
-
// trust-contract). Implements the existing S2a resolveContext/resolveEvent seam
|
|
7
|
-
// consumed by doc-reconciliation-producer.js / doc-reconciliation-events.js.
|
|
8
|
-
//
|
|
9
|
-
// Binding properties:
|
|
10
|
-
// - Positive credit is disabled until qualification resolves. The production
|
|
11
|
-
// path validates the qualification export next to this file and the sanitized
|
|
12
|
-
// capture it names (no directory search, no size-based acceptance).
|
|
13
|
-
// A process environment toggle or a self-declared capture flag can never
|
|
14
|
-
// substitute for that evidence. Dependency injection of an explicitly fake
|
|
15
|
-
// qualification object ({ source: 'fake-test-fixture', faked: true }) is a
|
|
16
|
-
// test-only construct for mechanism tests; production passes no
|
|
17
|
-
// qualification and stays gated.
|
|
18
|
-
// - The Claude provider accepts only Claude. OpenCode has a separate
|
|
19
|
-
// fail-closed mapping and never borrows Claude's exit or reviewer rules.
|
|
20
|
-
// - Exit mapping (owner decision row 1): for a given `tool_use_id`, a captured
|
|
21
|
-
// `PostToolUse` with `interrupted === false` and no `PostToolUseFailure`
|
|
22
|
-
// arrival maps to exit 0. This is a named mapping of the host's own
|
|
23
|
-
// success/failure classification, not a null→0 conversion. A
|
|
24
|
-
// `PostToolUseFailure` is never credited; failure for the same invocation
|
|
25
|
-
// voids the success mapping; interrupted or ambiguous outcomes are not
|
|
26
|
-
// credited; missing `tool_use_id` is not credited.
|
|
27
|
-
// - Reviewer principal (owner decision row 2): the reviewer is the host-issued
|
|
28
|
-
// `agent_id`, must differ from the author session and every executor
|
|
29
|
-
// principal, must be correlated consistently with the Agent/Task result
|
|
30
|
-
// surface, and a copied/replayed record cannot become a new accepted event
|
|
31
|
-
// by changing its reference. Local journal forgery is not defended against;
|
|
32
|
-
// host payload fields are re-validated at assessment time.
|
|
33
|
-
|
|
34
|
-
const crypto = require('crypto');
|
|
35
|
-
const fs = require('fs');
|
|
36
|
-
const path = require('path');
|
|
37
|
-
const { execFileSync } = require('child_process');
|
|
38
|
-
const { canonical, key, classifyShell } = require('./workflow-isolation');
|
|
39
|
-
|
|
40
|
-
const HOST_ID = 'claude-code';
|
|
41
|
-
const CAPTURE_RECORD_VERSION = 'claude-capture-record/1';
|
|
42
|
-
const OPENCODE_HOST_ID = 'opencode';
|
|
43
|
-
const OPENCODE_CAPTURE_RECORD_VERSION = 'opencode-capture-record/1';
|
|
44
|
-
const OPENCODE_CAPTURE_FILE = 'opencode-captures.jsonl';
|
|
45
|
-
const OPENCODE_CAPTURE_LIMIT_BYTES = 4 * 1024 * 1024;
|
|
46
|
-
const QUALIFICATION_EXPORT_SCHEMA = 'harness.doc-reconciliation.qualification.v1';
|
|
47
|
-
const HEX64 = /^[0-9a-f]{64}$/;
|
|
48
|
-
const PRE_CAPTURE_TOOLS = ['Bash', 'PowerShell', 'Task', 'Agent', 'Write', 'Edit', 'apply_patch'];
|
|
49
|
-
const STDOUT_CAP_BYTES = 1024 * 1024;
|
|
50
|
-
const DOC_CHECK_FLAGS = new Set(['--workspace', '--config', '--changed-path', '--base', '--derived-view']);
|
|
51
|
-
const DOC_CHECK_BOOLEAN_FLAGS = new Set(['--conflict-assessment']);
|
|
52
|
-
const DOC_CHECK_SCHEMA = 'harness.doc-check.check.v1';
|
|
53
|
-
const DOC_CHECK_CONFLICT_SCHEMA = 'harness.doc-check.conflict-assessment.v1';
|
|
54
|
-
const OUTLINE_DISPATCH_SCHEMA = 'harness.outline-dispatch.v1';
|
|
55
|
-
const OUTLINE_CAPTURE_MAPPING = Object.freeze({
|
|
56
|
-
version: 'claude-outline-dispatch-mapping/2',
|
|
57
|
-
promptField: 'tool_input.prompt',
|
|
58
|
-
dispatchKey: 'session_id+tool_use_id',
|
|
59
|
-
runInBackgroundField: 'tool_input.run_in_background',
|
|
60
|
-
isolationPresenceField: 'tool_input.isolation',
|
|
61
|
-
resultAgentIdField: 'tool_response.agentId',
|
|
62
|
-
resultStatusField: 'tool_response.status',
|
|
63
|
-
workerStartEvent: 'SubagentStart',
|
|
64
|
-
workerStopEvent: 'SubagentStop',
|
|
65
|
-
workerIdentity: 'session_id+agent_id',
|
|
66
|
-
workerRootField: 'cwd',
|
|
67
|
-
});
|
|
68
|
-
const OUTLINE_SEAM_SCHEMA = 'harness.outline-dispatch-seam.v1';
|
|
69
|
-
const OUTLINE_HANDOFF_SCHEMA = 'harness.outline-handoff.v1';
|
|
70
|
-
const OUTLINE_LEASE_SCHEMA = 'harness.outline-writer-lease.v1';
|
|
71
|
-
const W6_STATE_OPERATION_SCHEMA = 'harness.w6-state-operation.v1';
|
|
72
|
-
const OUTLINE_WRITE_TOOLS = ['Write', 'Edit', 'apply_patch'];
|
|
73
|
-
const OUTLINE_INVENTORY_SOURCE = '/Users/daniel.chang/Desktop/Skills/Harness-everything/.worktrees/packets/adr-e1-2026-10-27/report-inv.md';
|
|
74
|
-
const OUTLINE_INVENTORY_SHA256 = '2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6';
|
|
75
|
-
const OUTLINE_INVENTORY_PIN = Object.freeze({
|
|
76
|
-
source: OUTLINE_INVENTORY_SOURCE,
|
|
77
|
-
sha256: OUTLINE_INVENTORY_SHA256,
|
|
78
|
-
runId: 'e1-inv-1',
|
|
79
|
-
inputSha: '0ef0541c6cae550e8269ba712e03797e0e987dfb',
|
|
80
|
-
approvalRef: { issue: 325, commentId: '6436207729', decision: 1 },
|
|
81
|
-
rowDomainMappings: Object.freeze([Object.freeze({ rowIds: Object.freeze(['15', '16', '17', '18']),
|
|
82
|
-
sourceDomain: 'VERI', domain: 'EVID', approvalRef: 'https://github.com/dyphn1/Harness-everything/issues/325#issuecomment-6706805112' })]),
|
|
83
|
-
retainedArtifactPath: `inventory/${OUTLINE_INVENTORY_SHA256}.md`,
|
|
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
|
-
]);
|
|
93
|
-
const OUTLINE_MARKER = 'HARNESS_OUTLINE_DISPATCH_V1';
|
|
94
|
-
const OUTLINE_TASK_ID = /^task-[A-Za-z0-9][A-Za-z0-9+._-]{0,127}$/;
|
|
95
|
-
const OUTLINE_ATTEMPT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
96
|
-
const DOC_CHECK_SHELLS = new Set(['sh', 'bash', 'dash', 'zsh', 'ksh', 'fish']);
|
|
97
|
-
const DOC_CHECK_LAUNCHERS = new Set(['node', 'nodejs', 'bun', 'deno', 'tsx', 'ts-node']);
|
|
98
|
-
const DOC_CHECK_LAUNCHER_VALUE_FLAGS = new Set(['-r', '--require', '--import', '--loader', '--experimental-loader', '--inspect-port', '--input-type', '--conditions', '--env-file']);
|
|
99
|
-
const DOC_CHECK_WRAPPERS = new Set(['env', 'npx']);
|
|
100
|
-
const DOC_CHECK_ENV_VALUE_FLAGS = new Set(['-u', '--unset', '-C', '--chdir']);
|
|
101
|
-
const DOC_CHECK_NPX_VALUE_FLAGS = new Set(['-p', '--package', '--prefix', '--cache', '--userconfig', '--registry', '--workspace', '-w']);
|
|
102
|
-
// Backslashes are shell escapes except when a rooted Windows path token makes them separators.
|
|
103
|
-
function isWindowsPathToken(token) {
|
|
104
|
-
return token.startsWith('\\\\') || /^[A-Za-z]:$/.test(token) || /^[A-Za-z]:\\/.test(token)
|
|
105
|
-
|| (process.platform === 'win32' && !token.includes('/'));
|
|
106
|
-
}
|
|
107
|
-
function isDoubleQuotedEscapeTarget(value) {
|
|
108
|
-
return value === '"' || value === '\\' || value === '$' || value === '\x60';
|
|
109
|
-
}
|
|
110
|
-
function isUncPathPrefix(token, command, index) {
|
|
111
|
-
return token === '' && command[index] === '\\' && command[index + 1] === '\\';
|
|
112
|
-
}
|
|
113
|
-
// Canonical SHA-256 of harness-everything/scripts/doc-check.js (CRLF normalised to LF). Re-pin deliberately when that script changes.
|
|
114
|
-
const SHIPPED_DOC_CHECK_DIGEST = '0e93f252b2350b145c34dcb5354aa3b4246f3c59e948a62c3a912305b355a475';
|
|
115
|
-
// This install's own doc-check runtime, relative to hooks/scripts/lib: the source checkout or the packaged plugin.
|
|
116
|
-
const DOC_CHECK_INSTALL_LAYOUTS = [
|
|
117
|
-
['..', '..', '..', 'harness-everything', 'scripts', 'doc-check.js'],
|
|
118
|
-
['..', '..', '..', 'skills', 'harness-everything', 'scripts', 'doc-check.js'],
|
|
119
|
-
];
|
|
120
|
-
|
|
121
|
-
// The resolved path of this install's own doc-check.js, or null when neither layout exists.
|
|
122
|
-
function canonicalPath(value) { return fs.realpathSync.native(path.resolve(value)); }
|
|
123
|
-
function installedDocCheck() {
|
|
124
|
-
for (const layout of DOC_CHECK_INSTALL_LAYOUTS) {
|
|
125
|
-
try { return canonicalPath(path.resolve(__dirname, ...layout)); } catch { /* try the next layout */ }
|
|
126
|
-
}
|
|
127
|
-
return null;
|
|
128
|
-
}
|
|
129
|
-
// Canonical doc-check digest (UTF-8, CRLF normalised to LF): capture and assessment compare the same value.
|
|
130
|
-
function fileDigest(file) { return crypto.createHash('sha256').update(fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n')).digest('hex'); }
|
|
131
|
-
|
|
132
|
-
// Tokenize only the shell-word subset needed for a direct node invocation. Expansion and shell control syntax are refused.
|
|
133
|
-
function safeTokenize(command) {
|
|
134
|
-
if (typeof command !== 'string') return { ok: false, reason: 'invalid-command' };
|
|
135
|
-
const tokens = [];
|
|
136
|
-
let token = '';
|
|
137
|
-
let active = false;
|
|
138
|
-
let quote = null;
|
|
139
|
-
const push = () => {
|
|
140
|
-
if (active) tokens.push(token);
|
|
141
|
-
token = '';
|
|
142
|
-
active = false;
|
|
143
|
-
};
|
|
144
|
-
|
|
145
|
-
for (let index = 0; index < command.length; index += 1) {
|
|
146
|
-
const ch = command[index];
|
|
147
|
-
if (ch === '%' && /^%[^%\s]+%/.test(command.slice(index))) return { ok: false, reason: 'shell-expansion' };
|
|
148
|
-
if (ch === '\\' && isUncPathPrefix(token, command, index)) {
|
|
149
|
-
token += '\\\\';
|
|
150
|
-
index += 1;
|
|
151
|
-
active = true;
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
if (quote === "'") {
|
|
155
|
-
if (ch === "'") quote = null;
|
|
156
|
-
else token += ch;
|
|
157
|
-
continue;
|
|
158
|
-
}
|
|
159
|
-
if (quote === '"') {
|
|
160
|
-
if (ch === '"') { quote = null; continue; }
|
|
161
|
-
if (ch === '\\') {
|
|
162
|
-
const next = command[index + 1];
|
|
163
|
-
if (next === undefined || next === '\n' || next === '\r') return { ok: false, reason: 'shell-continuation' };
|
|
164
|
-
if ([ '"', '\\', '$', '`' ].includes(next)) token += next;
|
|
165
|
-
else token += `\\${next}`;
|
|
166
|
-
index += 1;
|
|
167
|
-
active = true;
|
|
168
|
-
continue;
|
|
169
|
-
}
|
|
170
|
-
if (ch === '$' || ch === '`') return { ok: false, reason: 'shell-expansion' };
|
|
171
|
-
token += ch;
|
|
172
|
-
active = true;
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
if (ch === '\n' || ch === '\r') return { ok: false, reason: 'shell-operator' };
|
|
177
|
-
if (/\s/.test(ch)) { push(); continue; }
|
|
178
|
-
if (ch === "'" || ch === '"') { quote = ch; active = true; continue; }
|
|
179
|
-
if (ch === '\\') {
|
|
180
|
-
const next = command[index + 1];
|
|
181
|
-
if (next === undefined || next === '\n' || next === '\r') return { ok: false, reason: 'shell-continuation' };
|
|
182
|
-
if (isWindowsPathToken(token)) token += '\\';
|
|
183
|
-
else {
|
|
184
|
-
token += next;
|
|
185
|
-
index += 1;
|
|
186
|
-
}
|
|
187
|
-
active = true;
|
|
188
|
-
continue;
|
|
189
|
-
}
|
|
190
|
-
if (';&|<>()'.includes(ch)) return { ok: false, reason: 'shell-operator' };
|
|
191
|
-
if ('*?[]{}'.includes(ch) || (ch === '~' && !active) || ch === '$' || ch === '`') return { ok: false, reason: 'shell-expansion' };
|
|
192
|
-
if (ch === '#' && !active) return { ok: false, reason: 'shell-comment' };
|
|
193
|
-
token += ch;
|
|
194
|
-
active = true;
|
|
195
|
-
}
|
|
196
|
-
if (quote) return { ok: false, reason: 'unclosed-quote' };
|
|
197
|
-
push();
|
|
198
|
-
return { ok: true, tokens };
|
|
199
|
-
}
|
|
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
|
-
|
|
364
|
-
function skipHereDocBodies(command, newlineIndex, hereDocs) {
|
|
365
|
-
const afterLineBreak = index => command[index] === '\r' && command[index + 1] === '\n' ? index + 2 : index + 1;
|
|
366
|
-
let index = afterLineBreak(newlineIndex);
|
|
367
|
-
for (const { delimiter, stripTabs } of hereDocs) {
|
|
368
|
-
let found = false;
|
|
369
|
-
while (index <= command.length) {
|
|
370
|
-
let end = index;
|
|
371
|
-
while (end < command.length && command[end] !== '\n' && command[end] !== '\r') end += 1;
|
|
372
|
-
let line = command.slice(index, end);
|
|
373
|
-
if (stripTabs) line = line.replace(/^\t+/, '');
|
|
374
|
-
if (line === delimiter) {
|
|
375
|
-
index = end < command.length ? afterLineBreak(end) : end;
|
|
376
|
-
found = true;
|
|
377
|
-
break;
|
|
378
|
-
}
|
|
379
|
-
if (end === command.length) return end;
|
|
380
|
-
index = afterLineBreak(end);
|
|
381
|
-
}
|
|
382
|
-
if (!found) return command.length;
|
|
383
|
-
}
|
|
384
|
-
return index;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
function commandSegments(command) {
|
|
388
|
-
const segments = [];
|
|
389
|
-
let words = [];
|
|
390
|
-
let token = '';
|
|
391
|
-
let active = false;
|
|
392
|
-
let quote = null;
|
|
393
|
-
let awaitingHereDocDelimiter = null;
|
|
394
|
-
const hereDocs = [];
|
|
395
|
-
const pushWord = () => {
|
|
396
|
-
if (active) {
|
|
397
|
-
if (awaitingHereDocDelimiter) {
|
|
398
|
-
hereDocs.push({ delimiter: token, stripTabs: awaitingHereDocDelimiter.stripTabs });
|
|
399
|
-
awaitingHereDocDelimiter = null;
|
|
400
|
-
} else words.push(token);
|
|
401
|
-
}
|
|
402
|
-
token = '';
|
|
403
|
-
active = false;
|
|
404
|
-
};
|
|
405
|
-
const pushSegment = () => {
|
|
406
|
-
pushWord();
|
|
407
|
-
if (words.length) segments.push(words);
|
|
408
|
-
words = [];
|
|
409
|
-
};
|
|
410
|
-
|
|
411
|
-
for (let index = 0; index < command.length; index += 1) {
|
|
412
|
-
const ch = command[index];
|
|
413
|
-
if (ch === '\\' && isUncPathPrefix(token, command, index)) {
|
|
414
|
-
token += '\\\\';
|
|
415
|
-
index += 1;
|
|
416
|
-
active = true;
|
|
417
|
-
continue;
|
|
418
|
-
}
|
|
419
|
-
if (quote === "'") {
|
|
420
|
-
if (ch === "'") quote = null;
|
|
421
|
-
else token += ch;
|
|
422
|
-
continue;
|
|
423
|
-
}
|
|
424
|
-
if (quote === '"') {
|
|
425
|
-
if (ch === '"') { quote = null; continue; }
|
|
426
|
-
if (ch === '\\' && command[index + 1] !== undefined) {
|
|
427
|
-
const next = command[index + 1];
|
|
428
|
-
if (isDoubleQuotedEscapeTarget(next)) token += command[++index];
|
|
429
|
-
else token += '\\';
|
|
430
|
-
active = true;
|
|
431
|
-
continue;
|
|
432
|
-
}
|
|
433
|
-
token += ch;
|
|
434
|
-
active = true;
|
|
435
|
-
continue;
|
|
436
|
-
}
|
|
437
|
-
if (ch === "'" || ch === '"') { quote = ch; active = true; continue; }
|
|
438
|
-
if (ch === '\\' && command[index + 1] !== undefined) {
|
|
439
|
-
const next = command[index + 1];
|
|
440
|
-
if (next === '\r' && command[index + 2] === '\n') index += 2;
|
|
441
|
-
else if (next === '\n') index += 1;
|
|
442
|
-
else if (isWindowsPathToken(token)) token += '\\';
|
|
443
|
-
else {
|
|
444
|
-
token += next;
|
|
445
|
-
index += 1;
|
|
446
|
-
}
|
|
447
|
-
active = true;
|
|
448
|
-
continue;
|
|
449
|
-
}
|
|
450
|
-
// shortcut: comments are word-initial unquoted # only, no heredoc or $(...) awareness, upgrade with a real shell parser
|
|
451
|
-
if (ch === '#' && !active) {
|
|
452
|
-
while (index + 1 < command.length && command[index + 1] !== '\n' && command[index + 1] !== '\r') index += 1;
|
|
453
|
-
continue;
|
|
454
|
-
}
|
|
455
|
-
if (ch === '<' && command[index + 1] === '<' && command[index + 2] !== '<') {
|
|
456
|
-
pushWord();
|
|
457
|
-
awaitingHereDocDelimiter = { stripTabs: command[index + 2] === '-' };
|
|
458
|
-
index += awaitingHereDocDelimiter.stripTabs ? 2 : 1;
|
|
459
|
-
continue;
|
|
460
|
-
}
|
|
461
|
-
if (ch === '\n' || ch === '\r') {
|
|
462
|
-
pushWord();
|
|
463
|
-
awaitingHereDocDelimiter = null;
|
|
464
|
-
pushSegment();
|
|
465
|
-
if (hereDocs.length) {
|
|
466
|
-
index = skipHereDocBodies(command, index, hereDocs) - 1;
|
|
467
|
-
hereDocs.length = 0;
|
|
468
|
-
} else if (ch === '\r' && command[index + 1] === '\n') index += 1;
|
|
469
|
-
continue;
|
|
470
|
-
}
|
|
471
|
-
if (/\s/.test(ch)) { pushWord(); continue; }
|
|
472
|
-
if (';&|<>()'.includes(ch)) {
|
|
473
|
-
pushWord();
|
|
474
|
-
awaitingHereDocDelimiter = null;
|
|
475
|
-
pushSegment();
|
|
476
|
-
continue;
|
|
477
|
-
}
|
|
478
|
-
token += ch;
|
|
479
|
-
active = true;
|
|
480
|
-
}
|
|
481
|
-
pushSegment();
|
|
482
|
-
return segments;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
function isDocCheckTarget(token) {
|
|
486
|
-
const basename = String(token || '').split(/[\\/]/).pop().toLowerCase();
|
|
487
|
-
return basename === 'doc-check' || basename === 'doc-check.js';
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
function commandAfterWrapper(words, wrapper, depth) {
|
|
491
|
-
for (let index = 1; index < words.length; index += 1) {
|
|
492
|
-
const word = words[index];
|
|
493
|
-
if (word === '--') return { words: words.slice(index + 1) };
|
|
494
|
-
if (wrapper === 'env') {
|
|
495
|
-
if (DOC_CHECK_ENV_VALUE_FLAGS.has(word)) { index += 1; continue; }
|
|
496
|
-
if (/^--(?:unset|chdir)=/.test(word) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
|
|
497
|
-
if (word.startsWith('-')) continue;
|
|
498
|
-
return { words: words.slice(index) };
|
|
499
|
-
}
|
|
500
|
-
if (DOC_CHECK_NPX_VALUE_FLAGS.has(word)) { index += 1; continue; }
|
|
501
|
-
if (word === '-c' || word === '--call') return { command: words[index + 1], depth: depth + 1 };
|
|
502
|
-
if (/^--(?:package|prefix|cache|userconfig|registry|workspace)=/.test(word)) continue;
|
|
503
|
-
if (word.startsWith('-')) continue;
|
|
504
|
-
return { words: words.slice(index) };
|
|
505
|
-
}
|
|
506
|
-
return null;
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// Classify explicit command/script targets; argument data that merely mentions the checker is not a candidate.
|
|
510
|
-
function hasDocCheckCommandTarget(command, depth = 0) {
|
|
511
|
-
if (typeof command !== 'string' || depth > 4) return false;
|
|
512
|
-
function wordsTarget(words, level) {
|
|
513
|
-
if (level > 4) return false;
|
|
514
|
-
const executable = String(words[0] || '').split(/[\\/]/).pop().toLowerCase();
|
|
515
|
-
if (isDocCheckTarget(words[0])) return true;
|
|
516
|
-
if (DOC_CHECK_SHELLS.has(executable)) {
|
|
517
|
-
if (isDocCheckTarget(words[1])) return true;
|
|
518
|
-
const commandFlag = words.findIndex((word, index) => index > 0 && /^-[a-z]*c[a-z]*$/i.test(word));
|
|
519
|
-
return commandFlag >= 0 && words[commandFlag + 1] !== undefined
|
|
520
|
-
&& hasDocCheckCommandTarget(words[commandFlag + 1], level + 1);
|
|
521
|
-
}
|
|
522
|
-
if (DOC_CHECK_WRAPPERS.has(executable)) {
|
|
523
|
-
const nested = commandAfterWrapper(words, executable, level);
|
|
524
|
-
if (!nested) return false;
|
|
525
|
-
return nested.command !== undefined
|
|
526
|
-
? hasDocCheckCommandTarget(nested.command, nested.depth)
|
|
527
|
-
: wordsTarget(nested.words, level + 1);
|
|
528
|
-
}
|
|
529
|
-
if (!DOC_CHECK_LAUNCHERS.has(executable)) return false;
|
|
530
|
-
for (let index = 1; index < words.length; index += 1) {
|
|
531
|
-
const word = words[index];
|
|
532
|
-
if (word === '--') return isDocCheckTarget(words[index + 1]);
|
|
533
|
-
if (DOC_CHECK_LAUNCHER_VALUE_FLAGS.has(word)) { index += 1; continue; }
|
|
534
|
-
if (word.startsWith('-')) continue;
|
|
535
|
-
return isDocCheckTarget(word);
|
|
536
|
-
}
|
|
537
|
-
return false;
|
|
538
|
-
}
|
|
539
|
-
return commandSegments(command).some(words => wordsTarget(words, depth));
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
// Internal realpath check; the public decision and reason tuple come only from resolveDocCheckInvocation.
|
|
543
|
-
function matchInstalledRuntime(tokens, cwd, installed) {
|
|
544
|
-
let argv;
|
|
545
|
-
try { argv = canonicalPath(path.resolve(textOf(cwd) ? cwd : process.cwd(), tokens[1])); } catch { return null; }
|
|
546
|
-
return argv === installed ? { tokens, installed } : null;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
function resolveDocCheckInvocation(command, cwd) {
|
|
550
|
-
let installed = null;
|
|
551
|
-
let digest = null;
|
|
552
|
-
let argv = null;
|
|
553
|
-
function rejected(reason) { return { kind: 'rejected', reason, installed, digest, argv }; }
|
|
554
|
-
|
|
555
|
-
if (!hasDocCheckCommandTarget(command)) {
|
|
556
|
-
return { kind: 'not-candidate', reason: 'not-doc-check', installed: null, digest: null, argv: null };
|
|
557
|
-
}
|
|
558
|
-
const parsed = safeTokenize(command);
|
|
559
|
-
if (!parsed.ok) return rejected(parsed.reason);
|
|
560
|
-
const tokens = parsed.tokens;
|
|
561
|
-
argv = tokens.slice(1);
|
|
562
|
-
if (tokens[0] !== 'node') return rejected('direct-launcher-required');
|
|
563
|
-
if (tokens.length < 4 || path.basename(tokens[1]).toLowerCase() !== 'doc-check.js' || tokens[2] !== 'check') {
|
|
564
|
-
return rejected('invocation-grammar');
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
const values = new Map();
|
|
568
|
-
const changedPaths = [];
|
|
569
|
-
let conflictAssessment = false;
|
|
570
|
-
for (let index = 3; index < tokens.length;) {
|
|
571
|
-
const flag = tokens[index++];
|
|
572
|
-
if (DOC_CHECK_BOOLEAN_FLAGS.has(flag)) {
|
|
573
|
-
if (conflictAssessment) return rejected('duplicate-flag');
|
|
574
|
-
conflictAssessment = true;
|
|
575
|
-
continue;
|
|
576
|
-
}
|
|
577
|
-
if (!DOC_CHECK_FLAGS.has(flag)) return rejected('unknown-flag');
|
|
578
|
-
const value = tokens[index++];
|
|
579
|
-
if (value === undefined || !value || value.startsWith('--')) return rejected('flag-value-missing');
|
|
580
|
-
if (flag === '--changed-path') changedPaths.push(value);
|
|
581
|
-
else {
|
|
582
|
-
if (values.has(flag)) return rejected('duplicate-flag');
|
|
583
|
-
if (flag === '--derived-view' && (path.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value)
|
|
584
|
-
|| value.split(/[\\/]/).includes('..') || /[*?\[\]{}]/.test(value))) return rejected('derived-view-invalid');
|
|
585
|
-
values.set(flag, value);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
if (!values.has('--workspace') || !values.has('--config') || !changedPaths.length) {
|
|
589
|
-
return rejected('required-flag-missing');
|
|
590
|
-
}
|
|
591
|
-
if (conflictAssessment && !values.has('--base')) return rejected('conflict-assessment-base-required');
|
|
592
|
-
if (conflictAssessment && !/^[0-9a-f]{40,64}$/.test(values.get('--base'))) return rejected('conflict-assessment-base-unpinned');
|
|
593
|
-
|
|
594
|
-
installed = installedDocCheck();
|
|
595
|
-
if (!installed) return rejected('implementation-not-installed');
|
|
596
|
-
const registered = matchInstalledRuntime(tokens, cwd, installed);
|
|
597
|
-
if (!registered) return rejected('implementation-not-installed');
|
|
598
|
-
digest = fileDigest(registered.installed);
|
|
599
|
-
if (registered) {
|
|
600
|
-
if (registered.installed) {
|
|
601
|
-
if (fileDigest(registered.installed) !== SHIPPED_DOC_CHECK_DIGEST) return rejected('implementation-pin-mismatch', 'the installed doc-check is not the shipped script (canonical digest differs from SHIPPED_DOC_CHECK_DIGEST); no credit');
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
return { kind: 'accepted', reason: null, installed: registered.installed, digest, argv,
|
|
605
|
-
conflictAssessment, base: values.get('--base') || null, config: values.get('--config'),
|
|
606
|
-
derivedView: values.get('--derived-view') || null, changedPaths };
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
// Observation-time digests of the checked paths, read from the workspace when the check ran. Absent paths are omitted.
|
|
610
|
-
function observedDigestsFor(root, paths) {
|
|
611
|
-
const digests = {};
|
|
612
|
-
for (const relative of paths) {
|
|
613
|
-
if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.split(/[\\/]/).includes('..')) continue;
|
|
614
|
-
try { digests[relative] = crypto.createHash('sha256').update(fs.readFileSync(path.join(root, relative))).digest('hex'); }
|
|
615
|
-
catch { /* absent: the event will lack this digest and be rejected by the checker */ }
|
|
616
|
-
}
|
|
617
|
-
return digests;
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
function observedConfigSourcesFor(root, sources) {
|
|
621
|
-
if (!Array.isArray(sources)) return [];
|
|
622
|
-
return sources.map(source => {
|
|
623
|
-
const relative = source && source.path;
|
|
624
|
-
if (typeof relative !== 'string' || !relative || path.isAbsolute(relative) || relative.split(/[\\/]/).includes('..')) {
|
|
625
|
-
return { path: String(relative || ''), presence: 'unsupported' };
|
|
626
|
-
}
|
|
627
|
-
const file = path.resolve(root, relative);
|
|
628
|
-
const within = path.relative(path.resolve(root), file);
|
|
629
|
-
if (!within || within === '..' || within.startsWith(`..${path.sep}`) || path.isAbsolute(within)) {
|
|
630
|
-
return { path: relative, presence: 'unsupported' };
|
|
631
|
-
}
|
|
632
|
-
try {
|
|
633
|
-
if (!fs.lstatSync(file).isFile()) return { path: relative, presence: 'unsupported' };
|
|
634
|
-
return { path: relative, presence: 'present', digest: crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') };
|
|
635
|
-
} catch (error) {
|
|
636
|
-
return error.code === 'ENOENT' || error.code === 'ENOTDIR'
|
|
637
|
-
? { path: relative, presence: 'missing' }
|
|
638
|
-
: { path: relative, presence: 'unreadable' };
|
|
639
|
-
}
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
function textOf(value) { return typeof value === 'string' && value.trim().length > 0; }
|
|
644
|
-
function recordOf(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
|
|
645
|
-
function compareKeys(a, b) { return a < b ? -1 : a > b ? 1 : 0; }
|
|
646
|
-
// Canonical capture serialization (sorted keys recursively, array order kept,
|
|
647
|
-
// missing/undefined values serialized as the literal `undefined` token). The
|
|
648
|
-
// capture journal and this provider must agree on this exact form so recorded
|
|
649
|
-
// digests bind the same bytes on both sides.
|
|
650
|
-
function canonicalCapture(value) {
|
|
651
|
-
if (Array.isArray(value)) return value.map(canonicalCapture);
|
|
652
|
-
if (value && typeof value === 'object') {
|
|
653
|
-
return Object.fromEntries(Object.keys(value).sort(compareKeys).map(key => [key, canonicalCapture(value[key])]));
|
|
654
|
-
}
|
|
655
|
-
return value;
|
|
656
|
-
}
|
|
657
|
-
function captureJson(value) {
|
|
658
|
-
const serialized = JSON.stringify(canonicalCapture(value));
|
|
659
|
-
return serialized === undefined ? 'undefined' : serialized;
|
|
660
|
-
}
|
|
661
|
-
function captureDigest(value) {
|
|
662
|
-
return crypto.createHash('sha256').update(captureJson(value)).digest('hex');
|
|
663
|
-
}
|
|
664
|
-
function digestText(value) { return crypto.createHash('sha256').update(String(value)).digest('hex'); }
|
|
665
|
-
function diagnostic(code, detail) {
|
|
666
|
-
return { code, message: code.replace(/-/g, ' '), ...(recordOf(detail) ? detail : {}) };
|
|
667
|
-
}
|
|
668
|
-
function failDiagnostics(prefix, reason) {
|
|
669
|
-
return [diagnostic(prefix, { reason: `${prefix}: ${reason}` })];
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
// ---- Retained live-capture gate -------------------------------------------------
|
|
673
|
-
|
|
674
|
-
// Canonical qualification export (A3 section 4): written by the live-capture packet, copied by plugin sync.
|
|
675
|
-
const EXPORT_FILE = 'doc-reconciliation-qualification.json';
|
|
676
|
-
|
|
677
|
-
// Structured verdict: a labelled line `Review verdict: approve|reject`, with the summary on that line or after it.
|
|
678
|
-
// Free text such as `REJECT: ...` carries no verdict, so it can never approve. The reviewed artifacts are named by
|
|
679
|
-
// `Reviewed artifact: <relative path> sha256:<64 hex>` lines; they bind the review to exact path digests (F6).
|
|
680
|
-
const REVIEWED_ARTIFACT_LINE = /^\s*-?\s*Reviewed artifact:\s*(\S+)\s+sha256:([0-9a-f]{64})\s*$/i;
|
|
681
|
-
function parseReviewVerdict(message) {
|
|
682
|
-
if (typeof message !== 'string') return null;
|
|
683
|
-
const match = /^\s*Review verdict:\s*(approve|reject)\b[.:]?\s*(.*)$/im.exec(message);
|
|
684
|
-
if (!match) return null;
|
|
685
|
-
const reviewedArtifactDigests = {};
|
|
686
|
-
const summary = [match[2], message.slice(match.index + match[0].length)].join('\n').split(/\r?\n/)
|
|
687
|
-
.filter(line => {
|
|
688
|
-
const reviewed = REVIEWED_ARTIFACT_LINE.exec(line);
|
|
689
|
-
if (reviewed) reviewedArtifactDigests[reviewed[1]] = reviewed[2].toLowerCase();
|
|
690
|
-
return !reviewed;
|
|
691
|
-
}).join('\n').trim();
|
|
692
|
-
return { verdict: match[1].toLowerCase(), summary, reviewedArtifactDigests };
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
// Conservative trust gate (owner decision 3, A10 §1). The narrow candidate scanner only selects doc refs; trust asks more.
|
|
696
|
-
// A command is risky when strict safeTokenize refuses it (newline, heredoc, `$()`, operators, malformed quoting) or when it
|
|
697
|
-
// names the checker, raw or decoded. Risky commands get no generic verification and no reviewer independence. The check is
|
|
698
|
-
// conservative on purpose: it is not a shell parser, and non-string input is not shell text.
|
|
699
|
-
// shortcut: benign compounds such as `npm test && echo ok` lose generic credit, upgrade with a real shell parser.
|
|
700
|
-
function trustRisk(command) {
|
|
701
|
-
const text = typeof command === 'string' ? command : '';
|
|
702
|
-
if (/doc-check/i.test(text)) return true;
|
|
703
|
-
if (commandSegments(text).some(words => words.some(word => /doc-check/i.test(word)))) return true;
|
|
704
|
-
// A Windows relative path and a POSIX escape can look the same; fail closed on either command spelling.
|
|
705
|
-
const posixDecoded = text.replace(/\\([^\r\n])/g, '$1');
|
|
706
|
-
if (posixDecoded !== text && hasDocCheckCommandTarget(posixDecoded)) return true;
|
|
707
|
-
const parsed = safeTokenize(text);
|
|
708
|
-
return !parsed.ok || parsed.tokens.some(word => /doc-check/i.test(word));
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
// Executor principals of this task (owner #325, 2026-10-21: the reviewer "must differ from the author's `session_id` and
|
|
712
|
-
// from every executor principal"; an executor principal is the principal of execution evidence used in this assessment).
|
|
713
|
-
// The author session is always an executor. Other executors are the principals of a registered doc-check run, the only
|
|
714
|
-
// execution evidence a doc obligation uses, and of any risky shell command (trustRisk), which could have run the checker.
|
|
715
|
-
// Acceptance is not required, so the set over-approximates and fails closed: a reviewer whose registered run was refused
|
|
716
|
-
// still counts as an executor. Plain read-only tool use, such as `git status`, does not make a reviewer an executor.
|
|
717
|
-
// The Agent/Task launch surface is never execution evidence.
|
|
718
|
-
function journalExecutors(captures, author) {
|
|
719
|
-
const executors = new Set(textOf(author) ? [author] : []);
|
|
720
|
-
for (const item of Array.isArray(captures) ? captures : []) {
|
|
721
|
-
if (!recordOf(item) || item.event !== 'PostToolUse') continue;
|
|
722
|
-
if (item.tool_name === 'Agent' || item.tool_name === 'Task') continue;
|
|
723
|
-
if (resolveDocCheckInvocation(item.command, item.cwd).kind === 'not-candidate' && !trustRisk(item.command)) continue;
|
|
724
|
-
if (textOf(item.session_id)) executors.add(item.session_id);
|
|
725
|
-
if (textOf(item.agent_id)) executors.add(item.agent_id);
|
|
726
|
-
}
|
|
727
|
-
return [...executors].sort(compareKeys);
|
|
728
|
-
}
|
|
729
|
-
|
|
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 };
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
// A reviewed path must be a relative governed path; its digest must be a sha256 of the observed bytes.
|
|
745
|
-
function reviewedDigestsValid(digests) {
|
|
746
|
-
return recordOf(digests) && Object.keys(digests).length > 0
|
|
747
|
-
&& Object.entries(digests).every(([relative, digest]) => textOf(relative) && !path.isAbsolute(relative)
|
|
748
|
-
&& !relative.split(/[\\/]/).includes('..') && HEX64.test(String(digest)));
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
// What the sanitized capture proves: the payload kinds with their fields, and the correlation rules it demonstrates.
|
|
752
|
-
// The export must claim exactly these; a claim the capture does not support fails qualification.
|
|
753
|
-
const QUALIFICATION_FIELDS = ['tool_use_id', 'interrupted', 'agent_id', 'agent_type', 'session_id'];
|
|
754
|
-
|
|
755
|
-
function observedPayloadKinds(records) {
|
|
756
|
-
const kinds = {};
|
|
757
|
-
for (const record of records) {
|
|
758
|
-
if (!recordOf(record) || !textOf(record.event)) continue;
|
|
759
|
-
const fields = kinds[record.event] || (kinds[record.event] = new Set());
|
|
760
|
-
for (const field of QUALIFICATION_FIELDS) if (record[field] !== undefined) fields.add(field);
|
|
761
|
-
}
|
|
762
|
-
return Object.fromEntries(Object.keys(kinds).sort(compareKeys).map(kind => [kind, [...kinds[kind]].sort(compareKeys)]));
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
function observedCorrelation(records) {
|
|
766
|
-
const pre = new Set(records.filter(item => recordOf(item) && item.event === 'PreToolUse' && textOf(item.tool_use_id)).map(item => item.tool_use_id));
|
|
767
|
-
const post = records.filter(item => recordOf(item) && item.event === 'PostToolUse' && textOf(item.tool_use_id));
|
|
768
|
-
const starts = records.filter(item => recordOf(item) && item.event === 'SubagentStart');
|
|
769
|
-
const stops = records.filter(item => recordOf(item) && item.event === 'SubagentStop');
|
|
770
|
-
return {
|
|
771
|
-
preToPostByToolUseId: post.some(item => pre.has(item.tool_use_id)),
|
|
772
|
-
interruptedExplicit: post.some(item => typeof item.interrupted === 'boolean'),
|
|
773
|
-
subagentStartStopSameAgent: stops.some(stop => starts.some(start => textOf(stop.agent_id) && start.agent_id === stop.agent_id)),
|
|
774
|
-
agentResultAliasCorrelated: records.some(item => recordOf(item) && item.event === 'PostToolUse' && textOf(item.agent_id)
|
|
775
|
-
&& stops.some(stop => stop.agent_id === item.agent_id)),
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
// Validates the qualification export against the sanitized capture it names: schema, host, capture-record version, the
|
|
780
|
-
// capture's digest, and every claimed kind, field and correlation. Returns null when valid, else the reason.
|
|
781
|
-
function validateQualificationExport(expectedHost = HOST_ID) {
|
|
782
|
-
const exported = JSON.parse(fs.readFileSync(path.join(__dirname, EXPORT_FILE), 'utf8'));
|
|
783
|
-
if (!recordOf(exported) || exported.schema !== QUALIFICATION_EXPORT_SCHEMA) return 'qualification export schema is not recognized';
|
|
784
|
-
if (!textOf(exported.hostVersion)) return 'qualification export host or host version is missing';
|
|
785
|
-
if (exported.host !== expectedHost) {
|
|
786
|
-
if (expectedHost === HOST_ID) return 'qualification export host or host version is missing';
|
|
787
|
-
return 'qualification export host does not match the selected provider';
|
|
788
|
-
}
|
|
789
|
-
if (exported.captureRecordVersion !== CAPTURE_RECORD_VERSION) return 'qualification export capture record version is not supported';
|
|
790
|
-
const source = recordOf(exported.sanitizedCapture) ? exported.sanitizedCapture : {};
|
|
791
|
-
// The sanitized capture is a sibling of the export, so source and packaged copies resolve it the same way.
|
|
792
|
-
if (!textOf(source.file) || /[\\/]/.test(source.file) || source.file.includes('..')) {
|
|
793
|
-
return 'qualification export names no valid capture file';
|
|
794
|
-
}
|
|
795
|
-
const bytes = fs.readFileSync(path.join(__dirname, source.file));
|
|
796
|
-
if (crypto.createHash('sha256').update(bytes).digest('hex') !== source.sha256) {
|
|
797
|
-
return 'sanitized capture digest does not match the qualification export';
|
|
798
|
-
}
|
|
799
|
-
const records = bytes.toString('utf8').split(/\r?\n/).filter(line => line.trim()).map(line => JSON.parse(line));
|
|
800
|
-
if (!records.every(recordOf)) return 'sanitized capture contains a record that is not an object';
|
|
801
|
-
if (captureJson(exported.payloadKinds) !== captureJson(observedPayloadKinds(records))) {
|
|
802
|
-
return 'qualification export payload kinds do not match the sanitized capture';
|
|
803
|
-
}
|
|
804
|
-
const correlation = observedCorrelation(records);
|
|
805
|
-
if (captureJson(exported.correlation) !== captureJson(correlation)) return 'qualification export correlation does not match the sanitized capture';
|
|
806
|
-
if (!Object.values(correlation).every(Boolean)) return 'required correlation rules are not observed in the sanitized capture';
|
|
807
|
-
return null;
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
function evaluateQualification(input, expectedHost = HOST_ID) {
|
|
811
|
-
if (recordOf(input) && input.qualification !== undefined && input.qualification !== null) {
|
|
812
|
-
const supplied = input.qualification;
|
|
813
|
-
// Test-only DI path: an explicitly fake qualification object. Anything else
|
|
814
|
-
// supplied is unrecognized qualification evidence and cannot open the gate.
|
|
815
|
-
if (recordOf(supplied) && supplied.faked === true && supplied.source === 'fake-test-fixture'
|
|
816
|
-
&& supplied.toolUseIdPopulated === true && supplied.agentIdPopulated === true) {
|
|
817
|
-
return { open: true, source: 'dependency-injection' };
|
|
818
|
-
}
|
|
819
|
-
return {
|
|
820
|
-
open: false,
|
|
821
|
-
fail: diagnostic('live-gate-unmet', {
|
|
822
|
-
reason: 'live gate unmet: supplied qualification evidence is malformed or unrecognized; positive credit requires verified retained evidence or an explicitly fake test DI object',
|
|
823
|
-
}),
|
|
824
|
-
};
|
|
825
|
-
}
|
|
826
|
-
// Production path: no qualification is supplied, so the validated qualification export is the only source. It is checked
|
|
827
|
-
// against the sanitized capture it names. Nothing is read from the environment, capture flags or ancestor directories.
|
|
828
|
-
let reason = null;
|
|
829
|
-
try {
|
|
830
|
-
reason = validateQualificationExport(expectedHost);
|
|
831
|
-
} catch (error) {
|
|
832
|
-
reason = `qualification evidence could not be read (${error.code || 'error'})`;
|
|
833
|
-
}
|
|
834
|
-
if (reason) {
|
|
835
|
-
return {
|
|
836
|
-
open: false,
|
|
837
|
-
fail: diagnostic('live-gate-unmet', { reason: `live gate unmet: ${reason}` }),
|
|
838
|
-
};
|
|
839
|
-
}
|
|
840
|
-
return { open: true, source: 'validated-export' };
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
function outlineSha(value) { return crypto.createHash('sha256').update(value).digest('hex'); }
|
|
844
|
-
|
|
845
|
-
function parseOutlineDispatchPrompt(prompt) {
|
|
846
|
-
if (typeof prompt !== 'string') return null;
|
|
847
|
-
const occurrences = prompt.match(new RegExp(OUTLINE_MARKER, 'g')) || [];
|
|
848
|
-
if (occurrences.length !== 1) return null;
|
|
849
|
-
const line = prompt.split(/\r?\n/).find(item => item.includes(OUTLINE_MARKER));
|
|
850
|
-
const match = /^(HARNESS_OUTLINE_DISPATCH_V1) taskId=([^\s]+) attemptId=([^\s]+) token=([^\s]+) workerRoot=(.+)$/.exec(line || '');
|
|
851
|
-
if (!match || !OUTLINE_TASK_ID.test(match[2]) || !OUTLINE_ATTEMPT_ID.test(match[3])
|
|
852
|
-
|| !textOf(match[4]) || !path.isAbsolute(match[5]) || match[5].trim() !== match[5]) return null;
|
|
853
|
-
const block = match[0];
|
|
854
|
-
const tokenDigest = outlineSha(match[4]);
|
|
855
|
-
const promptDigest = outlineSha(Buffer.from(prompt, 'utf8'));
|
|
856
|
-
return {
|
|
857
|
-
taskId: match[2], attemptId: match[3], token: match[4], tokenDigest,
|
|
858
|
-
workerRoot: match[5], blockDigest: outlineSha(Buffer.from(block, 'utf8')),
|
|
859
|
-
promptDigest,
|
|
860
|
-
dispatchInputDigest: outlineSha(captureJson({ taskId: match[2], attemptId: match[3], tokenDigest,
|
|
861
|
-
workerRoot: match[5], promptDigest })),
|
|
862
|
-
};
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
function parseInventoryPinRows(bytes) {
|
|
866
|
-
const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes || '');
|
|
867
|
-
const identity = /run id `([^`]+)`[^\n]*input SHA `([a-f0-9]+)`/i.exec(text);
|
|
868
|
-
if (!identity) return { state: 'unresolved', reason: 'inventory-identity-missing' };
|
|
869
|
-
const lines = text.split(/\r?\n/);
|
|
870
|
-
const mechanismIndex = lines.findIndex(line => /Mechanism inventory/i.test(line));
|
|
871
|
-
const areaIndex = lines.findIndex(line => /Area grouping \+ candidate domain prefixes/i.test(line));
|
|
872
|
-
if (mechanismIndex < 0 || areaIndex < 0 || areaIndex <= mechanismIndex) return { state: 'unresolved', reason: 'inventory-tables-missing' };
|
|
873
|
-
const rows = new Map();
|
|
874
|
-
for (const line of lines.slice(mechanismIndex, areaIndex)) {
|
|
875
|
-
const match = /^\|\s*(\d{1,2})\s*\|/.exec(line);
|
|
876
|
-
if (!match) continue;
|
|
877
|
-
rows.set(match[1], (rows.get(match[1]) || 0) + 1);
|
|
878
|
-
}
|
|
879
|
-
const domains = new Map();
|
|
880
|
-
for (const line of lines.slice(areaIndex)) {
|
|
881
|
-
const cells = line.split('|').map(cell => cell.trim());
|
|
882
|
-
if (cells.length < 5 || !cells[1] || !cells[2] || !cells[3]) continue;
|
|
883
|
-
const prefix = /^`([A-Z][A-Z0-9]{1,9})`$/.exec(cells[3]);
|
|
884
|
-
if (!prefix) continue;
|
|
885
|
-
for (const item of cells[2].split(',')) {
|
|
886
|
-
const range = /^(\d{1,2})\s*[–-]\s*(\d{1,2})$/.exec(item.trim());
|
|
887
|
-
if (range) {
|
|
888
|
-
for (let id = Number(range[1]); id <= Number(range[2]); id += 1) {
|
|
889
|
-
const key = String(id).padStart(2, '0');
|
|
890
|
-
const entries = domains.get(key) || [];
|
|
891
|
-
entries.push(prefix[1]);
|
|
892
|
-
domains.set(key, entries);
|
|
893
|
-
}
|
|
894
|
-
} else if (/^\d{1,2}$/.test(item.trim())) {
|
|
895
|
-
const key = item.trim().padStart(2, '0');
|
|
896
|
-
const entries = domains.get(key) || [];
|
|
897
|
-
entries.push(prefix[1]);
|
|
898
|
-
domains.set(key, entries);
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
return { state: 'parsed', runId: identity[1], inputSha: identity[2], rows, domains };
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
function validateOutlineInventoryPin({ bytes, pin, expectedPin = OUTLINE_INVENTORY_PIN } = {}) {
|
|
906
|
-
if (!Buffer.isBuffer(bytes) || !recordOf(pin) || !recordOf(expectedPin)) return { state: 'unresolved', reason: 'inventory-unavailable' };
|
|
907
|
-
const fields = ['source', 'sha256', 'runId', 'inputSha', 'approvalRef', 'rowDomainMappings', 'retainedArtifactPath'];
|
|
908
|
-
const actualPin = Object.fromEntries(fields.map(field => [field, pin[field]]));
|
|
909
|
-
const trustedPin = Object.fromEntries(fields.map(field => [field, expectedPin[field]]));
|
|
910
|
-
if (captureJson(actualPin) !== captureJson(trustedPin)) return { state: 'unresolved', reason: 'inventory-pin-mismatch' };
|
|
911
|
-
const digest = outlineSha(bytes);
|
|
912
|
-
if (digest !== expectedPin.sha256 || expectedPin.retainedArtifactPath !== `inventory/${expectedPin.sha256}.md`) {
|
|
913
|
-
return { state: 'unresolved', reason: 'inventory-digest-mismatch' };
|
|
914
|
-
}
|
|
915
|
-
const parsed = parseInventoryPinRows(bytes);
|
|
916
|
-
if (parsed.state !== 'parsed' || parsed.runId !== expectedPin.runId || parsed.inputSha !== expectedPin.inputSha) {
|
|
917
|
-
return { state: 'unresolved', reason: parsed.reason || 'inventory-revision-mismatch' };
|
|
918
|
-
}
|
|
919
|
-
return { state: 'accepted', pin: trustedPin, pinDigest: outlineSha(Buffer.from(captureJson(trustedPin))),
|
|
920
|
-
artifactDigest: digest, parsed };
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
function resolveInventoryRow(inventory, rowId) {
|
|
924
|
-
const parsed = inventory && inventory.parsed;
|
|
925
|
-
if (!parsed || parsed.state !== 'parsed' || !textOf(rowId)) return { state: 'unresolved', reason: 'inventory-row-missing' };
|
|
926
|
-
const matches = [...parsed.rows.entries()].filter(([id]) => id === rowId);
|
|
927
|
-
const domains = parsed.domains.get(rowId) || [];
|
|
928
|
-
if (matches.length !== 1 || matches[0][1] !== 1) {
|
|
929
|
-
return { state: 'unresolved', reason: 'inventory-row-ambiguous' };
|
|
930
|
-
}
|
|
931
|
-
const mappings = (Array.isArray(inventory.pin?.rowDomainMappings) ? inventory.pin.rowDomainMappings : [])
|
|
932
|
-
.filter(item => recordOf(item) && Array.isArray(item.rowIds) && item.rowIds.includes(rowId));
|
|
933
|
-
if (mappings.length > 1) return { state: 'unresolved', reason: 'inventory-row-ambiguous' };
|
|
934
|
-
const mapping = mappings[0];
|
|
935
|
-
if (mapping && (!domains.includes(mapping.sourceDomain) || !textOf(mapping.domain) || !textOf(mapping.approvalRef))) {
|
|
936
|
-
return { state: 'unresolved', reason: 'inventory-row-mapping-invalid' };
|
|
937
|
-
}
|
|
938
|
-
if (!mapping && domains.length !== 1) return { state: 'unresolved', reason: 'inventory-row-ambiguous' };
|
|
939
|
-
return { state: 'accepted', row: { rowId, domain: mapping ? mapping.domain : domains[0] } };
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
function hasSubstantiveDecision(text) {
|
|
943
|
-
const lines = String(text || '').split(/\r?\n/);
|
|
944
|
-
let decisionLines = null;
|
|
945
|
-
const substantive = linesToCheck => linesToCheck.some(line => {
|
|
946
|
-
const value = line.trim().replace(/^[-*]\s*/, '');
|
|
947
|
-
return value && !/^<!--|^-->$|^\[[^\]]*\]$|^<[^>]+>$|^TBD$|^TODO$/i.test(value);
|
|
948
|
-
});
|
|
949
|
-
for (const line of lines) {
|
|
950
|
-
const heading = /^ {0,3}##\s+(.+?)\s*#*\s*$/.exec(line);
|
|
951
|
-
const headingText = heading?.[1]?.trim() || '';
|
|
952
|
-
if (/^Decision\b/i.test(headingText)) {
|
|
953
|
-
if (decisionLines && substantive(decisionLines)) return true;
|
|
954
|
-
decisionLines = [];
|
|
955
|
-
continue;
|
|
956
|
-
}
|
|
957
|
-
if (decisionLines && heading) {
|
|
958
|
-
if (substantive(decisionLines)) return true;
|
|
959
|
-
decisionLines = null;
|
|
960
|
-
continue;
|
|
961
|
-
}
|
|
962
|
-
if (decisionLines) decisionLines.push(line);
|
|
963
|
-
}
|
|
964
|
-
return Boolean(decisionLines && substantive(decisionLines));
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
function parseOutlineCitation(bytes, targetPath) {
|
|
968
|
-
const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes || '');
|
|
969
|
-
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
970
|
-
if (!frontmatter) return { state: 'unresolved', reason: 'outline-frontmatter-missing' };
|
|
971
|
-
const field = name => new RegExp(`^${name}:\\s*([^\\r\\n]+)\\s*$`, 'm').exec(frontmatter[1])?.[1]?.trim() || '';
|
|
972
|
-
const id = field('id');
|
|
973
|
-
const status = field('status');
|
|
974
|
-
const rowMatches = [...text.matchAll(/^Inventory row:\s*([0-9]{1,2})\s*$/gmi)];
|
|
975
|
-
const targetMatches = [...text.matchAll(/^Target:\s*(\S+)\s*$/gmi)];
|
|
976
|
-
const domainMatches = [...text.matchAll(/^Domain:\s*([A-Z][A-Z0-9]{1,9})\s*$/gmi)];
|
|
977
|
-
if (!/^([A-Z][A-Z0-9]{1,9})-\d{3,}$/.test(id) || status !== 'proposed'
|
|
978
|
-
|| rowMatches.length !== 1 || targetMatches.length !== 1 || domainMatches.length !== 1
|
|
979
|
-
|| targetMatches[0][1] !== targetPath) return { state: 'unresolved', reason: 'outline-citation-invalid' };
|
|
980
|
-
if (hasSubstantiveDecision(text)) return { state: 'unresolved', reason: 'outline-already-draft' };
|
|
981
|
-
return { state: 'accepted', id, status, rowId: rowMatches[0][1], targetPath,
|
|
982
|
-
domain: domainMatches[0][1], bytesDigest: outlineSha(Buffer.from(text, 'utf8')) };
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
function outlineGit(root, args, binary = false) {
|
|
986
|
-
try {
|
|
987
|
-
const env = { ...process.env };
|
|
988
|
-
for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];
|
|
989
|
-
return execFileSync('git', ['-C', root, ...args], { env, encoding: binary ? null : 'utf8',
|
|
990
|
-
timeout: 10000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
991
|
-
} catch (error) {
|
|
992
|
-
throw new Error('outline-git-unavailable', { cause: error });
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
function canonicalOutlineRoot(value) {
|
|
997
|
-
if (typeof value !== 'string' || !path.isAbsolute(value)) throw new Error('outline-root-invalid');
|
|
998
|
-
try { fs.statSync(value); } catch { throw new Error('outline-root-not-canonical'); }
|
|
999
|
-
return canonical(value);
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
function outlineWorkspaceId(root) { return 'ws-' + digestText(captureJson({ workspaceRoot: canonical(root) })); }
|
|
1003
|
-
|
|
1004
|
-
function readOutlineJson(file) {
|
|
1005
|
-
try {
|
|
1006
|
-
const bytes = fs.readFileSync(file);
|
|
1007
|
-
const value = JSON.parse(bytes.toString('utf8'));
|
|
1008
|
-
if (!recordOf(value)) return { state: 'unresolved', reason: 'outline-record-invalid' };
|
|
1009
|
-
return { state: 'accepted', value, bytes, digest: outlineSha(bytes) };
|
|
1010
|
-
} catch {
|
|
1011
|
-
return { state: 'unresolved', reason: 'outline-record-unavailable' };
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
function outlineTaskState(sessionDir) {
|
|
1016
|
-
const workflowFile = path.join(sessionDir, 'workflow-run.json');
|
|
1017
|
-
const loaded = readOutlineJson(workflowFile);
|
|
1018
|
-
if (loaded.state !== 'accepted') return { state: 'unresolved', reason: 'workflow-pin-unavailable' };
|
|
1019
|
-
const workflow = loaded.value;
|
|
1020
|
-
const taskBinding = workflow.docReconciliationTask;
|
|
1021
|
-
const baseline = workflow.docReconciliationBaseline;
|
|
1022
|
-
if (!recordOf(taskBinding) || !OUTLINE_TASK_ID.test(String(taskBinding.taskId || ''))
|
|
1023
|
-
|| !Array.isArray(taskBinding.requirementIds) || !taskBinding.requirementIds.length
|
|
1024
|
-
|| !HEX64.test(String(taskBinding.requirementDigest || ''))
|
|
1025
|
-
|| !recordOf(baseline) || !textOf(baseline.root) || !/^[0-9a-f]{40,64}$/.test(String(baseline.commit || ''))
|
|
1026
|
-
|| outlineSha(Buffer.from(captureJson(taskBinding.requirementIds))) !== taskBinding.requirementDigest
|
|
1027
|
-
|| taskBinding.taskId !== `task-${taskBinding.requirementIds.join('+')}`
|
|
1028
|
-
|| taskBinding.baselineCommit !== baseline.commit || !sameCanonicalPath(taskBinding.baselineRoot, baseline.root)
|
|
1029
|
-
|| taskBinding.workflowId !== workflow.workflowId || taskBinding.workspaceId !== outlineWorkspaceId(baseline.root)) {
|
|
1030
|
-
return { state: 'unresolved', reason: 'workflow-task-binding-invalid' };
|
|
1031
|
-
}
|
|
1032
|
-
return { state: 'accepted', workflow, taskBinding, baseline };
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
function resolveOutlineAttempt({ sessionDir, taskId, attemptId } = {}) {
|
|
1036
|
-
if (!textOf(sessionDir) || !OUTLINE_TASK_ID.test(String(taskId || '')) || !OUTLINE_ATTEMPT_ID.test(String(attemptId || ''))) {
|
|
1037
|
-
return { state: 'unresolved', reason: 'attempt-identity-invalid' };
|
|
1038
|
-
}
|
|
1039
|
-
const taskState = outlineTaskState(sessionDir);
|
|
1040
|
-
if (taskState.state !== 'accepted' || taskState.taskBinding.taskId !== taskId) {
|
|
1041
|
-
return { state: 'unresolved', reason: taskState.reason || 'task-binding-mismatch' };
|
|
1042
|
-
}
|
|
1043
|
-
const attemptsRoot = path.join(sessionDir, 'doc-reconciliation', 'outline-confirmation', taskId, 'attempts');
|
|
1044
|
-
let names;
|
|
1045
|
-
try { names = fs.readdirSync(attemptsRoot, { withFileTypes: true }).filter(item => item.isDirectory()).map(item => item.name).sort(compareKeys); }
|
|
1046
|
-
catch { return { state: 'unresolved', reason: 'attempt-chain-unavailable' }; }
|
|
1047
|
-
if (!names.length) return { state: 'unresolved', reason: 'attempt-chain-empty' };
|
|
1048
|
-
const attempts = new Map();
|
|
1049
|
-
for (const name of names) {
|
|
1050
|
-
if (!OUTLINE_ATTEMPT_ID.test(name)) return { state: 'unresolved', reason: 'attempt-id-invalid' };
|
|
1051
|
-
const loaded = readOutlineJson(path.join(attemptsRoot, name, 'handoff.json'));
|
|
1052
|
-
if (loaded.state !== 'accepted') return { state: 'unresolved', reason: 'handoff-unavailable' };
|
|
1053
|
-
const handoff = loaded.value;
|
|
1054
|
-
if (handoff.schema !== OUTLINE_HANDOFF_SCHEMA || handoff.taskId !== taskId || handoff.attemptId !== name
|
|
1055
|
-
|| !textOf(handoff.handoffId) || !textOf(handoff.draftDispatchToken)
|
|
1056
|
-
|| !recordOf(handoff.baseline) || handoff.baseline.commit !== taskState.baseline.commit
|
|
1057
|
-
|| !sameCanonicalPath(handoff.baseline.root, taskState.baseline.root)
|
|
1058
|
-
|| handoff.configDigest !== taskState.taskBinding.configDigest) {
|
|
1059
|
-
return { state: 'unresolved', reason: 'handoff-identity-or-baseline-mismatch' };
|
|
1060
|
-
}
|
|
1061
|
-
const attemptDir = path.join(attemptsRoot, name);
|
|
1062
|
-
const seamDir = path.join(attemptDir, 'seams');
|
|
1063
|
-
const tokenDir = path.join(attemptDir, 'tokens');
|
|
1064
|
-
const filesIn = dir => {
|
|
1065
|
-
try { return fs.readdirSync(dir, { withFileTypes: true })
|
|
1066
|
-
.filter(entry => entry.isFile() && entry.name.endsWith('.json')).map(entry => path.join(dir, entry.name)); }
|
|
1067
|
-
catch { return []; }
|
|
1068
|
-
};
|
|
1069
|
-
const seamFiles = filesIn(seamDir);
|
|
1070
|
-
const tokenFiles = filesIn(tokenDir);
|
|
1071
|
-
const evidenceFiles = [...seamFiles, ...tokenFiles];
|
|
1072
|
-
const sealLoaded = readOutlineJson(path.join(attemptDir, 'handoff-seal.json'));
|
|
1073
|
-
const sealExists = fs.existsSync(path.join(attemptDir, 'handoff-seal.json'));
|
|
1074
|
-
if (sealExists && (sealLoaded.state !== 'accepted' || sealLoaded.value.schema !== 'harness.outline-handoff-seal.v1'
|
|
1075
|
-
|| sealLoaded.value.taskId !== taskId || sealLoaded.value.attemptId !== name
|
|
1076
|
-
|| sealLoaded.value.handoffDigest !== loaded.digest)) {
|
|
1077
|
-
return { state: 'unresolved', reason: 'handoff-overwritten-after-dispatch' };
|
|
1078
|
-
}
|
|
1079
|
-
if (evidenceFiles.length && !sealExists) {
|
|
1080
|
-
return { state: 'unresolved', reason: 'handoff-overwritten-after-dispatch' };
|
|
1081
|
-
}
|
|
1082
|
-
for (const evidenceFile of evidenceFiles) {
|
|
1083
|
-
const evidenceLoaded = readOutlineJson(evidenceFile);
|
|
1084
|
-
if (evidenceLoaded.state !== 'accepted' || evidenceLoaded.value.taskId !== taskId
|
|
1085
|
-
|| evidenceLoaded.value.attemptId !== name || evidenceLoaded.value.handoffDigest !== loaded.digest) {
|
|
1086
|
-
return { state: 'unresolved', reason: 'handoff-overwritten-after-dispatch' };
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
let interrupted = false;
|
|
1090
|
-
if (sealExists && (tokenFiles.length !== 1 || seamFiles.length !== 1)) interrupted = true;
|
|
1091
|
-
if (sealExists && tokenFiles.length === 1 && seamFiles.length === 1) {
|
|
1092
|
-
const token = readOutlineJson(tokenFiles[0]).value;
|
|
1093
|
-
const seam = readOutlineJson(seamFiles[0]).value;
|
|
1094
|
-
if (token.schema !== 'harness.outline-token.v1' || seam.schema !== OUTLINE_SEAM_SCHEMA
|
|
1095
|
-
|| token.tokenDigest !== seam.tokenDigest || token.toolUseId !== seam.toolUseId
|
|
1096
|
-
|| token.dispatchInputDigest !== seam.dispatchInputDigest) {
|
|
1097
|
-
return { state: 'unresolved', reason: 'handoff-dispatch-evidence-mismatch' };
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
attempts.set(name, { handoff, handoffDigest: loaded.digest, attemptDir, interrupted });
|
|
1101
|
-
}
|
|
1102
|
-
const parents = new Map();
|
|
1103
|
-
const children = new Map(names.map(name => [name, 0]));
|
|
1104
|
-
const tokens = new Set();
|
|
1105
|
-
for (const [name, item] of attempts) {
|
|
1106
|
-
const { handoff } = item;
|
|
1107
|
-
if (tokens.has(handoff.draftDispatchToken)) return { state: 'unresolved', reason: 'attempt-token-reused' };
|
|
1108
|
-
tokens.add(handoff.draftDispatchToken);
|
|
1109
|
-
const parent = handoff.supersedesAttemptId;
|
|
1110
|
-
if (parent === null || parent === undefined) { parents.set(name, null); continue; }
|
|
1111
|
-
if (!attempts.has(parent) || parent === name || children.get(parent) === undefined) {
|
|
1112
|
-
return { state: 'unresolved', reason: 'attempt-predecessor-missing' };
|
|
1113
|
-
}
|
|
1114
|
-
children.set(parent, children.get(parent) + 1);
|
|
1115
|
-
if (children.get(parent) > 1) return { state: 'unresolved', reason: 'attempt-chain-ambiguous' };
|
|
1116
|
-
parents.set(name, parent);
|
|
1117
|
-
}
|
|
1118
|
-
const roots = [...parents.values()].filter(parent => parent === null).length;
|
|
1119
|
-
if (roots !== 1) return { state: 'unresolved', reason: 'attempt-chain-ambiguous' };
|
|
1120
|
-
for (const name of names) {
|
|
1121
|
-
const seen = new Set();
|
|
1122
|
-
let current = name;
|
|
1123
|
-
while (current !== null) {
|
|
1124
|
-
if (seen.has(current)) return { state: 'unresolved', reason: 'attempt-chain-cyclic' };
|
|
1125
|
-
seen.add(current);
|
|
1126
|
-
current = parents.get(current);
|
|
1127
|
-
if (current === undefined) return { state: 'unresolved', reason: 'attempt-predecessor-missing' };
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
const leaves = names.filter(name => children.get(name) === 0);
|
|
1131
|
-
if (leaves.length !== 1) return { state: 'unresolved', reason: 'attempt-chain-ambiguous' };
|
|
1132
|
-
if (leaves[0] !== attemptId) return { state: 'unresolved', reason: 'attempt-superseded' };
|
|
1133
|
-
const currentAttempt = attempts.get(attemptId);
|
|
1134
|
-
if (currentAttempt.interrupted) return { state: 'unresolved', reason: 'attempt-interrupted' };
|
|
1135
|
-
return { state: 'accepted', taskBinding: taskState.taskBinding, baseline: taskState.baseline,
|
|
1136
|
-
handoff: currentAttempt.handoff, handoffDigest: currentAttempt.handoffDigest,
|
|
1137
|
-
attemptDir: currentAttempt.attemptDir, predecessors: [...parents.keys()].filter(id => id !== attemptId) };
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
function outlineHandoffDirectory(sessionDir, taskId) {
|
|
1141
|
-
return path.join(sessionDir, 'doc-reconciliation', 'outline-confirmation', taskId);
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// #341 step 1: Harness records O's identity at each SubagentStart inside an outline task. A reviewer's launch record predates
|
|
1145
|
-
// its review, so the identity it carries is the O the reviewer evaluated; the record is not taken from the reviewer's prose.
|
|
1146
|
-
function captureOutlineStartIdentity({ sessionDir } = {}) {
|
|
1147
|
-
const taskState = outlineTaskState(sessionDir);
|
|
1148
|
-
if (taskState.state !== 'accepted') return null;
|
|
1149
|
-
const root = taskState.baseline.root;
|
|
1150
|
-
try {
|
|
1151
|
-
const commit = outlineGit(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
|
|
1152
|
-
const tree = outlineGit(root, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
|
|
1153
|
-
const targetPaths = outlineGit(root, ['diff', '--name-only', '--no-renames', '-z', taskState.baseline.commit, commit])
|
|
1154
|
-
.split('\0').filter(Boolean).sort(compareKeys);
|
|
1155
|
-
const targetBlobs = {};
|
|
1156
|
-
for (const target of targetPaths) {
|
|
1157
|
-
targetBlobs[target] = { blobOid: outlineGit(root, ['rev-parse', `${commit}:${target}`]).trim(),
|
|
1158
|
-
storedBytesSha256: outlineSha(outlineGit(root, ['show', `${commit}:${target}`], true)) };
|
|
1159
|
-
}
|
|
1160
|
-
return { state: 'accepted', identity: { baselineCommit: taskState.baseline.commit, outlineCommit: commit,
|
|
1161
|
-
outlineTree: tree, targetPaths, targetBlobs } };
|
|
1162
|
-
} catch {
|
|
1163
|
-
return { state: 'unresolved', reason: 'outline-identity-unavailable' };
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
// The reviewer has exactly one launch record, it precedes the review Stop, and its identity equals the handoff's O identity.
|
|
1168
|
-
function validateOutlineIdentity({ handoff, captures } = {}) {
|
|
1169
|
-
const refs = (Array.isArray(captures) ? captures : []).filter(recordOf);
|
|
1170
|
-
const stop = refs.find(item => item.ref === handoff.reviewCaptureRef && item.event === 'SubagentStop');
|
|
1171
|
-
if (!stop || !textOf(stop.agent_id)) return { state: 'unresolved', reason: 'outline-review-capture-missing-or-ambiguous' };
|
|
1172
|
-
const starts = refs.filter(item => item.event === 'SubagentStart' && item.agent_id === stop.agent_id);
|
|
1173
|
-
if (starts.length !== 1) return { state: 'unresolved', reason: 'outline-review-result-missing-or-ambiguous' };
|
|
1174
|
-
if (refs.indexOf(starts[0]) > refs.indexOf(stop)) return { state: 'unresolved', reason: 'outline-identity-mismatch' };
|
|
1175
|
-
const recorded = starts[0].outlineIdentity;
|
|
1176
|
-
if (!recordOf(recorded) || recorded.state !== 'accepted' || !recordOf(recorded.identity)) {
|
|
1177
|
-
return { state: 'unresolved', reason: 'outline-identity-unavailable' };
|
|
1178
|
-
}
|
|
1179
|
-
const current = { baselineCommit: handoff.baseline?.commit, outlineCommit: handoff.outline?.commit,
|
|
1180
|
-
outlineTree: handoff.outline?.tree, targetPaths: handoff.targetPaths, targetBlobs: handoff.outline?.targetBlobs };
|
|
1181
|
-
if (captureJson(recorded.identity) !== captureJson(current)) return { state: 'unresolved', reason: 'outline-identity-mismatch' };
|
|
1182
|
-
return { state: 'accepted', identityDigest: outlineSha(Buffer.from(captureJson(recorded.identity))) };
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
function validateOutlineReview({ handoff, attemptDir, captures, targetPaths, outlineDigests, inventory, sessionId } = {}) {
|
|
1186
|
-
const refs = Array.isArray(captures) ? captures : [];
|
|
1187
|
-
const matches = refs.filter(item => recordOf(item) && item.ref === handoff.reviewCaptureRef && item.event === 'SubagentStop');
|
|
1188
|
-
if (matches.length !== 1) return { state: 'unresolved', reason: 'outline-review-capture-missing-or-ambiguous' };
|
|
1189
|
-
const review = matches[0];
|
|
1190
|
-
const reviewer = review.agent_id;
|
|
1191
|
-
if (!textOf(reviewer) || reviewer === sessionId || review.reviewVerdict !== 'approve'
|
|
1192
|
-
|| !textOf(review.reviewSummary) || !HEX64.test(String(review.reviewDigest || ''))
|
|
1193
|
-
|| review.reviewDigest !== handoff.reviewDigest) return { state: 'unresolved', reason: 'outline-review-invalid' };
|
|
1194
|
-
const capturedDigest = captureDigest(review);
|
|
1195
|
-
if (capturedDigest !== handoff.reviewCaptureDigest) return { state: 'unresolved', reason: 'outline-review-capture-digest-mismatch' };
|
|
1196
|
-
const principals = { author: sessionId, executors: journalExecutors(refs, sessionId) };
|
|
1197
|
-
if (!reviewRecordIndependent(review, refs, principals)) return { state: 'unresolved', reason: 'outline-review-not-independent' };
|
|
1198
|
-
const inventoryPath = path.posix.join('doc-reconciliation/outline-confirmation/inventory', path.posix.basename(inventory.pin.retainedArtifactPath));
|
|
1199
|
-
const expectedReviewed = { ...outlineDigests, [inventoryPath]: inventory.artifactDigest };
|
|
1200
|
-
if (captureJson(review.reviewedArtifactDigests) !== captureJson(expectedReviewed)) {
|
|
1201
|
-
return { state: 'unresolved', reason: 'outline-review-artifact-binding-mismatch' };
|
|
1202
|
-
}
|
|
1203
|
-
const summary = String(review.reviewSummary);
|
|
1204
|
-
if (!summary.includes(`inventory row ${handoff.inventory.rowId}`) || !summary.includes(targetPaths[0])
|
|
1205
|
-
|| !summary.includes(handoff.inventory.domain)) return { state: 'unresolved', reason: 'outline-review-scope-mismatch' };
|
|
1206
|
-
const result = refs.filter(item => recordOf(item) && item.event === 'PostToolUse'
|
|
1207
|
-
&& (item.tool_name === 'Agent' || item.tool_name === 'Task') && item.agent_id === reviewer);
|
|
1208
|
-
if (result.length !== 1) return { state: 'unresolved', reason: 'outline-review-result-missing-or-ambiguous' };
|
|
1209
|
-
return { state: 'accepted', review, reviewerPrincipal: reviewer, captureDigest: capturedDigest,
|
|
1210
|
-
reviewDigest: review.reviewDigest, inventoryPath };
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
function validateOutlineHandoffAtDispatch({ payload, parsed, sessionDir, workspaceRoot, captures, expectedPin } = {}) {
|
|
1214
|
-
const taskState = outlineTaskState(sessionDir);
|
|
1215
|
-
if (taskState.state !== 'accepted' || parsed.taskId !== taskState.taskBinding.taskId) {
|
|
1216
|
-
return { state: 'unresolved', reason: taskState.reason || 'task-binding-mismatch' };
|
|
1217
|
-
}
|
|
1218
|
-
const attempt = resolveOutlineAttempt({ sessionDir, taskId: parsed.taskId, attemptId: parsed.attemptId });
|
|
1219
|
-
if (attempt.state !== 'accepted') return attempt;
|
|
1220
|
-
const { handoff, handoffDigest, attemptDir, baseline, taskBinding } = attempt;
|
|
1221
|
-
const workflow = taskState.workflow;
|
|
1222
|
-
if (handoff.schema !== OUTLINE_HANDOFF_SCHEMA || handoff.workspaceId !== outlineWorkspaceId(baseline.root)
|
|
1223
|
-
|| handoff.workflowId !== workflow.workflowId || handoff.workflowRevision !== workflow.revision
|
|
1224
|
-
|| handoff.sessionId !== payload.session_id || handoff.hostId !== HOST_ID
|
|
1225
|
-
|| handoff.coordinatorPrincipal !== payload.session_id
|
|
1226
|
-
|| handoff.draftDispatchToken !== parsed.token
|
|
1227
|
-
|| !sameCanonicalPath(handoff.baseline.root, baseline.root) || handoff.baseline.commit !== baseline.commit
|
|
1228
|
-
|| handoff.baseline.tree !== baseline.tree || handoff.configDigest !== taskBinding.configDigest) {
|
|
1229
|
-
return { state: 'unresolved', reason: 'handoff-identity-mismatch' };
|
|
1230
|
-
}
|
|
1231
|
-
// O must change exactly the declared targets. Checked before the identity so an extra file reports its scope reason.
|
|
1232
|
-
const changedAtO = outlineGit(baseline.root, ['diff', '--name-only', '--no-renames', '-z', baseline.commit, handoff.outline.commit])
|
|
1233
|
-
.split('\0').filter(Boolean).sort(compareKeys);
|
|
1234
|
-
if (captureJson(changedAtO) !== captureJson(Array.isArray(handoff.targetPaths) ? [...handoff.targetPaths].sort(compareKeys) : null)) {
|
|
1235
|
-
return { state: 'unresolved', reason: 'outline-commit-scope-invalid' };
|
|
1236
|
-
}
|
|
1237
|
-
// Dispatch must still name the O the reviewer recorded: checked before the worktree, lease and review checks.
|
|
1238
|
-
const recordedIdentity = validateOutlineIdentity({ handoff, captures });
|
|
1239
|
-
if (recordedIdentity.state !== 'accepted') return recordedIdentity;
|
|
1240
|
-
const markerRoot = canonicalOutlineRoot(parsed.workerRoot);
|
|
1241
|
-
const declaredRoot = canonicalOutlineRoot(handoff.draftWorktreeRoot);
|
|
1242
|
-
if (!sameCanonicalPath(markerRoot, declaredRoot)) return { state: 'unresolved', reason: 'worker-root-mismatch' };
|
|
1243
|
-
const gitRoot = outlineGit(markerRoot, ['rev-parse', '--show-toplevel']).trim();
|
|
1244
|
-
if (!sameCanonicalPath(canonicalOutlineRoot(gitRoot), markerRoot)) return { state: 'unresolved', reason: 'worker-root-mismatch' };
|
|
1245
|
-
const head = outlineGit(markerRoot, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
|
|
1246
|
-
const tree = outlineGit(markerRoot, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
|
|
1247
|
-
const statusBytes = outlineGit(markerRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], true);
|
|
1248
|
-
const statusDigest = outlineSha(statusBytes);
|
|
1249
|
-
if (head !== handoff.outline.commit || tree !== handoff.outline.tree || statusBytes.length !== 0) {
|
|
1250
|
-
return { state: 'unresolved', reason: statusBytes.length ? 'worker-worktree-not-clean-at-O' : 'worker-worktree-not-at-O' };
|
|
1251
|
-
}
|
|
1252
|
-
if (outlineGit(markerRoot, ['rev-parse', '--verify', `${baseline.commit}^{commit}`]).trim() !== baseline.commit
|
|
1253
|
-
|| outlineGit(markerRoot, ['rev-parse', '--verify', `${handoff.outline.commit}^{tree}`]).trim() !== handoff.outline.tree
|
|
1254
|
-
|| outlineGit(markerRoot, ['merge-base', '--is-ancestor', baseline.commit, handoff.outline.commit]) !== '') {
|
|
1255
|
-
return { state: 'unresolved', reason: 'B-to-O-git-binding-invalid' };
|
|
1256
|
-
}
|
|
1257
|
-
const targetPaths = Array.isArray(handoff.targetPaths) ? [...handoff.targetPaths] : [];
|
|
1258
|
-
if (!targetPaths.length || targetPaths.some(item => typeof item !== 'string' || path.isAbsolute(item)
|
|
1259
|
-
|| item.includes('\\') || item.split('/').some(part => !part || part === '.' || part === '..'))
|
|
1260
|
-
|| captureJson([...new Set(targetPaths)].sort(compareKeys)) !== captureJson(targetPaths)) {
|
|
1261
|
-
return { state: 'unresolved', reason: 'outline-target-scope-invalid' };
|
|
1262
|
-
}
|
|
1263
|
-
const pinDir = path.join(sessionDir, 'doc-reconciliation', 'outline-confirmation', 'inventory');
|
|
1264
|
-
const trustedPin = expectedPin || OUTLINE_INVENTORY_PIN;
|
|
1265
|
-
const pinFile = path.join(pinDir, 'inventory-pin.json');
|
|
1266
|
-
const pinLoaded = readOutlineJson(pinFile);
|
|
1267
|
-
if (pinLoaded.state !== 'accepted') return { state: 'unresolved', reason: 'inventory-pin-unavailable' };
|
|
1268
|
-
const inventoryFile = path.join(pinDir, trustedPin.retainedArtifactPath.split('/').pop());
|
|
1269
|
-
let inventoryBytes;
|
|
1270
|
-
try { inventoryBytes = fs.readFileSync(inventoryFile); }
|
|
1271
|
-
catch { return { state: 'unresolved', reason: 'inventory-artifact-unavailable' }; }
|
|
1272
|
-
const inventory = validateOutlineInventoryPin({ bytes: inventoryBytes, pin: pinLoaded.value, expectedPin: trustedPin });
|
|
1273
|
-
if (inventory.state !== 'accepted') return inventory;
|
|
1274
|
-
if (outlineSha(pinLoaded.bytes) !== handoff.inventoryPinDigest && handoff.inventoryPinDigest !== undefined) {
|
|
1275
|
-
return { state: 'unresolved', reason: 'inventory-pin-digest-mismatch' };
|
|
1276
|
-
}
|
|
1277
|
-
const outlineBlobs = recordOf(handoff.outline?.targetBlobs) ? handoff.outline.targetBlobs : {};
|
|
1278
|
-
const outlineDigests = {};
|
|
1279
|
-
let citedRow = null;
|
|
1280
|
-
for (const target of targetPaths) {
|
|
1281
|
-
const atBaseline = outlineGit(baseline.root, ['ls-tree', '-r', '--name-only', baseline.commit, '--', target]).trim();
|
|
1282
|
-
if (atBaseline.split('\n').filter(Boolean).includes(target)) return { state: 'unresolved', reason: 'outline-target-existed-at-B' };
|
|
1283
|
-
if (!outlineGitTreeHasRegularBlob(markerRoot, handoff.outline.tree, target)) {
|
|
1284
|
-
return { state: 'unresolved', reason: 'outline-target-object-not-regular' };
|
|
1285
|
-
}
|
|
1286
|
-
const bytes = outlineGit(markerRoot, ['show', `${handoff.outline.commit}:${target}`], true);
|
|
1287
|
-
const blobOid = outlineGit(markerRoot, ['rev-parse', `${handoff.outline.commit}:${target}`]).trim();
|
|
1288
|
-
const expected = outlineBlobs[target];
|
|
1289
|
-
if (!recordOf(expected) || expected.blobOid !== blobOid || expected.storedBytesSha256 !== outlineSha(bytes)) {
|
|
1290
|
-
return { state: 'unresolved', reason: 'outline-object-binding-mismatch' };
|
|
1291
|
-
}
|
|
1292
|
-
const citation = parseOutlineCitation(bytes, target);
|
|
1293
|
-
if (citation.state !== 'accepted') return citation;
|
|
1294
|
-
const row = resolveInventoryRow(inventory, citation.rowId);
|
|
1295
|
-
if (row.state !== 'accepted' || citation.domain !== row.row.domain || citation.domain !== handoff.inventory.domain
|
|
1296
|
-
|| handoff.inventory.rowId !== citation.rowId || !Array.isArray(handoff.inventory.targetPaths)
|
|
1297
|
-
|| captureJson(handoff.inventory.targetPaths) !== captureJson(targetPaths)) {
|
|
1298
|
-
return { state: 'unresolved', reason: row.reason || 'outline-inventory-binding-mismatch' };
|
|
1299
|
-
}
|
|
1300
|
-
const expectedId = path.posix.basename(target, path.posix.extname(target));
|
|
1301
|
-
if (citation.id !== expectedId || !citation.id.startsWith(`${row.row.domain}-`)) {
|
|
1302
|
-
return { state: 'unresolved', reason: 'outline-domain-target-mismatch' };
|
|
1303
|
-
}
|
|
1304
|
-
if (citedRow && captureJson(citedRow) !== captureJson(row.row)) return { state: 'unresolved', reason: 'outline-row-ambiguous' };
|
|
1305
|
-
citedRow = row.row;
|
|
1306
|
-
outlineDigests[target] = outlineSha(bytes);
|
|
1307
|
-
}
|
|
1308
|
-
const leaseFile = path.join(attemptDir, 'writer-lease.json');
|
|
1309
|
-
const leaseLoaded = readOutlineJson(leaseFile);
|
|
1310
|
-
if (leaseLoaded.state !== 'accepted') return { state: 'unresolved', reason: 'writer-lease-unavailable' };
|
|
1311
|
-
const lease = leaseLoaded.value;
|
|
1312
|
-
if (lease.schema !== OUTLINE_LEASE_SCHEMA || lease.id !== handoff.writerLeaseId
|
|
1313
|
-
|| lease.principalId !== payload.session_id || !sameCanonicalPath(lease.root, markerRoot) || lease.exclusive !== true
|
|
1314
|
-
|| lease.active !== true || (Array.isArray(lease.competingWriters) && lease.competingWriters.length)
|
|
1315
|
-
|| leaseLoaded.digest !== handoff.writerLeaseDigest) {
|
|
1316
|
-
return { state: 'unresolved', reason: 'writer-lease-invalid' };
|
|
1317
|
-
}
|
|
1318
|
-
const review = validateOutlineReview({ handoff, attemptDir, captures, targetPaths, outlineDigests, inventory,
|
|
1319
|
-
sessionId: payload.session_id });
|
|
1320
|
-
if (review.state !== 'accepted') return review;
|
|
1321
|
-
return { state: 'accepted', taskBinding, baseline, handoff, handoffDigest, attemptDir, markerRoot,
|
|
1322
|
-
worktree: { root: markerRoot, head, tree, statusDigest, clean: true },
|
|
1323
|
-
inventory, inventoryPinDigest: outlineSha(pinLoaded.bytes), row: citedRow, targetPaths, outlineDigests, review,
|
|
1324
|
-
leaseDigest: leaseLoaded.digest, leaseId: lease.id, identityDigest: recordedIdentity.identityDigest };
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
function outlineDispatchUnresolved(parsed, reason) {
|
|
1328
|
-
return { schema: OUTLINE_DISPATCH_SCHEMA, state: 'unresolved', reasons: [reason],
|
|
1329
|
-
...(parsed ? { taskId: parsed.taskId, attemptId: parsed.attemptId, tokenDigest: parsed.tokenDigest,
|
|
1330
|
-
promptDigest: parsed.promptDigest, blockDigest: parsed.blockDigest, dispatchInputDigest: parsed.dispatchInputDigest,
|
|
1331
|
-
workerRoot: parsed.workerRoot } : {}) };
|
|
1332
|
-
}
|
|
1333
|
-
|
|
1334
|
-
function captureOutlineDispatch(input = {}) {
|
|
1335
|
-
let parsed = null;
|
|
1336
|
-
try {
|
|
1337
|
-
const { payload, capture, sessionDir, workspaceRoot, captures = [], fixtureExpectedPin } = input;
|
|
1338
|
-
if (!recordOf(payload) || !recordOf(capture) || payload.hook_event_name !== 'PreToolUse'
|
|
1339
|
-
|| !['Agent', 'Task'].includes(payload.tool_name) || !recordOf(payload.tool_input)) {
|
|
1340
|
-
return outlineDispatchUnresolved(null, 'dispatch-event-invalid');
|
|
1341
|
-
}
|
|
1342
|
-
parsed = parseOutlineDispatchPrompt(payload.tool_input.prompt);
|
|
1343
|
-
if (!parsed) return outlineDispatchUnresolved(null, 'dispatch-marker-invalid');
|
|
1344
|
-
if (capture.tool_use_id !== payload.tool_use_id || !textOf(payload.tool_use_id)
|
|
1345
|
-
|| capture.session_id !== payload.session_id || !textOf(payload.session_id)) {
|
|
1346
|
-
return outlineDispatchUnresolved(parsed, 'dispatch-correlation-missing');
|
|
1347
|
-
}
|
|
1348
|
-
const failedPredecessor = (Array.isArray(captures) ? captures : []).some(item => recordOf(item)
|
|
1349
|
-
&& item.event === 'PreToolUse' && item.session_id === payload.session_id
|
|
1350
|
-
&& item.outlineDispatch?.state === 'unresolved'
|
|
1351
|
-
&& (item.tool_use_id === payload.tool_use_id
|
|
1352
|
-
|| (item.outlineDispatch.taskId === parsed.taskId && item.outlineDispatch.attemptId === parsed.attemptId
|
|
1353
|
-
&& item.outlineDispatch.tokenDigest === parsed.tokenDigest)));
|
|
1354
|
-
if (failedPredecessor) return outlineDispatchUnresolved(parsed, 'attempt-already-unresolved');
|
|
1355
|
-
const validated = validateOutlineHandoffAtDispatch({ payload, parsed, sessionDir, workspaceRoot,
|
|
1356
|
-
captures, expectedPin: fixtureExpectedPin });
|
|
1357
|
-
if (validated.state !== 'accepted') return outlineDispatchUnresolved(parsed, validated.reason || 'dispatch-validation-unresolved');
|
|
1358
|
-
const seamDir = path.join(validated.attemptDir, 'seams');
|
|
1359
|
-
const tokenDir = path.join(validated.attemptDir, 'tokens');
|
|
1360
|
-
const seamName = `${outlineSha(String(payload.tool_use_id))}.json`;
|
|
1361
|
-
const seamFile = path.join(seamDir, seamName);
|
|
1362
|
-
const tokenFile = path.join(tokenDir, `${parsed.tokenDigest}.json`);
|
|
1363
|
-
const priorSeam = readOutlineJson(seamFile);
|
|
1364
|
-
if (priorSeam.state === 'accepted') {
|
|
1365
|
-
const prior = priorSeam.value;
|
|
1366
|
-
if (prior.toolUseId === payload.tool_use_id && prior.dispatchInputDigest === parsed.dispatchInputDigest
|
|
1367
|
-
&& prior.taskId === parsed.taskId && prior.attemptId === parsed.attemptId) {
|
|
1368
|
-
return { ...prior, schema: OUTLINE_DISPATCH_SCHEMA, duplicate: true };
|
|
1369
|
-
}
|
|
1370
|
-
return outlineDispatchUnresolved(parsed, 'dispatch-input-changed');
|
|
1371
|
-
}
|
|
1372
|
-
const priorToken = readOutlineJson(tokenFile);
|
|
1373
|
-
if (priorToken.state === 'accepted') {
|
|
1374
|
-
const token = priorToken.value;
|
|
1375
|
-
if (token.toolUseId !== payload.tool_use_id) return outlineDispatchUnresolved(parsed, 'draft-token-reused');
|
|
1376
|
-
return outlineDispatchUnresolved(parsed, 'seam-missing-after-token-consumption');
|
|
1377
|
-
}
|
|
1378
|
-
const seam = {
|
|
1379
|
-
schema: OUTLINE_SEAM_SCHEMA, state: 'accepted', captureRef: capture.ref, toolUseId: payload.tool_use_id,
|
|
1380
|
-
taskId: parsed.taskId, attemptId: parsed.attemptId, workerRoot: validated.markerRoot,
|
|
1381
|
-
tokenDigest: parsed.tokenDigest, promptDigest: parsed.promptDigest, blockDigest: parsed.blockDigest,
|
|
1382
|
-
dispatchInputDigest: parsed.dispatchInputDigest, handoffDigest: validated.handoffDigest,
|
|
1383
|
-
reviewCaptureRef: validated.review.review.ref, reviewCaptureDigest: validated.review.captureDigest,
|
|
1384
|
-
reviewDigest: validated.review.reviewDigest, outlineIdentityDigest: validated.identityDigest,
|
|
1385
|
-
inventoryPinDigest: validated.inventoryPinDigest,
|
|
1386
|
-
writerLeaseDigest: validated.leaseDigest, writerLeaseId: validated.leaseId,
|
|
1387
|
-
coordinatorPrincipal: payload.session_id, reviewerPrincipal: validated.review.reviewerPrincipal,
|
|
1388
|
-
worktree: validated.worktree, validationReasons: [],
|
|
1389
|
-
};
|
|
1390
|
-
const sealFile = path.join(validated.attemptDir, 'handoff-seal.json');
|
|
1391
|
-
const existingSeal = readOutlineJson(sealFile);
|
|
1392
|
-
if (existingSeal.state === 'accepted') {
|
|
1393
|
-
if (existingSeal.value.taskId !== parsed.taskId || existingSeal.value.attemptId !== parsed.attemptId
|
|
1394
|
-
|| existingSeal.value.handoffDigest !== validated.handoffDigest) {
|
|
1395
|
-
return outlineDispatchUnresolved(parsed, 'handoff-overwritten-after-dispatch');
|
|
1396
|
-
}
|
|
1397
|
-
return outlineDispatchUnresolved(parsed, 'handoff-seal-already-consumed');
|
|
1398
|
-
}
|
|
1399
|
-
const seal = { schema: 'harness.outline-handoff-seal.v1', taskId: parsed.taskId,
|
|
1400
|
-
attemptId: parsed.attemptId, handoffDigest: validated.handoffDigest };
|
|
1401
|
-
try { fs.writeFileSync(sealFile, JSON.stringify(seal, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' }); }
|
|
1402
|
-
catch { return outlineDispatchUnresolved(parsed, 'handoff-seal-persistence-failed'); }
|
|
1403
|
-
fs.mkdirSync(tokenDir, { recursive: true });
|
|
1404
|
-
fs.mkdirSync(seamDir, { recursive: true });
|
|
1405
|
-
const token = { schema: 'harness.outline-token.v1', taskId: parsed.taskId, attemptId: parsed.attemptId,
|
|
1406
|
-
tokenDigest: parsed.tokenDigest, toolUseId: payload.tool_use_id, dispatchInputDigest: parsed.dispatchInputDigest,
|
|
1407
|
-
handoffDigest: validated.handoffDigest };
|
|
1408
|
-
try {
|
|
1409
|
-
fs.writeFileSync(tokenFile, JSON.stringify(token, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
|
|
1410
|
-
} catch (error) {
|
|
1411
|
-
if (error.code === 'EEXIST') return outlineDispatchUnresolved(parsed, 'draft-token-reused');
|
|
1412
|
-
return outlineDispatchUnresolved(parsed, 'token-consumption-failed');
|
|
1413
|
-
}
|
|
1414
|
-
try {
|
|
1415
|
-
fs.writeFileSync(seamFile, JSON.stringify(seam, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
|
|
1416
|
-
} catch {
|
|
1417
|
-
return outlineDispatchUnresolved(parsed, 'seam-persistence-failed');
|
|
1418
|
-
}
|
|
1419
|
-
return { ...seam, schema: OUTLINE_DISPATCH_SCHEMA,
|
|
1420
|
-
seamRef: path.relative(sessionDir, seamFile).split(path.sep).join('/') };
|
|
1421
|
-
} catch (error) {
|
|
1422
|
-
return outlineDispatchUnresolved(parsed, error.message === 'outline-git-unavailable' ? error.message : 'dispatch-validation-failed');
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
function validateOutlineCaptureQualification(input, expectedHost = HOST_ID) {
|
|
1427
|
-
if (!recordOf(input) || input.hostId !== expectedHost || expectedHost !== HOST_ID) return { open: false, reason: 'unsupported-host' };
|
|
1428
|
-
const supplied = input.qualification;
|
|
1429
|
-
if (recordOf(supplied) && supplied.faked === true && supplied.source === 'fake-test-fixture'
|
|
1430
|
-
&& supplied.toolUseIdPopulated === true && supplied.agentIdPopulated === true) {
|
|
1431
|
-
return supplied.outlineDispatchCaptureVerified === true
|
|
1432
|
-
? { open: true, source: 'dependency-injection' }
|
|
1433
|
-
: { open: false, reason: 'outline-live-capture-unqualified' };
|
|
1434
|
-
}
|
|
1435
|
-
try {
|
|
1436
|
-
const qualificationError = validateQualificationExport(expectedHost);
|
|
1437
|
-
if (qualificationError) return { open: false, reason: qualificationError };
|
|
1438
|
-
const exported = JSON.parse(fs.readFileSync(path.join(__dirname, EXPORT_FILE), 'utf8'));
|
|
1439
|
-
const wrapper = exported.outlineDispatchCapture;
|
|
1440
|
-
if (!recordOf(wrapper) || !textOf(wrapper.hostVersion) || !textOf(wrapper.run) || !textOf(wrapper.baseline)
|
|
1441
|
-
|| !textOf(wrapper.file) || /[\\/]/.test(wrapper.file) || wrapper.file.includes('..')) {
|
|
1442
|
-
return { open: false, reason: 'outline-live-capture-unqualified' };
|
|
1443
|
-
}
|
|
1444
|
-
const bytes = fs.readFileSync(path.join(__dirname, wrapper.file));
|
|
1445
|
-
if (crypto.createHash('sha256').update(bytes).digest('hex') !== wrapper.sha256) {
|
|
1446
|
-
return { open: false, reason: 'outline-live-capture-unqualified' };
|
|
1447
|
-
}
|
|
1448
|
-
const records = bytes.toString('utf8').split(/\r?\n/).filter(line => line.trim()).map(line => JSON.parse(line));
|
|
1449
|
-
if (!records.every(recordOf) || !outlineCaptureMappingValid(wrapper.mapping, records)) {
|
|
1450
|
-
return { open: false, reason: 'outline-live-capture-unqualified' };
|
|
1451
|
-
}
|
|
1452
|
-
return { open: true, source: 'validated-export', captureFile: wrapper.file };
|
|
1453
|
-
} catch (error) {
|
|
1454
|
-
return { open: false, reason: `outline-live-capture-unqualified:${error.code || 'invalid'}` };
|
|
1455
|
-
}
|
|
1456
|
-
}
|
|
1457
|
-
|
|
1458
|
-
function outlineCaptureMappingValid(mapping, records) {
|
|
1459
|
-
if (!recordOf(mapping) || captureJson(mapping) !== captureJson(OUTLINE_CAPTURE_MAPPING) || !Array.isArray(records)) return false;
|
|
1460
|
-
const pres = records.filter(item => recordOf(item) && item.event === 'PreToolUse'
|
|
1461
|
-
&& ['Task', 'Agent'].includes(item.tool_name) && recordOf(item.tool_input)
|
|
1462
|
-
&& typeof item.tool_input.prompt === 'string' && textOf(item.session_id) && textOf(item.tool_use_id));
|
|
1463
|
-
return pres.some(pre => correlateOutlineDispatch(records, pre).state === 'accepted');
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
function outlineCorrelationFailure(reason) { return { state: 'unresolved', reason }; }
|
|
1467
|
-
|
|
1468
|
-
function outlineDispatchKeyMatches(item, pre) {
|
|
1469
|
-
return recordOf(item) && item.session_id === pre.session_id && item.tool_use_id === pre.tool_use_id;
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
function outlineResultAgentId(result) {
|
|
1473
|
-
if (recordOf(result.tool_response)) {
|
|
1474
|
-
const observed = result.tool_response.agentId;
|
|
1475
|
-
if (textOf(result.agent_id) && textOf(observed) && result.agent_id !== observed) {
|
|
1476
|
-
return { state: 'unresolved', reason: 'outline-worker-result-agent-id-conflict' };
|
|
1477
|
-
}
|
|
1478
|
-
return { state: textOf(observed) ? 'accepted' : 'unresolved', agentId: observed,
|
|
1479
|
-
...(textOf(observed) ? {} : { reason: 'outline-worker-result-agent-id-missing' }) };
|
|
1480
|
-
}
|
|
1481
|
-
return textOf(result.agent_id)
|
|
1482
|
-
? { state: 'accepted', agentId: result.agent_id }
|
|
1483
|
-
: { state: 'unresolved', reason: 'outline-worker-result-agent-id-missing' };
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
function outlineResultStatus(result) {
|
|
1487
|
-
if (recordOf(result.tool_response)) return Object.prototype.hasOwnProperty.call(result.tool_response, 'status')
|
|
1488
|
-
? { present: true, value: result.tool_response.status } : { present: false };
|
|
1489
|
-
return Object.prototype.hasOwnProperty.call(result, 'tool_response_status')
|
|
1490
|
-
? { present: true, value: result.tool_response_status } : { present: false };
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
function correlateOutlineDispatch(records, anchor, expectedWorkerRoot) {
|
|
1494
|
-
if (!Array.isArray(records)) return outlineCorrelationFailure('outline-capture-records-missing');
|
|
1495
|
-
if (!recordOf(anchor) || anchor.event !== 'PreToolUse' || !['Task', 'Agent'].includes(anchor.tool_name)) {
|
|
1496
|
-
return outlineCorrelationFailure('outline-dispatch-anchor-invalid');
|
|
1497
|
-
}
|
|
1498
|
-
if (!textOf(anchor.session_id) || !textOf(anchor.tool_use_id)) return outlineCorrelationFailure('outline-dispatch-key-missing');
|
|
1499
|
-
const pres = records.filter(item => recordOf(item) && item.event === 'PreToolUse'
|
|
1500
|
-
&& ['Task', 'Agent'].includes(item.tool_name) && outlineDispatchKeyMatches(item, anchor));
|
|
1501
|
-
if (pres.length !== 1) return outlineCorrelationFailure('outline-dispatch-anchor-missing-or-ambiguous');
|
|
1502
|
-
const pre = pres[0];
|
|
1503
|
-
let workerRoot = expectedWorkerRoot;
|
|
1504
|
-
if (recordOf(pre.tool_input)) {
|
|
1505
|
-
const marker = parseOutlineDispatchPrompt(pre.tool_input.prompt);
|
|
1506
|
-
if (!marker) return outlineCorrelationFailure('outline-dispatch-marker-invalid');
|
|
1507
|
-
if (workerRoot !== undefined && !samePathKey(marker.workerRoot, workerRoot)) {
|
|
1508
|
-
return outlineCorrelationFailure('outline-dispatch-worker-root-mismatch');
|
|
1509
|
-
}
|
|
1510
|
-
workerRoot = marker.workerRoot;
|
|
1511
|
-
if (!Object.prototype.hasOwnProperty.call(pre.tool_input, 'run_in_background')) {
|
|
1512
|
-
return outlineCorrelationFailure('outline-dispatch-background-unobserved');
|
|
1513
|
-
}
|
|
1514
|
-
if (pre.tool_input.run_in_background !== false) {
|
|
1515
|
-
return outlineCorrelationFailure('outline-dispatch-background-enabled');
|
|
1516
|
-
}
|
|
1517
|
-
if (Object.prototype.hasOwnProperty.call(pre.tool_input, 'isolation')) {
|
|
1518
|
-
return outlineCorrelationFailure('outline-dispatch-isolation-unsupported');
|
|
1519
|
-
}
|
|
1520
|
-
} else {
|
|
1521
|
-
if (!recordOf(pre.outlineDispatch) || pre.outlineDispatch.state !== 'accepted' || !textOf(pre.outlineDispatch.workerRoot)) {
|
|
1522
|
-
return outlineCorrelationFailure('outline-dispatch-marker-unobserved');
|
|
1523
|
-
}
|
|
1524
|
-
if (workerRoot !== undefined && !samePathKey(pre.outlineDispatch.workerRoot, workerRoot)) {
|
|
1525
|
-
return outlineCorrelationFailure('outline-dispatch-worker-root-mismatch');
|
|
1526
|
-
}
|
|
1527
|
-
workerRoot = pre.outlineDispatch.workerRoot;
|
|
1528
|
-
if (!Object.prototype.hasOwnProperty.call(pre, 'run_in_background')) {
|
|
1529
|
-
return outlineCorrelationFailure('outline-dispatch-background-unobserved');
|
|
1530
|
-
}
|
|
1531
|
-
if (pre.run_in_background !== false) return outlineCorrelationFailure('outline-dispatch-background-enabled');
|
|
1532
|
-
if (!Object.prototype.hasOwnProperty.call(pre, 'isolationSet')) {
|
|
1533
|
-
return outlineCorrelationFailure('outline-dispatch-isolation-unobserved');
|
|
1534
|
-
}
|
|
1535
|
-
if (pre.isolationSet !== false) return outlineCorrelationFailure('outline-dispatch-isolation-unsupported');
|
|
1536
|
-
}
|
|
1537
|
-
if (!textOf(workerRoot) || !path.isAbsolute(workerRoot)) return outlineCorrelationFailure('outline-dispatch-worker-root-unobserved');
|
|
1538
|
-
|
|
1539
|
-
const failures = records.filter(item => outlineDispatchKeyMatches(item, pre) && item.event === 'PostToolUseFailure');
|
|
1540
|
-
if (failures.length) return outlineCorrelationFailure('outline-worker-result-failed');
|
|
1541
|
-
const results = records.filter(item => outlineDispatchKeyMatches(item, pre) && item.event === 'PostToolUse'
|
|
1542
|
-
&& ['Task', 'Agent'].includes(item.tool_name));
|
|
1543
|
-
if (results.length !== 1) return outlineCorrelationFailure('outline-worker-result-missing-or-ambiguous');
|
|
1544
|
-
const result = results[0];
|
|
1545
|
-
const status = outlineResultStatus(result);
|
|
1546
|
-
if (!status.present || status.value === undefined) return outlineCorrelationFailure('outline-worker-result-status-missing');
|
|
1547
|
-
if (status.value === 'async_launched') return outlineCorrelationFailure('outline-worker-result-async');
|
|
1548
|
-
if (status.value !== 'completed') return outlineCorrelationFailure('outline-worker-result-failed');
|
|
1549
|
-
const observedAgent = outlineResultAgentId(result);
|
|
1550
|
-
if (observedAgent.state !== 'accepted') return outlineCorrelationFailure(observedAgent.reason);
|
|
1551
|
-
const agentId = observedAgent.agentId;
|
|
1552
|
-
const sameAgentResults = records.filter(item => recordOf(item) && item.event === 'PostToolUse'
|
|
1553
|
-
&& ['Task', 'Agent'].includes(item.tool_name) && item.session_id === pre.session_id
|
|
1554
|
-
&& outlineResultAgentId(item).state === 'accepted' && outlineResultAgentId(item).agentId === agentId);
|
|
1555
|
-
if (sameAgentResults.length !== 1) return outlineCorrelationFailure('outline-worker-agent-id-replayed');
|
|
1556
|
-
|
|
1557
|
-
const starts = records.filter(item => recordOf(item) && item.event === 'SubagentStart'
|
|
1558
|
-
&& item.session_id === pre.session_id && item.agent_id === agentId);
|
|
1559
|
-
if (starts.length !== 1) return outlineCorrelationFailure('outline-worker-start-missing-or-ambiguous');
|
|
1560
|
-
const stops = records.filter(item => recordOf(item) && item.event === 'SubagentStop'
|
|
1561
|
-
&& item.session_id === pre.session_id && item.agent_id === agentId);
|
|
1562
|
-
if (stops.length !== 1) return outlineCorrelationFailure('outline-worker-stop-missing-or-ambiguous');
|
|
1563
|
-
const start = starts[0];
|
|
1564
|
-
const stop = stops[0];
|
|
1565
|
-
const preIndex = records.indexOf(pre);
|
|
1566
|
-
const startIndex = records.indexOf(start);
|
|
1567
|
-
const stopIndex = records.indexOf(stop);
|
|
1568
|
-
if (preIndex < 0 || startIndex < 0 || stopIndex < 0) return outlineCorrelationFailure('outline-worker-journal-position-unavailable');
|
|
1569
|
-
if (startIndex <= preIndex) return outlineCorrelationFailure('outline-worker-start-before-dispatch');
|
|
1570
|
-
if (stopIndex <= startIndex) return outlineCorrelationFailure('outline-worker-stop-before-start');
|
|
1571
|
-
for (const workerEvent of [start, stop]) {
|
|
1572
|
-
if (!textOf(workerEvent.cwd) || !path.isAbsolute(workerEvent.cwd)) {
|
|
1573
|
-
return outlineCorrelationFailure('outline-worker-root-unobserved');
|
|
1574
|
-
}
|
|
1575
|
-
if (!samePathKey(workerEvent.cwd, workerRoot)) return outlineCorrelationFailure('outline-worker-root-mismatch');
|
|
1576
|
-
}
|
|
1577
|
-
return { state: 'accepted', pre, result, start, stop, workerRoot, agentId };
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
function verifyOutlineMergeCorrespondence({ root, outlineCommit, draftCommit, mergedCommit, targetPaths, record } = {}) {
|
|
1581
|
-
if (!recordOf(record) || !textOf(root) || !Array.isArray(targetPaths) || !targetPaths.length
|
|
1582
|
-
|| record.outlineCommit !== outlineCommit || record.draftCommit !== draftCommit || record.mergedCommit !== mergedCommit) {
|
|
1583
|
-
return { state: 'unresolved', reason: 'merge-correspondence-missing-or-mismatched' };
|
|
1584
|
-
}
|
|
1585
|
-
try {
|
|
1586
|
-
for (const commit of [outlineCommit, draftCommit, mergedCommit]) {
|
|
1587
|
-
if (outlineGit(root, ['rev-parse', '--verify', `${commit}^{commit}`]).trim() !== commit) {
|
|
1588
|
-
return { state: 'unresolved', reason: 'merge-object-missing' };
|
|
1589
|
-
}
|
|
1590
|
-
}
|
|
1591
|
-
if (outlineCommit === draftCommit || outlineGit(root, ['merge-base', '--is-ancestor', outlineCommit, draftCommit]) !== '') {
|
|
1592
|
-
return { state: 'unresolved', reason: 'merge-pre-draft-ancestry-invalid' };
|
|
1593
|
-
}
|
|
1594
|
-
const recorded = record.targetBlobs;
|
|
1595
|
-
if (!recordOf(recorded) || captureJson(Object.keys(recorded).sort(compareKeys)) !== captureJson([...targetPaths].sort(compareKeys))) {
|
|
1596
|
-
return { state: 'unresolved', reason: 'merge-target-correspondence-invalid' };
|
|
1597
|
-
}
|
|
1598
|
-
let changed = false;
|
|
1599
|
-
for (const target of targetPaths) {
|
|
1600
|
-
const draft = outlineGit(root, ['rev-parse', `${draftCommit}:${target}`]).trim();
|
|
1601
|
-
const merged = outlineGit(root, ['rev-parse', `${mergedCommit}:${target}`]).trim();
|
|
1602
|
-
if (recorded[target]?.draft !== draft || recorded[target]?.merged !== merged) {
|
|
1603
|
-
return { state: 'unresolved', reason: 'merge-target-correspondence-invalid' };
|
|
1604
|
-
}
|
|
1605
|
-
changed ||= draft !== merged;
|
|
1606
|
-
}
|
|
1607
|
-
return { state: changed ? 'changed' : 'accepted', draftCommit, mergedCommit, targetPaths: [...targetPaths], targetBlobs: recorded };
|
|
1608
|
-
} catch (error) {
|
|
1609
|
-
return { state: 'unresolved', reason: error.message || 'merge-object-missing' };
|
|
1610
|
-
}
|
|
1611
|
-
}
|
|
1612
|
-
|
|
1613
|
-
function outlineAncestry(root, ancestor, descendant) {
|
|
1614
|
-
try {
|
|
1615
|
-
outlineGit(root, ['merge-base', '--is-ancestor', ancestor, descendant]);
|
|
1616
|
-
return true;
|
|
1617
|
-
} catch { return false; }
|
|
1618
|
-
}
|
|
1619
|
-
|
|
1620
|
-
function possibleWriterCapture(item) {
|
|
1621
|
-
if (!recordOf(item)) return false;
|
|
1622
|
-
if (OUTLINE_WRITE_TOOLS.includes(item.tool_name)) return true;
|
|
1623
|
-
if (!['Bash', 'PowerShell', 'exec_command'].includes(item.tool_name)) return false;
|
|
1624
|
-
return !['read-only', 'worktree-setup'].includes(classifyShell(item.command));
|
|
1625
|
-
}
|
|
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
|
-
|
|
1987
|
-
function writeTargetsOf(toolName, toolInput) {
|
|
1988
|
-
if (toolName === 'apply_patch') {
|
|
1989
|
-
const patch = typeof toolInput === 'string' ? toolInput : (recordOf(toolInput) ? String(toolInput.patch || toolInput.input || '') : '');
|
|
1990
|
-
const targets = [];
|
|
1991
|
-
for (const match of patch.matchAll(/^\*\*\* ([^\r\n]*)(?:\r?$)/gm)) {
|
|
1992
|
-
const header = match[1];
|
|
1993
|
-
if (['Begin Patch', 'End Patch', 'End of File'].includes(header)) continue;
|
|
1994
|
-
const fileHeader = /^(?:Add File|Update File|Delete File|Move to): (.*)$/.exec(header);
|
|
1995
|
-
if (!fileHeader) return null;
|
|
1996
|
-
targets.push(fileHeader[1]);
|
|
1997
|
-
}
|
|
1998
|
-
return targets;
|
|
1999
|
-
}
|
|
2000
|
-
const file = recordOf(toolInput) ? toolInput.file_path || toolInput.path : undefined;
|
|
2001
|
-
return typeof file === 'string' && file.length ? [file] : [];
|
|
2002
|
-
}
|
|
2003
|
-
|
|
2004
|
-
function validOutlineTarget(target) {
|
|
2005
|
-
return typeof target === 'string' && target.length > 0 && !target.includes('\0') && !target.includes('\\')
|
|
2006
|
-
&& !target.includes(':') && !path.posix.isAbsolute(target)
|
|
2007
|
-
&& target.split('/').every(part => part && part !== '.' && part !== '..');
|
|
2008
|
-
}
|
|
2009
|
-
|
|
2010
|
-
function outlineRootSpellings(root) {
|
|
2011
|
-
try {
|
|
2012
|
-
if (typeof root !== 'string' || !path.isAbsolute(root)) return [];
|
|
2013
|
-
return [...new Set([root, canonicalOutlineRoot(root)])];
|
|
2014
|
-
} catch { return []; }
|
|
2015
|
-
}
|
|
2016
|
-
|
|
2017
|
-
function outlineCwdMatchesRoot(cwd, root, allowVerifiedAlias = false) {
|
|
2018
|
-
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
|
|
2019
|
-
if (outlineRootSpellings(root).includes(cwd)) return true;
|
|
2020
|
-
if (!allowVerifiedAlias) return false;
|
|
2021
|
-
try { return canonicalOutlineRoot(cwd) === canonicalOutlineRoot(root); }
|
|
2022
|
-
catch { return false; }
|
|
2023
|
-
}
|
|
2024
|
-
|
|
2025
|
-
function outlineCaptureRootSpellings(root, cwd) {
|
|
2026
|
-
const roots = outlineRootSpellings(root);
|
|
2027
|
-
// Hook setup may retain the canonical root while the captured cwd keeps its original spelling; this affects topology only.
|
|
2028
|
-
if (outlineCwdMatchesRoot(cwd, root, true)) roots.push(cwd);
|
|
2029
|
-
return [...new Set(roots)];
|
|
2030
|
-
}
|
|
2031
|
-
|
|
2032
|
-
function outlineRelativeSpellingKey(spelling, toolName) {
|
|
2033
|
-
if (validOutlineTarget(spelling)) return spelling;
|
|
2034
|
-
if (process.platform !== 'win32' || !OUTLINE_WRITE_TOOLS.includes(toolName)
|
|
2035
|
-
|| !spelling.includes(path.sep) || spelling.includes('/')) return null;
|
|
2036
|
-
const candidate = spelling.split(path.sep).join('/');
|
|
2037
|
-
return validOutlineTarget(candidate) ? candidate : null;
|
|
2038
|
-
}
|
|
2039
|
-
|
|
2040
|
-
function outlineSpellingKey(spelling, { root, cwd, toolName } = {}) {
|
|
2041
|
-
if (typeof spelling !== 'string' || !spelling.length || spelling.includes('\0')
|
|
2042
|
-
|| !outlineCwdMatchesRoot(cwd, root, true)) return null;
|
|
2043
|
-
const relative = outlineRelativeSpellingKey(spelling, toolName);
|
|
2044
|
-
if (relative) return relative;
|
|
2045
|
-
for (const rootSpelling of outlineCaptureRootSpellings(root, cwd)) {
|
|
2046
|
-
const prefix = rootSpelling.endsWith(path.sep) ? rootSpelling : `${rootSpelling}${path.sep}`;
|
|
2047
|
-
if (!spelling.startsWith(prefix)) continue;
|
|
2048
|
-
return outlineRelativeSpellingKey(spelling.slice(prefix.length), toolName);
|
|
2049
|
-
}
|
|
2050
|
-
return null;
|
|
2051
|
-
}
|
|
2052
|
-
|
|
2053
|
-
function outlineTargetSpellings(target, { root, toolName } = {}) {
|
|
2054
|
-
if (!validOutlineTarget(target)) return [];
|
|
2055
|
-
const targetSpellings = [target];
|
|
2056
|
-
if (process.platform === 'win32' && OUTLINE_WRITE_TOOLS.includes(toolName)) {
|
|
2057
|
-
targetSpellings.push(target.split('/').join(path.sep));
|
|
2058
|
-
}
|
|
2059
|
-
const spellings = [...targetSpellings];
|
|
2060
|
-
for (const rootSpelling of outlineRootSpellings(root)) {
|
|
2061
|
-
const prefix = rootSpelling.endsWith(path.sep) ? rootSpelling : `${rootSpelling}${path.sep}`;
|
|
2062
|
-
for (const renderedTarget of targetSpellings) spellings.push(prefix + renderedTarget);
|
|
2063
|
-
}
|
|
2064
|
-
return spellings;
|
|
2065
|
-
}
|
|
2066
|
-
|
|
2067
|
-
// Capture can prove a lexical path/topology before the later handoff supplies the pin. Its candidate is non-authorizing;
|
|
2068
|
-
// the assessment call below must match the same raw spelling against the validated pinned target set.
|
|
2069
|
-
function recognizeOutlineTarget(spelling, { root, cwd, targets, toolName } = {}) {
|
|
2070
|
-
const hasPinnedTargets = Array.isArray(targets);
|
|
2071
|
-
if (typeof spelling !== 'string' || !spelling.length || spelling.includes('\0')
|
|
2072
|
-
|| !outlineCwdMatchesRoot(cwd, root, !hasPinnedTargets)) return null;
|
|
2073
|
-
if (Array.isArray(targets)) {
|
|
2074
|
-
const target = targets.find(item => outlineTargetSpellings(item, { root, toolName }).includes(spelling));
|
|
2075
|
-
return target ? { candidate: target, target } : null;
|
|
2076
|
-
}
|
|
2077
|
-
const candidate = outlineSpellingKey(spelling, { root, cwd, toolName });
|
|
2078
|
-
if (!candidate) return null;
|
|
2079
|
-
return { candidate, target: null };
|
|
2080
|
-
}
|
|
2081
|
-
|
|
2082
|
-
function outlineBToOGitAllowed(command, { cwd, root, targets, topology }) {
|
|
2083
|
-
const parsed = safeTokenize(String(command || '').trim());
|
|
2084
|
-
if (!parsed.ok || parsed.tokens[0] !== 'git' || parsed.tokens.length < 2) return false;
|
|
2085
|
-
const [operation, ...args] = parsed.tokens.slice(1);
|
|
2086
|
-
if (operation === 'add') {
|
|
2087
|
-
const hasOperandMarker = args[0] === '--';
|
|
2088
|
-
const operands = hasOperandMarker ? args.slice(1) : args;
|
|
2089
|
-
if (!operands.length || !Array.isArray(topology) || topology.length !== operands.length) return false;
|
|
2090
|
-
if (!hasOperandMarker && operands.some(operand => operand.startsWith('-'))) return false;
|
|
2091
|
-
return operands.every((operand, index) => {
|
|
2092
|
-
if (!operand || operand.startsWith(':') || /[*?\[\]{}]/.test(operand) || /[\\/]$/.test(operand)) return false;
|
|
2093
|
-
const target = recognizeOutlineTarget(operand, { root, cwd, targets, toolName: 'Bash' })?.target;
|
|
2094
|
-
const proof = topology[index];
|
|
2095
|
-
return Boolean(target && proof?.path === target && proof.state === 'regular'
|
|
2096
|
-
&& outlineFilesystemProof(root, root, target, false).state === 'regular');
|
|
2097
|
-
});
|
|
2098
|
-
}
|
|
2099
|
-
return operation === 'commit' && args.length === 2 && args[0] === '-m' && args[1] !== '';
|
|
2100
|
-
}
|
|
2101
|
-
|
|
2102
|
-
function outlineFilesystemProof(root, cwd, target, allowMissing) {
|
|
2103
|
-
let relativePath;
|
|
2104
|
-
try {
|
|
2105
|
-
const canonicalRoot = canonicalOutlineRoot(root);
|
|
2106
|
-
const base = canonicalOutlineRoot(cwd || root);
|
|
2107
|
-
if (base !== canonicalRoot) return { path: null, state: 'unresolved' };
|
|
2108
|
-
const relative = path.relative(canonicalRoot, path.resolve(canonicalRoot, target));
|
|
2109
|
-
if (!relative || path.isAbsolute(relative) || relative === '..' || relative.startsWith(`..${path.sep}`)) {
|
|
2110
|
-
return { path: null, state: 'unresolved' };
|
|
2111
|
-
}
|
|
2112
|
-
const absolute = path.resolve(canonicalRoot, relative);
|
|
2113
|
-
relativePath = path.relative(canonicalRoot, absolute);
|
|
2114
|
-
if (!relativePath || path.isAbsolute(relativePath) || relativePath === '..' || relativePath.startsWith(`..${path.sep}`)) {
|
|
2115
|
-
return { path: null, state: 'unresolved' };
|
|
2116
|
-
}
|
|
2117
|
-
const relativeKey = relativePath.split(path.sep).join('/');
|
|
2118
|
-
let current = canonicalRoot;
|
|
2119
|
-
const parts = relativePath.split(path.sep);
|
|
2120
|
-
for (let index = 0; index < parts.length; index++) {
|
|
2121
|
-
current = path.join(current, parts[index]);
|
|
2122
|
-
let stat;
|
|
2123
|
-
try { stat = fs.lstatSync(current); }
|
|
2124
|
-
catch (error) {
|
|
2125
|
-
return error.code === 'ENOENT' && allowMissing
|
|
2126
|
-
? { path: relativeKey, state: 'absent' } : { path: relativeKey, state: 'unresolved' };
|
|
2127
|
-
}
|
|
2128
|
-
if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory())) {
|
|
2129
|
-
return { path: relativeKey, state: 'unresolved' };
|
|
2130
|
-
}
|
|
2131
|
-
if (index === parts.length - 1) return { path: relativeKey, state: stat.isFile() ? 'regular' : 'unresolved' };
|
|
2132
|
-
}
|
|
2133
|
-
} catch { /* filesystem state is evidence only when every component can be checked */ }
|
|
2134
|
-
return { path: relativePath ? relativePath.split(path.sep).join('/') : null, state: 'unresolved' };
|
|
2135
|
-
}
|
|
2136
|
-
|
|
2137
|
-
function outlineGitTreeHasRegularBlob(root, tree, target) {
|
|
2138
|
-
try {
|
|
2139
|
-
const entries = outlineGit(root, ['--literal-pathspecs', 'ls-tree', '-z', tree, '--', target], true)
|
|
2140
|
-
.toString('utf8').split('\0').filter(Boolean);
|
|
2141
|
-
if (entries.length !== 1) return false;
|
|
2142
|
-
const tab = entries[0].indexOf('\t');
|
|
2143
|
-
if (tab < 0 || entries[0].slice(tab + 1) !== target) return false;
|
|
2144
|
-
const [mode, type, oid] = entries[0].slice(0, tab).split(/\s+/);
|
|
2145
|
-
return type === 'blob' && ['100644', '100755'].includes(mode) && /^[0-9a-f]+$/i.test(oid);
|
|
2146
|
-
} catch { return false; }
|
|
2147
|
-
}
|
|
2148
|
-
|
|
2149
|
-
// Phase-aware writer decision (W1–W3). Principal, phase and operation-time path topology come from captured records.
|
|
2150
|
-
// Allowed: coordinator Write/Edit/apply_patch of exactly a pinned target before the reviewer lifecycle starts; coordinator
|
|
2151
|
-
// target-bound git add or simple git commit before review; the correlated draft worker
|
|
2152
|
-
// between dispatch and its Stop. Everything else, including any coordinator state write after review, stays ambiguous.
|
|
2153
|
-
function outlineWriterAllowed(item, { index, sessionId, root, targets, worker, workerRoot, reviewStartIndex, reviewStopIndex,
|
|
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;
|
|
2158
|
-
const phase = index < reviewStartIndex ? 'b-to-o' : index <= reviewStopIndex ? 'review'
|
|
2159
|
-
: index < dispatchIndex ? 'review-to-dispatch' : index <= workerStopIndex ? 'dispatch-to-draft' : 'after-draft';
|
|
2160
|
-
if (phase === 'dispatch-to-draft') return item.agent_id === worker.agent_id && sameCanonicalPath(item.cwd, workerRoot);
|
|
2161
|
-
if (phase !== 'b-to-o' || textOf(item.agent_id) || item.session_id !== sessionId) return false;
|
|
2162
|
-
if (item.event !== 'PreToolUse') {
|
|
2163
|
-
const pre = (Array.isArray(captures) ? captures : []).find(record => record.event === 'PreToolUse'
|
|
2164
|
-
&& record.session_id === item.session_id && record.tool_use_id === item.tool_use_id
|
|
2165
|
-
&& record.tool_name === item.tool_name && record.command === item.command
|
|
2166
|
-
&& captureJson(record.writeTargets || null) === captureJson(item.writeTargets || null)
|
|
2167
|
-
&& samePathKey(record.cwd || root, item.cwd || root));
|
|
2168
|
-
return Boolean(pre && outlineWriterAllowed(pre, { index: captures.indexOf(pre), sessionId, root, targets, worker, workerRoot,
|
|
2169
|
-
reviewStartIndex, reviewStopIndex, dispatchIndex, workerStopIndex, captures }));
|
|
2170
|
-
}
|
|
2171
|
-
if (OUTLINE_WRITE_TOOLS.includes(item.tool_name)) {
|
|
2172
|
-
const topology = item.outlineWriteTopology;
|
|
2173
|
-
return Array.isArray(item.writeTargets) && item.writeTargets.length > 0
|
|
2174
|
-
&& Array.isArray(topology) && topology.length === item.writeTargets.length
|
|
2175
|
-
&& item.writeTargets.every((file, index) => {
|
|
2176
|
-
const target = recognizeOutlineTarget(file, { root, cwd: item.cwd, targets, toolName: item.tool_name })?.target;
|
|
2177
|
-
const proof = topology[index];
|
|
2178
|
-
return Boolean(target && proof?.path === target && ['absent', 'regular'].includes(proof.state)
|
|
2179
|
-
&& outlineFilesystemProof(root, root, target, false).state === 'regular');
|
|
2180
|
-
});
|
|
2181
|
-
}
|
|
2182
|
-
const cwd = item.cwd;
|
|
2183
|
-
return item.tool_name === 'Bash' && outlineCwdMatchesRoot(cwd, root)
|
|
2184
|
-
&& outlineBToOGitAllowed(item.command, { cwd, root, targets, topology: item.outlineWriteTopology });
|
|
2185
|
-
}
|
|
2186
|
-
|
|
2187
|
-
function sameCanonicalPath(left, right) {
|
|
2188
|
-
try {
|
|
2189
|
-
fs.statSync(left);
|
|
2190
|
-
fs.statSync(right);
|
|
2191
|
-
return key(left) === key(right);
|
|
2192
|
-
}
|
|
2193
|
-
catch { return false; }
|
|
2194
|
-
}
|
|
2195
|
-
|
|
2196
|
-
function samePathKey(left, right) {
|
|
2197
|
-
try { return key(left) === key(right); }
|
|
2198
|
-
catch { return false; }
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2201
|
-
function sameOutlineTaskBinding(left, right) {
|
|
2202
|
-
if (!recordOf(left) || !recordOf(right)) return false;
|
|
2203
|
-
const { baselineRoot: leftRoot, ...leftIdentity } = left;
|
|
2204
|
-
const { baselineRoot: rightRoot, ...rightIdentity } = right;
|
|
2205
|
-
return captureJson(leftIdentity) === captureJson(rightIdentity) && sameCanonicalPath(leftRoot, rightRoot);
|
|
2206
|
-
}
|
|
2207
|
-
|
|
2208
|
-
function resolveOutlineEvidence({ safeInput, capture, captures, request, originRef } = {}) {
|
|
2209
|
-
const fail = (reason, status = 'rejected') => ({ status, diagnostics: [diagnostic(reason, { reason })] });
|
|
2210
|
-
try {
|
|
2211
|
-
const cap = capture;
|
|
2212
|
-
const sessionDir = safeInput.sessionDir;
|
|
2213
|
-
const dispatch = cap?.outlineDispatch;
|
|
2214
|
-
if (!recordOf(dispatch) || dispatch.schema !== OUTLINE_DISPATCH_SCHEMA || dispatch.state !== 'accepted'
|
|
2215
|
-
|| !textOf(dispatch.seamRef) || dispatch.captureRef !== cap.ref || dispatch.toolUseId !== cap.tool_use_id) {
|
|
2216
|
-
// The dispatch-time reason (for example outline-identity-mismatch) is kept beside the wrapper code, so the rejection names its cause.
|
|
2217
|
-
const reasons = recordOf(dispatch) && Array.isArray(dispatch.reasons) ? dispatch.reasons.filter(reason => /^[a-z0-9-]+$/.test(String(reason))) : [];
|
|
2218
|
-
return { status: 'rejected', diagnostics: [diagnostic('outline-pre-dispatch-seam-unresolved', { reason: 'outline-pre-dispatch-seam-unresolved' }),
|
|
2219
|
-
...reasons.map(reason => diagnostic(reason, { reason }))] };
|
|
2220
|
-
}
|
|
2221
|
-
if (cap.event !== 'PreToolUse' || !['Task', 'Agent'].includes(cap.tool_name)
|
|
2222
|
-
|| cap.session_id !== safeInput.sessionId || cap.observedIdentity?.taskPin?.taskId !== safeInput.taskId) {
|
|
2223
|
-
return fail('outline-dispatch-identity-mismatch');
|
|
2224
|
-
}
|
|
2225
|
-
const taskState = outlineTaskState(sessionDir);
|
|
2226
|
-
if (taskState.state !== 'accepted' || taskState.taskBinding.taskId !== safeInput.taskId
|
|
2227
|
-
|| (recordOf(safeInput.taskBinding) && !sameOutlineTaskBinding(taskState.taskBinding, safeInput.taskBinding))
|
|
2228
|
-
|| !sameOutlineTaskBinding(cap.observedIdentity.taskPin, taskState.taskBinding)
|
|
2229
|
-
|| cap.observedIdentity.baselinePin?.commit !== taskState.baseline.commit
|
|
2230
|
-
|| !sameCanonicalPath(cap.observedIdentity.baselinePin?.root, taskState.baseline.root)) {
|
|
2231
|
-
return fail('outline-task-binding-mismatch');
|
|
2232
|
-
}
|
|
2233
|
-
const attempt = resolveOutlineAttempt({ sessionDir, taskId: dispatch.taskId, attemptId: dispatch.attemptId });
|
|
2234
|
-
if (attempt.state !== 'accepted') return fail(attempt.reason || 'outline-attempt-unresolved');
|
|
2235
|
-
if (attempt.handoffDigest !== dispatch.handoffDigest) return fail('outline-handoff-changed-after-dispatch');
|
|
2236
|
-
const seamRef = String(dispatch.seamRef).replace(/\\/g, '/');
|
|
2237
|
-
if (path.isAbsolute(seamRef) || seamRef.split('/').some(part => !part || part === '.' || part === '..')) {
|
|
2238
|
-
return fail('outline-seam-reference-invalid');
|
|
2239
|
-
}
|
|
2240
|
-
const seamFile = path.join(sessionDir, ...seamRef.split('/'));
|
|
2241
|
-
const seamLoaded = readOutlineJson(seamFile);
|
|
2242
|
-
if (seamLoaded.state !== 'accepted') return fail('outline-seam-missing');
|
|
2243
|
-
const seam = seamLoaded.value;
|
|
2244
|
-
if (seam.schema !== OUTLINE_SEAM_SCHEMA || seam.state !== 'accepted' || seam.captureRef !== cap.ref
|
|
2245
|
-
|| seam.toolUseId !== cap.tool_use_id || seam.taskId !== dispatch.taskId || seam.attemptId !== dispatch.attemptId
|
|
2246
|
-
|| seam.dispatchInputDigest !== dispatch.dispatchInputDigest || seam.handoffDigest !== attempt.handoffDigest
|
|
2247
|
-
|| seam.tokenDigest !== dispatch.tokenDigest) return fail('outline-seam-mismatch');
|
|
2248
|
-
const sameAttempt = (Array.isArray(captures) ? captures : []).filter(item => recordOf(item)
|
|
2249
|
-
&& item.event === 'PreToolUse' && item.outlineDispatch?.taskId === dispatch.taskId
|
|
2250
|
-
&& item.outlineDispatch?.attemptId === dispatch.attemptId && item.outlineDispatch?.tokenDigest === dispatch.tokenDigest);
|
|
2251
|
-
for (const other of sameAttempt) {
|
|
2252
|
-
const evidence = other.outlineDispatch;
|
|
2253
|
-
if (evidence.state !== 'accepted' || evidence.dispatchInputDigest !== dispatch.dispatchInputDigest
|
|
2254
|
-
|| other.tool_use_id !== cap.tool_use_id) return fail('outline-dispatch-replay-or-conflict');
|
|
2255
|
-
}
|
|
2256
|
-
const sameToolUse = (Array.isArray(captures) ? captures : []).filter(item => recordOf(item)
|
|
2257
|
-
&& item.event === 'PreToolUse' && item.tool_use_id === cap.tool_use_id);
|
|
2258
|
-
if (sameToolUse.some(item => item.ref !== cap.ref && (item.outlineDispatch?.state !== 'accepted'
|
|
2259
|
-
|| item.outlineDispatch.dispatchInputDigest !== dispatch.dispatchInputDigest))) return fail('outline-tool-use-id-replayed');
|
|
2260
|
-
const handoff = attempt.handoff;
|
|
2261
|
-
const targetPaths = Array.isArray(handoff.targetPaths) ? handoff.targetPaths : [];
|
|
2262
|
-
const expectedPin = recordOf(safeInput.qualification) && safeInput.qualification.faked === true
|
|
2263
|
-
&& recordOf(safeInput.outlineFixture?.expectedPin) ? safeInput.outlineFixture.expectedPin : OUTLINE_INVENTORY_PIN;
|
|
2264
|
-
const inventoryRoot = path.join(sessionDir, 'doc-reconciliation', 'outline-confirmation', 'inventory');
|
|
2265
|
-
const pinFile = path.join(inventoryRoot, 'inventory-pin.json');
|
|
2266
|
-
const pinLoaded = readOutlineJson(pinFile);
|
|
2267
|
-
if (pinLoaded.state !== 'accepted' || outlineSha(pinLoaded.bytes) !== seam.inventoryPinDigest) return fail('outline-inventory-pin-changed');
|
|
2268
|
-
let inventoryBytes;
|
|
2269
|
-
try { inventoryBytes = fs.readFileSync(path.join(inventoryRoot, expectedPin.retainedArtifactPath.split('/').pop())); }
|
|
2270
|
-
catch { return fail('outline-inventory-bytes-missing'); }
|
|
2271
|
-
const inventory = validateOutlineInventoryPin({ bytes: inventoryBytes, pin: pinLoaded.value, expectedPin });
|
|
2272
|
-
if (inventory.state !== 'accepted') return fail(inventory.reason || 'outline-inventory-unresolved');
|
|
2273
|
-
const outlineDigests = {};
|
|
2274
|
-
const reviewRows = {};
|
|
2275
|
-
for (const target of targetPaths) {
|
|
2276
|
-
if (!outlineGitTreeHasRegularBlob(seam.worktree.root, handoff.outline.tree, target)) {
|
|
2277
|
-
return fail('outline-target-object-not-regular');
|
|
2278
|
-
}
|
|
2279
|
-
const bytes = outlineGit(seam.worktree.root, ['show', `${handoff.outline.commit}:${target}`], true);
|
|
2280
|
-
outlineDigests[target] = outlineSha(bytes);
|
|
2281
|
-
const citation = parseOutlineCitation(bytes, target);
|
|
2282
|
-
if (citation.state !== 'accepted') return fail(citation.reason || 'outline-citation-invalid');
|
|
2283
|
-
const row = resolveInventoryRow(inventory, citation.rowId);
|
|
2284
|
-
if (row.state !== 'accepted' || row.row.domain !== citation.domain || citation.domain !== handoff.inventory?.domain
|
|
2285
|
-
|| citation.rowId !== handoff.inventory?.rowId) return fail(row.reason || 'outline-inventory-binding-mismatch');
|
|
2286
|
-
reviewRows[target] = row.row;
|
|
2287
|
-
}
|
|
2288
|
-
const review = validateOutlineReview({ handoff, attemptDir: attempt.attemptDir, captures, targetPaths,
|
|
2289
|
-
outlineDigests, inventory, sessionId: safeInput.sessionId });
|
|
2290
|
-
if (review.state !== 'accepted' || review.captureDigest !== seam.reviewCaptureDigest
|
|
2291
|
-
|| review.reviewDigest !== seam.reviewDigest || review.reviewerPrincipal !== seam.reviewerPrincipal) {
|
|
2292
|
-
return fail(review.reason || 'outline-review-changed-after-dispatch');
|
|
2293
|
-
}
|
|
2294
|
-
const correlation = correlateOutlineDispatch(captures, cap, seam.workerRoot);
|
|
2295
|
-
if (correlation.state !== 'accepted') return fail(correlation.reason);
|
|
2296
|
-
const worker = correlation.start;
|
|
2297
|
-
const workerRoot = correlation.workerRoot;
|
|
2298
|
-
if (review.reviewerPrincipal === worker.agent_id) return fail('outline-reviewer-is-draft-worker');
|
|
2299
|
-
const principals = { author: safeInput.sessionId, executors: journalExecutors(captures, safeInput.sessionId) };
|
|
2300
|
-
if (!reviewRecordIndependent(review.review, captures, principals)) return fail('outline-review-not-independent');
|
|
2301
|
-
// An agent whose start and unique stop both precede the dispatch cannot write after the seam; earlier writes
|
|
2302
|
-
// are covered by the clean-O seam check and by unattributedWriters below.
|
|
2303
|
-
const journal = Array.isArray(captures) ? captures : [];
|
|
2304
|
-
const dispatchIndex = journal.indexOf(correlation.pre);
|
|
2305
|
-
const uniqueLifecycle = start => {
|
|
2306
|
-
if (!textOf(start.session_id) || !textOf(start.agent_id)) return null;
|
|
2307
|
-
const lifecycle = event => journal.filter(item => recordOf(item) && item.event === event
|
|
2308
|
-
&& item.session_id === start.session_id && textOf(start.agent_id) && item.agent_id === start.agent_id);
|
|
2309
|
-
// Exactly one Start and one Stop per (session_id, agent_id); a duplicate either way stays ambiguous.
|
|
2310
|
-
const starts = lifecycle('SubagentStart');
|
|
2311
|
-
const stops = lifecycle('SubagentStop');
|
|
2312
|
-
if (starts.length !== 1 || starts[0] !== start || stops.length !== 1) return null;
|
|
2313
|
-
const startIndex = journal.indexOf(start);
|
|
2314
|
-
const stopIndex = journal.indexOf(stops[0]);
|
|
2315
|
-
if (startIndex < 0 || stopIndex <= startIndex) return null;
|
|
2316
|
-
return { startIndex, stopIndex };
|
|
2317
|
-
};
|
|
2318
|
-
const stoppedBeforeDispatch = start => {
|
|
2319
|
-
const lifecycle = uniqueLifecycle(start);
|
|
2320
|
-
return Boolean(lifecycle && dispatchIndex >= 0 && lifecycle.stopIndex < dispatchIndex);
|
|
2321
|
-
};
|
|
2322
|
-
const startedAfterWorkerStop = start => {
|
|
2323
|
-
const lifecycle = uniqueLifecycle(start);
|
|
2324
|
-
const workerStopIndex = journal.indexOf(correlation.stop);
|
|
2325
|
-
return Boolean(lifecycle && workerStopIndex >= 0 && lifecycle.startIndex > workerStopIndex);
|
|
2326
|
-
};
|
|
2327
|
-
const competingStarts = journal.filter(item => recordOf(item)
|
|
2328
|
-
&& item.event === 'SubagentStart' && item.ref !== worker.ref && sameCanonicalPath(item.cwd, workerRoot)
|
|
2329
|
-
&& !stoppedBeforeDispatch(item) && !startedAfterWorkerStop(item));
|
|
2330
|
-
if (competingStarts.length) return fail('outline-competing-writer-start');
|
|
2331
|
-
// Reviewer lifecycle is exactly one Start and one Stop for its identity; a duplicate or missing record withholds credit.
|
|
2332
|
-
const reviewerLifecycle = event => journal.filter(item => recordOf(item) && item.event === event
|
|
2333
|
-
&& item.agent_id === review.reviewerPrincipal).length;
|
|
2334
|
-
if (reviewerLifecycle('SubagentStart') !== 1 || reviewerLifecycle('SubagentStop') !== 1) {
|
|
2335
|
-
return fail('outline-review-result-missing-or-ambiguous');
|
|
2336
|
-
}
|
|
2337
|
-
// The O the reviewer recorded at launch must still be the O dispatch and the handoff name (#341 step 1).
|
|
2338
|
-
const identityNow = validateOutlineIdentity({ handoff, captures });
|
|
2339
|
-
if (identityNow.state !== 'accepted' || identityNow.identityDigest !== seam.outlineIdentityDigest) {
|
|
2340
|
-
return fail(identityNow.reason || 'outline-identity-mismatch');
|
|
2341
|
-
}
|
|
2342
|
-
// Review window: the reviewer's first record (or its launch result) through its SubagentStop.
|
|
2343
|
-
const reviewLaunchIds = new Set(journal.filter(item => recordOf(item) && item.event === 'PostToolUse'
|
|
2344
|
-
&& ['Task', 'Agent'].includes(item.tool_name) && item.agent_id === review.reviewerPrincipal && textOf(item.tool_use_id))
|
|
2345
|
-
.map(item => item.tool_use_id));
|
|
2346
|
-
const writerWindow = {
|
|
2347
|
-
sessionId: safeInput.sessionId, root: taskState.baseline.root, targets: targetPaths, worker, workerRoot,
|
|
2348
|
-
captures: journal,
|
|
2349
|
-
reviewStartIndex: journal.findIndex(item => recordOf(item) && (item.agent_id === review.reviewerPrincipal
|
|
2350
|
-
|| (textOf(item.tool_use_id) && reviewLaunchIds.has(item.tool_use_id)))),
|
|
2351
|
-
reviewStopIndex: journal.indexOf(review.review), dispatchIndex, workerStopIndex: journal.indexOf(correlation.stop),
|
|
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();
|
|
2358
|
-
const unattributedWriters = journal.filter((item, index) => possibleWriterCapture(item)
|
|
2359
|
-
&& !outlineWriterAllowed(item, { ...writerWindow, index }));
|
|
2360
|
-
if (unattributedWriters.length) return fail('outline-writer-activity-ambiguous');
|
|
2361
|
-
// The B→O commit is accepted only if O changes exactly the pinned target(s) relative to B.
|
|
2362
|
-
const oChanged = outlineGit(seam.worktree.root, ['diff', '--name-only', '--no-renames', '-z', taskState.baseline.commit,
|
|
2363
|
-
handoff.outline.commit]).split('\0').filter(Boolean).sort(compareKeys);
|
|
2364
|
-
if (captureJson(oChanged) !== captureJson([...targetPaths].sort(compareKeys))) return fail('outline-commit-scope-invalid');
|
|
2365
|
-
// The cumulative diff hides content committed then reverted inside B..O, so every commit (merges too, per parent) must touch only the targets.
|
|
2366
|
-
const targetSet = new Set(targetPaths);
|
|
2367
|
-
const rangeCommits = outlineGit(seam.worktree.root, ['rev-list', `${taskState.baseline.commit}..${handoff.outline.commit}`])
|
|
2368
|
-
.split('\n').filter(Boolean);
|
|
2369
|
-
for (const commit of rangeCommits) {
|
|
2370
|
-
const touched = outlineGit(seam.worktree.root, ['diff-tree', '-r', '--root', '-m', '--no-commit-id', '--name-only',
|
|
2371
|
-
'--no-renames', '-z', commit]).split('\0').filter(Boolean);
|
|
2372
|
-
if (touched.some(file => !targetSet.has(file))) return fail('outline-commit-scope-invalid');
|
|
2373
|
-
}
|
|
2374
|
-
|
|
2375
|
-
let candidateRoot;
|
|
2376
|
-
try { candidateRoot = canonicalOutlineRoot(safeInput.workspaceRoot); }
|
|
2377
|
-
catch { return fail('outline-candidate-root-unavailable'); }
|
|
2378
|
-
const baseline = taskState.baseline;
|
|
2379
|
-
const outlineCommit = handoff.outline.commit;
|
|
2380
|
-
let finalCommit;
|
|
2381
|
-
let finalTree;
|
|
2382
|
-
try {
|
|
2383
|
-
finalCommit = outlineGit(candidateRoot, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
|
|
2384
|
-
finalTree = outlineGit(candidateRoot, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
|
|
2385
|
-
outlineGit(candidateRoot, ['rev-parse', '--verify', `${outlineCommit}^{commit}`]);
|
|
2386
|
-
outlineGit(candidateRoot, ['rev-parse', '--verify', `${baseline.commit}^{commit}`]);
|
|
2387
|
-
} catch { return fail('outline-final-git-object-unavailable'); }
|
|
2388
|
-
if (finalCommit === outlineCommit) return fail('outline-final-draft-missing', 'unavailable');
|
|
2389
|
-
if (!outlineAncestry(candidateRoot, baseline.commit, outlineCommit)) return fail('outline-B-to-O-ancestry-invalid');
|
|
2390
|
-
let merge = { state: 'accepted', draftCommit: finalCommit, mergedCommit: finalCommit, targetPaths };
|
|
2391
|
-
if (!outlineAncestry(candidateRoot, outlineCommit, finalCommit)) {
|
|
2392
|
-
const mergeFile = path.join(attempt.attemptDir, 'merge-correspondence.json');
|
|
2393
|
-
const mergeLoaded = readOutlineJson(mergeFile);
|
|
2394
|
-
if (mergeLoaded.state !== 'accepted') return fail('outline-merge-correspondence-unavailable', 'unavailable');
|
|
2395
|
-
const correspondence = mergeLoaded.value;
|
|
2396
|
-
if (correspondence.taskId !== dispatch.taskId || correspondence.attemptId !== dispatch.attemptId
|
|
2397
|
-
|| correspondence.baselineCommit !== baseline.commit) return fail('outline-merge-correspondence-mismatch');
|
|
2398
|
-
merge = verifyOutlineMergeCorrespondence({ root: candidateRoot, outlineCommit,
|
|
2399
|
-
draftCommit: correspondence.draftCommit, mergedCommit: finalCommit, targetPaths, record: correspondence });
|
|
2400
|
-
if (!['accepted', 'changed'].includes(merge.state)) return fail(merge.reason || 'outline-merge-correspondence-invalid', 'unavailable');
|
|
2401
|
-
}
|
|
2402
|
-
const draftArtifactDigests = {};
|
|
2403
|
-
const draftBlobOids = {};
|
|
2404
|
-
for (const target of targetPaths) {
|
|
2405
|
-
const atBaseline = outlineGit(candidateRoot, ['ls-tree', '-r', '--name-only', baseline.commit, '--', target]).trim();
|
|
2406
|
-
if (atBaseline.split('\n').filter(Boolean).includes(target)) return fail('outline-target-existed-at-B');
|
|
2407
|
-
let candidateBytes;
|
|
2408
|
-
let commitBytes;
|
|
2409
|
-
try {
|
|
2410
|
-
candidateBytes = fs.readFileSync(path.join(candidateRoot, ...target.split('/')));
|
|
2411
|
-
commitBytes = outlineGit(candidateRoot, ['show', `${finalCommit}:${target}`], true);
|
|
2412
|
-
} catch { return fail('outline-final-target-missing'); }
|
|
2413
|
-
if (!Buffer.from(candidateBytes).equals(commitBytes)) return fail('outline-final-working-tree-not-D');
|
|
2414
|
-
draftArtifactDigests[target] = outlineSha(commitBytes);
|
|
2415
|
-
draftBlobOids[target] = outlineGit(candidateRoot, ['rev-parse', `${finalCommit}:${target}`]).trim();
|
|
2416
|
-
}
|
|
2417
|
-
const independentOf = [...new Set([safeInput.sessionId, ...principals.executors])].filter(value => textOf(value) && value !== review.reviewerPrincipal);
|
|
2418
|
-
const event = {
|
|
2419
|
-
eventId: 'claude-outline-' + digestText(captureJson({ handoffDigest: attempt.handoffDigest,
|
|
2420
|
-
seamDigest: seamLoadedDigest(seamFile), draftCommit: finalCommit })),
|
|
2421
|
-
producerId: 'claude-code-origin-provider', originRef, principalId: review.reviewerPrincipal,
|
|
2422
|
-
provenance: `claude-code-outline-capture:${cap.captureId}`, capability: 'outline-confirmation', kind: 'review',
|
|
2423
|
-
verdict: 'approve', summary: review.review.reviewSummary, independentOf,
|
|
2424
|
-
identity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2425
|
-
paths: targetPaths, reviewedArtifactDigests: { ...outlineDigests,
|
|
2426
|
-
[review.inventoryPath]: inventory.artifactDigest }, draftArtifactDigests,
|
|
2427
|
-
outlineEvidence: {
|
|
2428
|
-
schema: 'harness.outline-confirmation.v1', state: 'validated', taskId: dispatch.taskId,
|
|
2429
|
-
attemptId: dispatch.attemptId, inventoryRowId: handoff.inventory.rowId, domain: handoff.inventory.domain,
|
|
2430
|
-
inventoryPinDigest: seam.inventoryPinDigest, inventoryArtifactDigest: inventory.artifactDigest,
|
|
2431
|
-
baselineCommit: baseline.commit, outlineCommit, outlineTree: handoff.outline.tree,
|
|
2432
|
-
outlineBlobOids: Object.fromEntries(targetPaths.map(target => [target, handoff.outline.targetBlobs[target].blobOid])),
|
|
2433
|
-
outlineArtifactDigests: outlineDigests, draftCommit: merge.draftCommit, mergedCommit: finalCommit,
|
|
2434
|
-
draftTree: finalTree, draftBlobOids, draftArtifactDigests, handoffDigest: attempt.handoffDigest,
|
|
2435
|
-
reviewCaptureRef: review.review.ref, reviewCaptureDigest: review.captureDigest,
|
|
2436
|
-
reviewDigest: review.reviewDigest, seamDigest: seamLoadedDigest(seamFile), dispatchInputDigest: seam.dispatchInputDigest,
|
|
2437
|
-
dispatchToolUseId: cap.tool_use_id, coordinatorPrincipal: safeInput.sessionId,
|
|
2438
|
-
reviewerPrincipal: review.reviewerPrincipal, workerPrincipal: worker.agent_id,
|
|
2439
|
-
workerRoot, writerLeaseDigest: seam.writerLeaseDigest,
|
|
2440
|
-
ancestry: 'strict-descendant', mergeCorrespondence: merge.state === 'accepted' && merge.draftCommit === finalCommit ? null : merge,
|
|
2441
|
-
targetPaths,
|
|
2442
|
-
},
|
|
2443
|
-
captured: { captureRef: cap.ref, toolUseId: cap.tool_use_id, seamDigest: seamLoadedDigest(seamFile) },
|
|
2444
|
-
};
|
|
2445
|
-
return { status: 'accepted', originRef, event,
|
|
2446
|
-
correlation: { toolCorrelationId: cap.tool_use_id, resultRef: cap.responseRef } };
|
|
2447
|
-
} catch (error) {
|
|
2448
|
-
return fail(error.message === 'outline-git-unavailable' ? 'outline-git-unavailable' : 'outline-evidence-unresolved', 'unavailable');
|
|
2449
|
-
}
|
|
2450
|
-
}
|
|
2451
|
-
|
|
2452
|
-
function seamLoadedDigest(file) {
|
|
2453
|
-
try { return outlineSha(fs.readFileSync(file)); } catch { return ''; }
|
|
2454
|
-
}
|
|
2455
|
-
|
|
2456
|
-
// ---- Shared provider state ------------------------------------------------------
|
|
2457
|
-
|
|
2458
|
-
function supportedHostCheck(input, expectedHost = HOST_ID) {
|
|
2459
|
-
if ([HOST_ID, OPENCODE_HOST_ID].includes(expectedHost) && recordOf(input) && input.hostId === expectedHost) return null;
|
|
2460
|
-
const host = recordOf(input) && typeof input.hostId === 'string' ? input.hostId : 'unknown';
|
|
2461
|
-
return diagnostic('unsupported-host', {
|
|
2462
|
-
reason: `unsupported host ${host} has no matching capture implementation; hosts must not borrow another host's exit mapping`,
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
|
|
2466
|
-
function contentSignature(cap) {
|
|
2467
|
-
return captureJson({
|
|
2468
|
-
event: cap.event === undefined ? null : cap.event,
|
|
2469
|
-
command: cap.command === undefined ? null : cap.command,
|
|
2470
|
-
cwd: cap.cwd === undefined ? null : cap.cwd,
|
|
2471
|
-
tool_use_id: cap.tool_use_id === undefined ? null : cap.tool_use_id,
|
|
2472
|
-
session_id: cap.session_id === undefined ? null : cap.session_id,
|
|
2473
|
-
agent_id: cap.agent_id === undefined ? null : cap.agent_id,
|
|
2474
|
-
agent_type: cap.agent_type === undefined ? null : cap.agent_type,
|
|
2475
|
-
responseDigest: cap.responseDigest === undefined ? null : cap.responseDigest,
|
|
2476
|
-
reviewDigest: cap.reviewDigest === undefined ? null : cap.reviewDigest,
|
|
2477
|
-
interrupted: typeof cap.interrupted === 'boolean' ? cap.interrupted : null,
|
|
2478
|
-
is_interrupt: typeof cap.is_interrupt === 'boolean' ? cap.is_interrupt : null,
|
|
2479
|
-
failureDisposition: cap.failureDisposition === undefined ? null : cap.failureDisposition,
|
|
2480
|
-
reviewVerdict: cap.reviewVerdict === undefined ? null : cap.reviewVerdict,
|
|
2481
|
-
reviewSummary: cap.reviewSummary === undefined ? null : cap.reviewSummary,
|
|
2482
|
-
});
|
|
2483
|
-
}
|
|
2484
|
-
|
|
2485
|
-
function rejected(code, reason) { return { status: 'rejected', diagnostics: [diagnostic(code, { reason: `${code}: ${reason}` })] }; }
|
|
2486
|
-
function unavailable(code, reason) { return { status: 'unavailable', diagnostics: [diagnostic(code, { reason: `${code}: ${reason}` })] }; }
|
|
2487
|
-
|
|
2488
|
-
const createClaudeOriginProvider = input => {
|
|
2489
|
-
const safeInput = recordOf(input) ? input : {};
|
|
2490
|
-
|
|
2491
|
-
function resolveContext(request) {
|
|
2492
|
-
const hostFail = supportedHostCheck(safeInput);
|
|
2493
|
-
if (hostFail) return { status: 'unavailable', diagnostics: [hostFail] };
|
|
2494
|
-
const qualification = evaluateQualification(safeInput);
|
|
2495
|
-
if (!qualification.open) return { status: 'unavailable', diagnostics: [qualification.fail] };
|
|
2496
|
-
const workspaceRoot = textOf(safeInput.workspaceRoot) ? safeInput.workspaceRoot : (recordOf(request) && textOf(request.workspaceRoot) ? request.workspaceRoot : '');
|
|
2497
|
-
const author = recordOf(safeInput.principals) && textOf(safeInput.principals.author) ? safeInput.principals.author : safeInput.sessionId;
|
|
2498
|
-
const executors = recordOf(safeInput.principals) && Array.isArray(safeInput.principals.executors) ? safeInput.principals.executors.filter(textOf) : [];
|
|
2499
|
-
const originRef = 'origin://claude-code/' + digestText(captureJson({
|
|
2500
|
-
hostId: HOST_ID,
|
|
2501
|
-
sessionId: safeInput.sessionId === undefined ? null : safeInput.sessionId,
|
|
2502
|
-
workspaceRoot,
|
|
2503
|
-
taskId: safeInput.taskId === undefined ? null : safeInput.taskId,
|
|
2504
|
-
workflowId: safeInput.workflowId === undefined ? null : safeInput.workflowId,
|
|
2505
|
-
workflowRevision: safeInput.workflowRevision === undefined ? null : safeInput.workflowRevision,
|
|
2506
|
-
author,
|
|
2507
|
-
executors: executors.slice(),
|
|
2508
|
-
qualificationSource: qualification.source,
|
|
2509
|
-
}));
|
|
2510
|
-
return {
|
|
2511
|
-
status: 'accepted',
|
|
2512
|
-
originRef,
|
|
2513
|
-
context: {
|
|
2514
|
-
workspaceId: 'ws-' + digestText(captureJson({ workspaceRoot })),
|
|
2515
|
-
sessionId: safeInput.sessionId === undefined ? '' : safeInput.sessionId,
|
|
2516
|
-
workflowId: textOf(safeInput.workflowId) ? safeInput.workflowId : '',
|
|
2517
|
-
workflowRevision: Number.isInteger(safeInput.workflowRevision) ? safeInput.workflowRevision : 0,
|
|
2518
|
-
taskId: textOf(safeInput.taskId) ? safeInput.taskId : '',
|
|
2519
|
-
principals: { author, executors: executors.slice() },
|
|
2520
|
-
activeHost: HOST_ID,
|
|
2521
|
-
baselineReference: `retained-live-capture:claude-325-3b-s2b:${digestText(originRef)}`,
|
|
2522
|
-
// The concrete workflow-start pin, when the caller supplies it. It is never inferred from the current state.
|
|
2523
|
-
...(recordOf(safeInput.baseline) && textOf(safeInput.baseline.commit) && textOf(safeInput.baseline.root)
|
|
2524
|
-
? { baseline: { commit: safeInput.baseline.commit, root: safeInput.baseline.root } } : {}),
|
|
2525
|
-
workspaceRoot,
|
|
2526
|
-
},
|
|
2527
|
-
};
|
|
2528
|
-
}
|
|
2529
|
-
|
|
2530
|
-
function resolveEvent(request) {
|
|
2531
|
-
if (!recordOf(request) || !textOf(request.reference)) return unavailable('invalid-input', 'resolveEvent requires a nonempty event reference');
|
|
2532
|
-
const hostFail = supportedHostCheck(safeInput);
|
|
2533
|
-
if (hostFail) return { status: 'unavailable', diagnostics: [hostFail] };
|
|
2534
|
-
const qualification = evaluateQualification(safeInput);
|
|
2535
|
-
if (!qualification.open) return { status: 'unavailable', diagnostics: [qualification.fail] };
|
|
2536
|
-
const { reference } = request;
|
|
2537
|
-
const captures = Array.isArray(safeInput.captures) ? safeInput.captures : [];
|
|
2538
|
-
// A reference is `<captureRef>` (lifecycle events) or `<captureRef>#<capability>` (doc-check projections).
|
|
2539
|
-
const [captureRef, capability] = String(reference).split('#');
|
|
2540
|
-
const index = captures.findIndex(item => recordOf(item) && item.ref === captureRef);
|
|
2541
|
-
if (index === -1) return unavailable('origin-unavailable', `no captured host event is retained for reference ${reference}`);
|
|
2542
|
-
const cap = captures[index];
|
|
2543
|
-
const originRefResponse = resolveContext(request);
|
|
2544
|
-
if (!originRefResponse || originRefResponse.status !== 'accepted' || !textOf(originRefResponse.originRef)) {
|
|
2545
|
-
return unavailable('origin-unavailable', 'origin context did not resolve');
|
|
2546
|
-
}
|
|
2547
|
-
const originRef = originRefResponse.originRef;
|
|
2548
|
-
const author = recordOf(safeInput.principals) && textOf(safeInput.principals.author) ? safeInput.principals.author : safeInput.sessionId;
|
|
2549
|
-
const executors = recordOf(safeInput.principals) && Array.isArray(safeInput.principals.executors) ? safeInput.principals.executors.filter(textOf) : [];
|
|
2550
|
-
// Session binding: a record copied from another session can never belong to
|
|
2551
|
-
// this workflow's assessment.
|
|
2552
|
-
if (cap.session_id === undefined || cap.session_id !== safeInput.sessionId) {
|
|
2553
|
-
return rejected('record-origin-mismatch', `captured record session_id must equal the provider session to belong to this invocation (owner row: copied records from another session are rejected)`);
|
|
2554
|
-
}
|
|
2555
|
-
// Observation-time identity (I2c): a record captured under another workflow, revision or baseline pin is stale.
|
|
2556
|
-
if (cap.observedIdentity !== undefined && cap.observedIdentity !== null) {
|
|
2557
|
-
const observed = cap.observedIdentity;
|
|
2558
|
-
const pin = recordOf(safeInput.baseline) ? safeInput.baseline : null;
|
|
2559
|
-
const sameWorkflow = observed.workflowId === safeInput.workflowId && observed.workflowRevision === safeInput.workflowRevision;
|
|
2560
|
-
const samePin = !pin || (recordOf(observed.baselinePin) && observed.baselinePin.commit === pin.commit
|
|
2561
|
-
&& samePathKey(observed.baselinePin.root, pin.root));
|
|
2562
|
-
if (!sameWorkflow || !samePin) {
|
|
2563
|
-
return rejected('identity-mismatch', 'the observed workflow revision or baseline pin differs from the current one; stale evidence loses credit');
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
if (capability && !(recordOf(cap.observedIdentity))) {
|
|
2567
|
-
return rejected('identity-missing', 'a doc capability needs the workflow identity observed at capture time');
|
|
2568
|
-
}
|
|
2569
|
-
if (capability === 'outline-confirmation') {
|
|
2570
|
-
const outlineQualification = validateOutlineCaptureQualification(safeInput);
|
|
2571
|
-
if (!outlineQualification.open) {
|
|
2572
|
-
return unavailable('outline-live-gate-unmet', `positive outline credit is disabled until retained Claude prompt, coordinator, synchronous-boundary and worker-root capture is qualified (${outlineQualification.reason})`);
|
|
2573
|
-
}
|
|
2574
|
-
return resolveOutlineEvidence({ safeInput, capture: cap, captures, request, originRef });
|
|
2575
|
-
}
|
|
2576
|
-
// Replay: identical host-event content re-presented under a new reference
|
|
2577
|
-
// cannot become a new accepted event. The first recorded occurrence wins.
|
|
2578
|
-
const signature = contentSignature(cap);
|
|
2579
|
-
const firstOccurrence = captures.findIndex(item => recordOf(item) && contentSignature(item) === signature);
|
|
2580
|
-
if (firstOccurrence !== index) {
|
|
2581
|
-
return rejected('replayed-record', `identical host-event content already recorded (first occurrence index ${firstOccurrence}); a copied record cannot become a new accepted event by changing its reference`);
|
|
2582
|
-
}
|
|
2583
|
-
const producerId = 'claude-code-origin-provider';
|
|
2584
|
-
// Only true doc capabilities reach the doc-check branch; quality-review is the SubagentStop review branch below.
|
|
2585
|
-
if (capability && capability !== 'quality-review') {
|
|
2586
|
-
// Doc capability: only a registered, passed, fully covered doc-check invocation with retained stdout can cover it.
|
|
2587
|
-
if (cap.event !== 'PostToolUse') return rejected('capability-mismatch', 'only a PostToolUse check invocation can cover a doc capability');
|
|
2588
|
-
const registered = resolveDocCheckInvocation(cap.command, cap.cwd);
|
|
2589
|
-
if (registered.kind === 'not-candidate') return rejected('unregistered-command', 'the command is not a registered doc-check invocation; an arbitrary successful shell command never covers a doc capability');
|
|
2590
|
-
if (capability === 'conflict-check' && registered.conflictAssessment !== true) {
|
|
2591
|
-
return rejected('capability-mismatch', 'conflict-check requires the structurally parsed --conflict-assessment mode');
|
|
2592
|
-
}
|
|
2593
|
-
if (registered.kind === 'rejected' && registered.reason !== 'implementation-pin-mismatch') {
|
|
2594
|
-
if (registered.reason === 'implementation-not-installed') return rejected('implementation-not-installed', 'the registered check does not resolve to this install\'s own doc-check runtime; a different path earns no credit');
|
|
2595
|
-
return rejected('unregistered-command', `doc-check invocation rejected (${registered.reason}); no credit`);
|
|
2596
|
-
}
|
|
2597
|
-
if (cap.implementationDigest !== fileDigest(registered.installed)) return rejected('implementation-digest-mismatch', 'the installed doc-check digest differs from the one observed at capture; no credit');
|
|
2598
|
-
if (registered.kind === 'rejected') return rejected('implementation-pin-mismatch', 'the installed doc-check is not the shipped script (canonical digest differs from SHIPPED_DOC_CHECK_DIGEST); no credit');
|
|
2599
|
-
if (!(cap.tool_use_id && typeof cap.tool_use_id === 'string')) return rejected('tool-use-id-missing', 'absent or empty tool_use_id: the invocation cannot be correlated, no credit');
|
|
2600
|
-
if (typeof cap.interrupted !== 'boolean') return rejected('outcome-ambiguous', 'ambiguous interruption/success correlation cannot be treated as success');
|
|
2601
|
-
if (cap.interrupted === true) return rejected('interrupted-not-credited', 'interrupted success is not mapped to exit 0 (owner decision row 1)');
|
|
2602
|
-
if (captures.some((item, i) => recordOf(item) && i !== index && item.event === 'PostToolUseFailure'
|
|
2603
|
-
&& item.tool_use_id === cap.tool_use_id && item.session_id === cap.session_id)) {
|
|
2604
|
-
return rejected('failure-invalidates-mapping', 'a PostToolUseFailure arrived for the same tool_use_id; the success mapping is voided');
|
|
2605
|
-
}
|
|
2606
|
-
if (typeof cap.stdout !== 'string') return rejected('stdout-withheld', 'retained stdout is absent or over the cap; the event is withheld and never credited');
|
|
2607
|
-
if (crypto.createHash('sha256').update(cap.stdout).digest('hex') !== cap.stdoutDigest) return rejected('stdout-digest-mismatch', 'retained stdout does not match its digest');
|
|
2608
|
-
// The raw host result must still be the one observed: its canonical digest and stdout must match the record.
|
|
2609
|
-
if (!recordOf(cap.toolResponse) || captureDigest(cap.toolResponse) !== cap.responseDigest || cap.toolResponse.stdout !== cap.stdout) {
|
|
2610
|
-
return rejected('payload-edited', 'the retained raw tool response does not match the recorded responseDigest; an edited payload is never credited');
|
|
2611
|
-
}
|
|
2612
|
-
let report;
|
|
2613
|
-
try { report = JSON.parse(cap.stdout); } catch { return rejected('stdout-not-json', 'retained stdout is not a JSON check report'); }
|
|
2614
|
-
if (!recordOf(report) || report.schema !== DOC_CHECK_SCHEMA || !recordOf(report.lint) || report.lint.exit !== 0) {
|
|
2615
|
-
return rejected('check-not-passed', 'the registered check did not pass lint; no capability is credited');
|
|
2616
|
-
}
|
|
2617
|
-
const projection = recordOf(report.capabilities) ? report.capabilities[capability] : undefined;
|
|
2618
|
-
if (!recordOf(projection) || projection.state !== 'pass') {
|
|
2619
|
-
return rejected('partial-coverage', `${capability} is ${projection ? projection.state : 'absent'}; partial coverage earns no credit`);
|
|
2620
|
-
}
|
|
2621
|
-
const paths = Array.isArray(projection.checkedPaths) ? projection.checkedPaths.slice() : [];
|
|
2622
|
-
if (!paths.length) return rejected('scope-empty', `${capability} checked no governed paths`);
|
|
2623
|
-
let corpusBinding;
|
|
2624
|
-
let baselineArtifactDigests;
|
|
2625
|
-
let derivedBinding;
|
|
2626
|
-
if (capability === 'derived-regenerate') {
|
|
2627
|
-
if (!registered.derivedView || paths.length !== 1 || paths[0] !== registered.derivedView) {
|
|
2628
|
-
return rejected('capability-mismatch', 'derived-regenerate requires the exact registered --derived-view path');
|
|
2629
|
-
}
|
|
2630
|
-
const binding = projection.binding;
|
|
2631
|
-
const corpus = binding && binding.sourceCorpus;
|
|
2632
|
-
const config = binding && binding.config;
|
|
2633
|
-
const generator = binding && binding.generator;
|
|
2634
|
-
const generation = binding && binding.generation;
|
|
2635
|
-
const comparison = binding && binding.comparison;
|
|
2636
|
-
if (!recordOf(binding) || binding.view !== registered.derivedView || !recordOf(corpus) || corpus.complete !== true
|
|
2637
|
-
|| !Array.isArray(corpus.paths) || !corpus.paths.length || !recordOf(corpus.digests)
|
|
2638
|
-
|| JSON.stringify([...new Set(corpus.paths)].sort(compareKeys)) !== JSON.stringify(corpus.paths)
|
|
2639
|
-
|| JSON.stringify(Object.keys(corpus.digests).sort(compareKeys)) !== JSON.stringify(corpus.paths)
|
|
2640
|
-
|| corpus.paths.some(relative => !textOf(relative) || path.isAbsolute(relative) || relative.split(/[\\/]/).includes('..')
|
|
2641
|
-
|| !HEX64.test(String(corpus.digests[relative] || '')))
|
|
2642
|
-
|| !recordOf(config) || !textOf(config.path) || path.isAbsolute(config.path)
|
|
2643
|
-
|| config.path.split(/[\\/]/).includes('..') || !HEX64.test(String(config.digest || ''))
|
|
2644
|
-
|| !Array.isArray(config.sources) || !recordOf(generator) || !textOf(generator.path)
|
|
2645
|
-
|| !HEX64.test(String(generator.digest || '')) || !recordOf(generation) || generation.state !== 'pass'
|
|
2646
|
-
|| !HEX64.test(String(generation.outputDigest || '')) || !recordOf(comparison) || comparison.state !== 'equal'
|
|
2647
|
-
|| comparison.targetDigest !== generation.outputDigest) {
|
|
2648
|
-
return rejected('derived-binding-invalid', 'derived-regenerate stdout lacks complete generation, comparison, and input binding');
|
|
2649
|
-
}
|
|
2650
|
-
const configPath = path.resolve(cap.cwd, registered.config);
|
|
2651
|
-
const configRelative = path.relative(path.resolve(cap.cwd), configPath).split(path.sep).join('/');
|
|
2652
|
-
const observedDerived = recordOf(cap.observedDerivedDigests) ? cap.observedDerivedDigests : {};
|
|
2653
|
-
if (configRelative !== config.path || observedDerived[config.path] !== config.digest
|
|
2654
|
-
|| observedDerived[registered.derivedView] !== comparison.targetDigest) {
|
|
2655
|
-
return rejected('derived-input-changed-after-check', 'the selected config or derived target changed before host capture');
|
|
2656
|
-
}
|
|
2657
|
-
const expectedObservedPaths = [...new Set([...corpus.paths, config.path, registered.derivedView])].sort(compareKeys);
|
|
2658
|
-
if (JSON.stringify(Object.keys(observedDerived).sort(compareKeys)) !== JSON.stringify(expectedObservedPaths)
|
|
2659
|
-
|| corpus.paths.some(relative => observedDerived[relative] !== corpus.digests[relative])) {
|
|
2660
|
-
return rejected('derived-input-changed-after-check', 'a source path is missing or changed before host capture');
|
|
2661
|
-
}
|
|
2662
|
-
const configSources = config.sources;
|
|
2663
|
-
if (JSON.stringify(configSources.map(item => item && item.path)) !== JSON.stringify([...new Set(configSources.map(item => item && item.path))].sort(compareKeys))
|
|
2664
|
-
|| configSources.some(item => !recordOf(item) || !textOf(item.path) || path.isAbsolute(item.path)
|
|
2665
|
-
|| item.path.split(/[\\/]/).includes('..') || !['present', 'missing'].includes(item.presence)
|
|
2666
|
-
|| (item.presence === 'present' ? !HEX64.test(String(item.digest || '')) : item.digest !== undefined))) {
|
|
2667
|
-
return rejected('derived-config-binding-invalid', 'derived-regenerate config source inventory is malformed');
|
|
2668
|
-
}
|
|
2669
|
-
const observedConfigSources = cap.observedDerivedConfigSources;
|
|
2670
|
-
if (!Array.isArray(observedConfigSources) || JSON.stringify(observedConfigSources) !== JSON.stringify(configSources)) {
|
|
2671
|
-
return rejected('config-changed-after-check', 'a config source changed between check and host capture');
|
|
2672
|
-
}
|
|
2673
|
-
const configSource = configSources.find(item => item.path === config.path);
|
|
2674
|
-
if (!configSource || configSource.presence !== 'present' || configSource.digest !== config.digest) {
|
|
2675
|
-
return rejected('derived-config-binding-invalid', 'the selected config is absent from the observed config inventory');
|
|
2676
|
-
}
|
|
2677
|
-
let configData;
|
|
2678
|
-
try { configData = JSON.parse(fs.readFileSync(configPath, 'utf8')); }
|
|
2679
|
-
catch { return rejected('derived-config-binding-invalid', 'the selected config cannot be read during assessment'); }
|
|
2680
|
-
const selectedViews = Array.isArray(configData.derived) ? configData.derived.filter(item => item && item.path === registered.derivedView) : [];
|
|
2681
|
-
const expectedGenerator = `node harness-everything/scripts/doc-lifecycle.js index --workspace . --config ${registered.config} --all`;
|
|
2682
|
-
if (selectedViews.length !== 1 || selectedViews[0].generator !== expectedGenerator) {
|
|
2683
|
-
return rejected('derived-generator-unsupported', 'the selected config does not declare the supported lifecycle index operation');
|
|
2684
|
-
}
|
|
2685
|
-
let generatorPath;
|
|
2686
|
-
try { generatorPath = fs.realpathSync(path.join(path.dirname(registered.installed), 'doc-lifecycle.js')); }
|
|
2687
|
-
catch { return rejected('derived-generator-unavailable', 'the installed lifecycle index generator is missing'); }
|
|
2688
|
-
if (generator.path !== generatorPath || fileDigest(generatorPath) !== generator.digest) {
|
|
2689
|
-
return rejected('derived-generator-mismatch', 'the lifecycle generator differs from the implementation observed in stdout');
|
|
2690
|
-
}
|
|
2691
|
-
let currentConfigSources;
|
|
2692
|
-
try {
|
|
2693
|
-
const lifecycle = require(generatorPath);
|
|
2694
|
-
currentConfigSources = lifecycle.configSourceInventory(cap.cwd, configPath);
|
|
2695
|
-
} catch { return rejected('derived-config-binding-invalid', 'the lifecycle config inventory is unavailable'); }
|
|
2696
|
-
if (!currentConfigSources || currentConfigSources.complete !== true
|
|
2697
|
-
|| JSON.stringify(currentConfigSources.sources) !== JSON.stringify(configSources)) {
|
|
2698
|
-
return rejected('config-changed-after-check', 'the lifecycle config source inventory changed after the check');
|
|
2699
|
-
}
|
|
2700
|
-
if (!recordOf(request.identity) || !HEX64.test(String(request.identity.baselineDigest || ''))
|
|
2701
|
-
|| !HEX64.test(String(request.identity.candidateDigest || '')) || !HEX64.test(String(request.identity.configDigest || ''))) {
|
|
2702
|
-
return rejected('identity-missing', 'derived-regenerate needs the complete snapshot identity');
|
|
2703
|
-
}
|
|
2704
|
-
derivedBinding = {
|
|
2705
|
-
...binding,
|
|
2706
|
-
baselineDigest: request.identity.baselineDigest,
|
|
2707
|
-
candidateDigest: request.identity.candidateDigest,
|
|
2708
|
-
configIdentityDigest: request.identity.configDigest,
|
|
2709
|
-
};
|
|
2710
|
-
}
|
|
2711
|
-
if (capability === 'conflict-check') {
|
|
2712
|
-
const assessment = report.conflictAssessment;
|
|
2713
|
-
const corpus = assessment && assessment.corpus;
|
|
2714
|
-
const config = corpus && corpus.config;
|
|
2715
|
-
if (registered.conflictAssessment !== true || report.mode !== 'conflict-assessment'
|
|
2716
|
-
|| assessment?.schema !== DOC_CHECK_CONFLICT_SCHEMA || assessment.state !== 'pass'
|
|
2717
|
-
|| projection.corpus?.complete !== true || corpus?.complete !== true
|
|
2718
|
-
|| !Array.isArray(corpus.paths) || !corpus.paths.length || !recordOf(corpus.digests)
|
|
2719
|
-
|| !recordOf(config) || !textOf(config.path) || path.isAbsolute(config.path)
|
|
2720
|
-
|| config.path.split(/[\\/]/).includes('..') || !HEX64.test(String(config.digest || ''))
|
|
2721
|
-
|| !/^[0-9a-f]{40,64}$/.test(String(corpus.baseCommit || ''))
|
|
2722
|
-
|| JSON.stringify([...new Set(corpus.paths)].sort(compareKeys)) !== JSON.stringify(corpus.paths)
|
|
2723
|
-
|| JSON.stringify(Object.keys(corpus.digests).sort(compareKeys)) !== JSON.stringify(corpus.paths)
|
|
2724
|
-
|| corpus.paths.some(relative => !textOf(relative) || path.isAbsolute(relative)
|
|
2725
|
-
|| relative.split(/[\\/]/).includes('..') || !HEX64.test(String(corpus.digests[relative] || '')))) {
|
|
2726
|
-
return rejected('corpus-binding-invalid', 'conflict-check stdout does not carry a complete, structured full-corpus assessment');
|
|
2727
|
-
}
|
|
2728
|
-
const observedCorpus = recordOf(cap.observedCorpusDigests) ? cap.observedCorpusDigests : {};
|
|
2729
|
-
if (corpus.paths.some(relative => observedCorpus[relative] !== corpus.digests[relative])) {
|
|
2730
|
-
return rejected('corpus-changed-after-check', 'a full-corpus path is missing or changed between assessment and capture');
|
|
2731
|
-
}
|
|
2732
|
-
if (cap.observedConfigDigest !== config.digest) {
|
|
2733
|
-
return rejected('config-changed-after-check', 'the project-docs config changed between assessment and capture');
|
|
2734
|
-
}
|
|
2735
|
-
if (!recordOf(request.identity) || !HEX64.test(String(request.identity.baselineDigest || ''))
|
|
2736
|
-
|| !HEX64.test(String(request.identity.candidateDigest || '')) || !HEX64.test(String(request.identity.configDigest || ''))) {
|
|
2737
|
-
return rejected('identity-missing', 'conflict-check needs the complete snapshot identity');
|
|
2738
|
-
}
|
|
2739
|
-
corpusBinding = {
|
|
2740
|
-
complete: true,
|
|
2741
|
-
paths: corpus.paths.slice(),
|
|
2742
|
-
digests: { ...corpus.digests },
|
|
2743
|
-
config: { ...config },
|
|
2744
|
-
baseCommit: corpus.baseCommit,
|
|
2745
|
-
baselineDigest: request.identity.baselineDigest,
|
|
2746
|
-
candidateDigest: request.identity.candidateDigest,
|
|
2747
|
-
configIdentityDigest: request.identity.configDigest,
|
|
2748
|
-
};
|
|
2749
|
-
baselineArtifactDigests = recordOf(assessment.baselineArtifacts) ? assessment.baselineArtifacts : {};
|
|
2750
|
-
}
|
|
2751
|
-
const observed = recordOf(cap.observedDigests) ? cap.observedDigests : {};
|
|
2752
|
-
const artifactDigests = {};
|
|
2753
|
-
const baselineArtifacts = {};
|
|
2754
|
-
for (const relative of paths) {
|
|
2755
|
-
if (typeof observed[relative] === 'string') artifactDigests[relative] = observed[relative];
|
|
2756
|
-
else if (capability === 'conflict-check' && HEX64.test(String(baselineArtifactDigests[relative] || ''))) baselineArtifacts[relative] = baselineArtifactDigests[relative];
|
|
2757
|
-
else return rejected('artifact-unobserved', `no observation-time digest for ${relative}`);
|
|
2758
|
-
}
|
|
2759
|
-
const argv = ['node', ...registered.argv];
|
|
2760
|
-
const command = argv.join(' ');
|
|
2761
|
-
const event = {
|
|
2762
|
-
eventId: 'claude-check-' + digestText(cap.captureId + ':' + capability),
|
|
2763
|
-
producerId,
|
|
2764
|
-
originRef,
|
|
2765
|
-
principalId: cap.session_id,
|
|
2766
|
-
provenance: 'claude-code-capture:' + cap.captureId,
|
|
2767
|
-
capability,
|
|
2768
|
-
kind: 'execution',
|
|
2769
|
-
command,
|
|
2770
|
-
argv,
|
|
2771
|
-
cwd: typeof cap.cwd === 'string' ? cap.cwd : '',
|
|
2772
|
-
exitCode: 0,
|
|
2773
|
-
signal: null,
|
|
2774
|
-
toolCorrelationId: cap.tool_use_id,
|
|
2775
|
-
resultRef: cap.responseRef,
|
|
2776
|
-
identity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2777
|
-
startIdentity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2778
|
-
endIdentity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2779
|
-
paths,
|
|
2780
|
-
artifactDigests,
|
|
2781
|
-
...(Object.keys(baselineArtifacts).length ? { baselineArtifacts } : {}),
|
|
2782
|
-
...(corpusBinding ? { corpusBinding } : {}),
|
|
2783
|
-
...(derivedBinding ? { derivedBinding } : {}),
|
|
2784
|
-
captured: { responseRef: cap.responseRef, responseDigest: cap.responseDigest },
|
|
2785
|
-
};
|
|
2786
|
-
return { status: 'accepted', originRef, event, correlation: { toolCorrelationId: cap.tool_use_id, resultRef: cap.responseRef } };
|
|
2787
|
-
}
|
|
2788
|
-
// A quality-review reference must name a SubagentStop review; it never falls through to the lifecycle branches below.
|
|
2789
|
-
if (capability === 'quality-review' && cap.event !== 'SubagentStop') {
|
|
2790
|
-
return rejected('capability-mismatch', 'quality-review is credited only from a SubagentStop review');
|
|
2791
|
-
}
|
|
2792
|
-
if (cap.event === 'PostToolUseFailure') {
|
|
2793
|
-
return rejected('failure-not-credited', 'PostToolUseFailure is never credited; its Exit code N text is diagnostics-only (owner decision row 1)');
|
|
2794
|
-
}
|
|
2795
|
-
if (cap.event === 'SubagentStart') {
|
|
2796
|
-
return rejected('capture-not-completed', 'SubagentStart records only a launch; a background launch is not a completed review or execution');
|
|
2797
|
-
}
|
|
2798
|
-
if (cap.event === 'PreToolUse') {
|
|
2799
|
-
return rejected('capture-not-completed', 'PreToolUse records only a launch; without a completed outcome it cannot be credited');
|
|
2800
|
-
}
|
|
2801
|
-
if (cap.event === 'PostToolUse') {
|
|
2802
|
-
if (!(cap.tool_use_id && typeof cap.tool_use_id === 'string')) {
|
|
2803
|
-
return rejected('tool-use-id-missing', 'absent or empty tool_use_id: the invocation cannot be correlated, no credit');
|
|
2804
|
-
}
|
|
2805
|
-
if (typeof cap.interrupted !== 'boolean') {
|
|
2806
|
-
return rejected('outcome-ambiguous', 'ambiguous interruption/success correlation cannot be treated as success');
|
|
2807
|
-
}
|
|
2808
|
-
if (cap.interrupted === true) {
|
|
2809
|
-
return rejected('interrupted-not-credited', 'interrupted success is not mapped to exit 0 (owner decision row 1)');
|
|
2810
|
-
}
|
|
2811
|
-
if (!textOf(cap.command) && typeof cap.command !== 'string') {
|
|
2812
|
-
return rejected('command-missing', 'captured record without a retained command cannot be credited');
|
|
2813
|
-
}
|
|
2814
|
-
const failureForInvocation = captures.some((item, i) => recordOf(item) && i !== index
|
|
2815
|
-
&& item.event === 'PostToolUseFailure' && item.tool_use_id === cap.tool_use_id && item.session_id === cap.session_id);
|
|
2816
|
-
if (failureForInvocation) {
|
|
2817
|
-
return rejected('failure-invalidates-mapping', 'a PostToolUseFailure arrived for the same tool_use_id; the success mapping is voided (owner decision row 1)');
|
|
2818
|
-
}
|
|
2819
|
-
const eventId = 'claude-exit-map-' + digestText(signature + ':execution');
|
|
2820
|
-
const event = {
|
|
2821
|
-
eventId,
|
|
2822
|
-
producerId,
|
|
2823
|
-
originRef,
|
|
2824
|
-
principalId: cap.session_id,
|
|
2825
|
-
capability: 'shell-command',
|
|
2826
|
-
kind: 'execution',
|
|
2827
|
-
command: cap.command,
|
|
2828
|
-
argv: [cap.command],
|
|
2829
|
-
cwd: cap.cwd === undefined ? '' : cap.cwd,
|
|
2830
|
-
exitCode: 0,
|
|
2831
|
-
signal: null,
|
|
2832
|
-
toolCorrelationId: cap.tool_use_id,
|
|
2833
|
-
resultRef: cap.responseRef,
|
|
2834
|
-
identity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2835
|
-
startIdentity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2836
|
-
endIdentity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2837
|
-
paths: [],
|
|
2838
|
-
artifactDigests: {},
|
|
2839
|
-
captured: { responseRef: cap.responseRef, responseDigest: cap.responseDigest },
|
|
2840
|
-
};
|
|
2841
|
-
return { status: 'accepted', originRef, event, correlation: { toolCorrelationId: cap.tool_use_id, resultRef: cap.responseRef } };
|
|
2842
|
-
}
|
|
2843
|
-
if (cap.event === 'SubagentStop') {
|
|
2844
|
-
const reviewer = cap.agent_id;
|
|
2845
|
-
if (!textOf(reviewer)) {
|
|
2846
|
-
return rejected('reviewer-principal-missing', 'SubagentStop without a host-issued agent_id cannot establish a reviewer principal; a caller-supplied name or review prose is not an agent identity');
|
|
2847
|
-
}
|
|
2848
|
-
// Executors: the configured principals plus every session and agent that ran a captured tool in this task (F4).
|
|
2849
|
-
const reviewerExecutors = [...new Set([...executors, ...journalExecutors(captures, author)])];
|
|
2850
|
-
if (reviewer === author) {
|
|
2851
|
-
return rejected('reviewer-not-independent', 'the reviewer agent_id equals the author session principal; not independent');
|
|
2852
|
-
}
|
|
2853
|
-
if (reviewerExecutors.includes(reviewer)) {
|
|
2854
|
-
return rejected('reviewer-not-independent', 'the reviewer agent_id equals an executor principal; not independent');
|
|
2855
|
-
}
|
|
2856
|
-
// An approval needs its own correlated Agent/Task result surface, never a bare SubagentStop (F5).
|
|
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
|
-
}
|
|
2868
|
-
}
|
|
2869
|
-
if (!HEX64.test(String(cap.reviewDigest === undefined ? '' : cap.reviewDigest))) {
|
|
2870
|
-
return rejected('review-digest-missing', 'SubagentStop without a bound final review artifact digest cannot close a review');
|
|
2871
|
-
}
|
|
2872
|
-
// Approval only from an explicit structured verdict in the bound final artifact. SubagentStop alone never approves.
|
|
2873
|
-
if (cap.reviewVerdict === 'reject') {
|
|
2874
|
-
return rejected('review-not-approved', 'the final review artifact states reject; a reject never approves');
|
|
2875
|
-
}
|
|
2876
|
-
if (cap.reviewVerdict !== 'approve') {
|
|
2877
|
-
return rejected('review-verdict-missing', 'the final review artifact has no explicit structured verdict; SubagentStop alone is never approval');
|
|
2878
|
-
}
|
|
2879
|
-
if (!textOf(cap.reviewSummary)) {
|
|
2880
|
-
return rejected('review-summary-missing', 'an approve verdict needs a non-empty summary');
|
|
2881
|
-
}
|
|
2882
|
-
// The reviewed paths and their digests come from the explicit verdict, never from the caller (F6).
|
|
2883
|
-
if (!reviewedDigestsValid(cap.reviewedArtifactDigests)) {
|
|
2884
|
-
return rejected('reviewed-artifacts-missing', 'an approve verdict must name each reviewed path with its sha256 (Reviewed artifact lines); without them the review cannot bind the candidate');
|
|
2885
|
-
}
|
|
2886
|
-
const eventId = 'claude-review-' + digestText(signature + ':review');
|
|
2887
|
-
const independentOf = [];
|
|
2888
|
-
for (const candidate of [author, ...reviewerExecutors]) {
|
|
2889
|
-
if (textOf(candidate) && candidate !== reviewer && !independentOf.includes(candidate)) independentOf.push(candidate);
|
|
2890
|
-
}
|
|
2891
|
-
const event = {
|
|
2892
|
-
eventId,
|
|
2893
|
-
producerId,
|
|
2894
|
-
originRef,
|
|
2895
|
-
principalId: reviewer,
|
|
2896
|
-
provenance: 'claude-code-capture:' + cap.captureId,
|
|
2897
|
-
capability: 'quality-review',
|
|
2898
|
-
kind: 'review',
|
|
2899
|
-
verdict: 'approve',
|
|
2900
|
-
summary: cap.reviewSummary,
|
|
2901
|
-
independentOf,
|
|
2902
|
-
identity: recordOf(request.identity) ? JSON.parse(JSON.stringify(request.identity)) : null,
|
|
2903
|
-
paths: Object.keys(cap.reviewedArtifactDigests).sort(compareKeys),
|
|
2904
|
-
reviewedArtifactDigests: { ...cap.reviewedArtifactDigests },
|
|
2905
|
-
captured: {
|
|
2906
|
-
responseRef: cap.responseRef,
|
|
2907
|
-
responseDigest: cap.responseDigest,
|
|
2908
|
-
reviewDigest: cap.reviewDigest,
|
|
2909
|
-
agentId: reviewer,
|
|
2910
|
-
agentType: cap.agent_type === undefined ? null : cap.agent_type,
|
|
2911
|
-
},
|
|
2912
|
-
};
|
|
2913
|
-
return { status: 'accepted', originRef, event, correlation: { toolCorrelationId: cap.agent_id, resultRef: cap.responseRef } };
|
|
2914
|
-
}
|
|
2915
|
-
return rejected('capture-event-unsupported', `event ${String(cap.event)} is outside the retained capture vocabulary`);
|
|
2916
|
-
}
|
|
2917
|
-
|
|
2918
|
-
return { resolveContext, resolveEvent };
|
|
2919
|
-
};
|
|
2920
|
-
|
|
2921
|
-
function opencodeContentSignature(cap) {
|
|
2922
|
-
return captureJson({
|
|
2923
|
-
hostId: cap.hostId,
|
|
2924
|
-
tool: cap.tool === undefined ? null : cap.tool,
|
|
2925
|
-
command: cap.command === undefined ? null : cap.command,
|
|
2926
|
-
cwd: cap.cwd === undefined ? null : cap.cwd,
|
|
2927
|
-
status: cap.status === undefined ? null : cap.status,
|
|
2928
|
-
exit: cap.exit === undefined ? null : cap.exit,
|
|
2929
|
-
resultDigest: cap.result_digest === undefined ? null : cap.result_digest,
|
|
2930
|
-
error: cap.error === undefined ? null : cap.error,
|
|
2931
|
-
});
|
|
2932
|
-
}
|
|
2933
|
-
|
|
2934
|
-
const createOpencodeOriginProvider = input => {
|
|
2935
|
-
const safeInput = recordOf(input) ? input : {};
|
|
2936
|
-
|
|
2937
|
-
function resolveContext(request) {
|
|
2938
|
-
const hostFail = supportedHostCheck(safeInput, OPENCODE_HOST_ID);
|
|
2939
|
-
if (hostFail) return { status: 'unavailable', diagnostics: [hostFail] };
|
|
2940
|
-
const qualification = evaluateQualification(safeInput, OPENCODE_HOST_ID);
|
|
2941
|
-
if (!qualification.open) return { status: 'unavailable', diagnostics: [qualification.fail] };
|
|
2942
|
-
const workspaceRoot = textOf(safeInput.workspaceRoot) ? safeInput.workspaceRoot : (recordOf(request) && textOf(request.workspaceRoot) ? request.workspaceRoot : '');
|
|
2943
|
-
const sessionId = textOf(safeInput.sessionId) ? safeInput.sessionId : '';
|
|
2944
|
-
const workflowId = textOf(safeInput.workflowId) ? safeInput.workflowId : '';
|
|
2945
|
-
const workflowRevision = Number.isInteger(safeInput.workflowRevision) ? safeInput.workflowRevision : null;
|
|
2946
|
-
const taskId = textOf(safeInput.taskId) ? safeInput.taskId : '';
|
|
2947
|
-
if (!workspaceRoot || !sessionId || !workflowId || workflowRevision === null || !taskId) {
|
|
2948
|
-
return { status: 'unavailable', diagnostics: [diagnostic('invalid-input', { reason: 'OpenCode origin requires the recorded workspace, session, workflow, revision and task identity' })] };
|
|
2949
|
-
}
|
|
2950
|
-
const suppliedPrincipals = recordOf(safeInput.principals) ? safeInput.principals : {};
|
|
2951
|
-
const author = textOf(suppliedPrincipals.author) ? suppliedPrincipals.author : sessionId;
|
|
2952
|
-
const executors = Array.isArray(suppliedPrincipals.executors) ? suppliedPrincipals.executors.filter(textOf) : [sessionId];
|
|
2953
|
-
const originRef = 'origin://opencode/' + digestText(captureJson({
|
|
2954
|
-
hostId: OPENCODE_HOST_ID, sessionId, workspaceRoot, taskId, workflowId, workflowRevision,
|
|
2955
|
-
author, executors, qualificationSource: qualification.source,
|
|
2956
|
-
}));
|
|
2957
|
-
return {
|
|
2958
|
-
status: 'accepted', originRef,
|
|
2959
|
-
context: {
|
|
2960
|
-
workspaceId: 'ws-' + digestText(captureJson({ workspaceRoot })), sessionId, workflowId, workflowRevision, taskId,
|
|
2961
|
-
principals: { author, executors: executors.slice() }, activeHost: OPENCODE_HOST_ID,
|
|
2962
|
-
baselineReference: `retained-live-capture:opencode-341:${digestText(originRef)}`,
|
|
2963
|
-
...(recordOf(safeInput.baseline) && textOf(safeInput.baseline.commit) && textOf(safeInput.baseline.root)
|
|
2964
|
-
? { baseline: { commit: safeInput.baseline.commit, root: safeInput.baseline.root } } : {}),
|
|
2965
|
-
workspaceRoot,
|
|
2966
|
-
},
|
|
2967
|
-
};
|
|
2968
|
-
}
|
|
2969
|
-
|
|
2970
|
-
function resolveEvent(request) {
|
|
2971
|
-
if (!recordOf(request) || !textOf(request.reference)) return unavailable('invalid-input', 'resolveEvent requires a nonempty event reference');
|
|
2972
|
-
const hostFail = supportedHostCheck(safeInput, OPENCODE_HOST_ID);
|
|
2973
|
-
if (hostFail) return { status: 'unavailable', diagnostics: [hostFail] };
|
|
2974
|
-
const qualification = evaluateQualification(safeInput, OPENCODE_HOST_ID);
|
|
2975
|
-
if (!qualification.open) return { status: 'unavailable', diagnostics: [qualification.fail] };
|
|
2976
|
-
const [captureRef, capability] = String(request.reference).split('#');
|
|
2977
|
-
const captures = Array.isArray(safeInput.captures) ? safeInput.captures : [];
|
|
2978
|
-
const matches = captures.map((item, index) => ({ item, index })).filter(({ item }) => recordOf(item) && item.call_id === captureRef);
|
|
2979
|
-
if (!matches.length) return unavailable('origin-unavailable', `no captured OpenCode event is retained for reference ${request.reference}`);
|
|
2980
|
-
if (matches.length > 1) return rejected('replayed-record', 'multiple OpenCode records share this call id');
|
|
2981
|
-
const { item: cap, index } = matches[0];
|
|
2982
|
-
if (cap.hostId !== OPENCODE_HOST_ID || cap.schema !== OPENCODE_CAPTURE_RECORD_VERSION
|
|
2983
|
-
|| cap.session_id !== safeInput.sessionId) {
|
|
2984
|
-
return rejected('record-origin-mismatch', 'the capture host and session must match this OpenCode provider invocation');
|
|
2985
|
-
}
|
|
2986
|
-
const observed = cap.observedIdentity;
|
|
2987
|
-
const pin = recordOf(safeInput.baseline) ? safeInput.baseline : null;
|
|
2988
|
-
if (!recordOf(observed)) return rejected('identity-missing', 'OpenCode capture lacks workflow identity observed at capture time');
|
|
2989
|
-
const sameWorkflow = observed.workflowId === safeInput.workflowId && observed.workflowRevision === safeInput.workflowRevision;
|
|
2990
|
-
const samePin = !pin || (recordOf(observed.baselinePin) && observed.baselinePin.commit === pin.commit
|
|
2991
|
-
&& samePathKey(observed.baselinePin.root, pin.root));
|
|
2992
|
-
if (!sameWorkflow || !samePin) return rejected('identity-mismatch', 'the observed workflow revision or baseline pin differs from the current one; stale evidence loses credit');
|
|
2993
|
-
const signature = opencodeContentSignature(cap);
|
|
2994
|
-
const firstOccurrence = captures.findIndex(item => recordOf(item) && opencodeContentSignature(item) === signature);
|
|
2995
|
-
if (firstOccurrence !== index) return rejected('replayed-record', `identical OpenCode tool content already recorded (first occurrence index ${firstOccurrence})`);
|
|
2996
|
-
if (cap.error !== undefined && cap.error !== null) return rejected('failure-not-credited', 'the native tool event carries an error');
|
|
2997
|
-
if (typeof cap.status !== 'string' || !cap.status) return rejected('outcome-ambiguous', 'the native tool status is missing');
|
|
2998
|
-
if (cap.status !== 'completed') return rejected(cap.status === 'error' ? 'failure-not-credited' : 'outcome-ambiguous', `native tool status ${cap.status} does not prove completion`);
|
|
2999
|
-
const processTool = ['bash', 'shell', 'powershell', 'cmd'].includes(String(cap.tool).toLowerCase());
|
|
3000
|
-
if (processTool && !Number.isInteger(cap.exit)) return rejected('outcome-ambiguous', 'a process result without a numeric native exit is ambiguous');
|
|
3001
|
-
if (processTool && cap.exit !== 0) return rejected('failure-not-credited', `the native process exit was ${cap.exit}`);
|
|
3002
|
-
if (!/^[0-9a-f]{64}$/.test(String(cap.result_digest || '')) || !Number.isInteger(cap.result_bytes) || cap.result_bytes < 0) {
|
|
3003
|
-
return rejected('stdout-withheld', 'the native result digest and byte count are absent');
|
|
3004
|
-
}
|
|
3005
|
-
const author = recordOf(safeInput.principals) && textOf(safeInput.principals.author) ? safeInput.principals.author : safeInput.sessionId;
|
|
3006
|
-
if (capability === 'quality-review') {
|
|
3007
|
-
if (!textOf(cap.agent_id)) return rejected('reviewer-principal-missing', 'OpenCode supplied no host-issued reviewer identity');
|
|
3008
|
-
if (cap.agent_id === author) return rejected('reviewer-not-independent', 'the reviewer identity equals the author session principal');
|
|
3009
|
-
return rejected('reviewer-principal-missing', 'OpenCode supplied no host-issued independent-review record');
|
|
3010
|
-
}
|
|
3011
|
-
if (capability) {
|
|
3012
|
-
if (!['doc-lint', 'link-check'].includes(capability)) return rejected('capability-mismatch', `OpenCode cannot supply capability ${capability}`);
|
|
3013
|
-
if (!textOf(cap.command)) return rejected('command-missing', 'the native record has no command for a registered doc-check');
|
|
3014
|
-
if (!textOf(cap.cwd)) return rejected('unregistered-command', 'the host omitted per-tool cwd, so the doc-check invocation cannot be validated');
|
|
3015
|
-
const registered = resolveDocCheckInvocation(cap.command, cap.cwd);
|
|
3016
|
-
if (registered.kind !== 'accepted') return rejected('unregistered-command', `doc-check invocation rejected (${registered.reason}); no credit`);
|
|
3017
|
-
return rejected('stdout-withheld', 'the OpenCode result body is retained only as a digest and cannot prove doc-check output');
|
|
3018
|
-
}
|
|
3019
|
-
if (!textOf(cap.command)) return rejected('command-missing', 'captured OpenCode record has no retained process command');
|
|
3020
|
-
if (!textOf(cap.cwd)) return rejected('outcome-ambiguous', 'the host omitted per-tool cwd');
|
|
3021
|
-
if (!processTool) return rejected('capture-event-unsupported', `tool ${String(cap.tool)} has no OpenCode process mapping`);
|
|
3022
|
-
if (!recordOf(request.identity)) return rejected('identity-missing', 'execution evidence needs a snapshot identity');
|
|
3023
|
-
const contextResponse = resolveContext(request);
|
|
3024
|
-
if (contextResponse.status !== 'accepted') return unavailable('origin-unavailable', 'origin context did not resolve');
|
|
3025
|
-
const identity = JSON.parse(JSON.stringify(request.identity));
|
|
3026
|
-
const resultRef = `opencode-result/${cap.call_id}/${cap.result_digest}`;
|
|
3027
|
-
const event = {
|
|
3028
|
-
eventId: 'opencode-exec-' + digestText(signature + ':execution'),
|
|
3029
|
-
producerId: 'opencode-origin-provider', originRef: contextResponse.originRef,
|
|
3030
|
-
principalId: cap.session_id, provenance: 'opencode-capture:' + cap.call_id,
|
|
3031
|
-
capability: 'shell-command', kind: 'execution', command: cap.command, argv: [cap.command], cwd: cap.cwd,
|
|
3032
|
-
exitCode: cap.exit, signal: null, toolCorrelationId: cap.call_id, resultRef,
|
|
3033
|
-
identity, startIdentity: identity, endIdentity: identity,
|
|
3034
|
-
paths: [], artifactDigests: {}, captured: { responseRef: resultRef, responseDigest: cap.result_digest },
|
|
3035
|
-
};
|
|
3036
|
-
return { status: 'accepted', originRef: contextResponse.originRef, event,
|
|
3037
|
-
correlation: { toolCorrelationId: cap.call_id, resultRef } };
|
|
3038
|
-
}
|
|
3039
|
-
|
|
3040
|
-
return { resolveContext, resolveEvent };
|
|
3041
|
-
};
|
|
3042
|
-
|
|
3043
|
-
// ---- Capture record builder (consumed by state-persist.js) ----------------------
|
|
3044
|
-
|
|
3045
|
-
// Builds the retained capture record for a Claude hook payload. The field names
|
|
3046
|
-
// are the doc's capture-table vocabulary (docs/doc-workflow-reconciliation.md
|
|
3047
|
-
// § S2b). Absent input fields stay absent in the record, never invented.
|
|
3048
|
-
// Responses:
|
|
3049
|
-
// - value capturing the event, or null when the payload does not describe a
|
|
3050
|
-
// supported capture event.
|
|
3051
|
-
let captureSequence = 0;
|
|
3052
|
-
|
|
3053
|
-
function buildCaptureRecord(payload, eventName, workspaceRoot, options = {}) {
|
|
3054
|
-
if (!recordOf(payload)) return null;
|
|
3055
|
-
const event = typeof eventName === 'string' ? eventName : (payload.hook_event_name || payload.hookEventName || '');
|
|
3056
|
-
if (['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'SubagentStart', 'SubagentStop'].indexOf(event) === -1) return null;
|
|
3057
|
-
// PreToolUse is captured only for the launches whose outcome the pilot can later correlate.
|
|
3058
|
-
if (event === 'PreToolUse' && PRE_CAPTURE_TOOLS.indexOf(payload.tool_name) === -1) return null;
|
|
3059
|
-
const toolInput = recordOf(payload.tool_input) ? payload.tool_input : {};
|
|
3060
|
-
const toolResponse = payload.tool_response;
|
|
3061
|
-
const rawExitCode = recordOf(toolResponse) ? (toolResponse.exitCode ?? toolResponse.exit_code) : payload.exitCode;
|
|
3062
|
-
const outlinePre = event === 'PreToolUse' && ['Task', 'Agent'].includes(payload.tool_name);
|
|
3063
|
-
const outlineResult = event === 'PostToolUse' && ['Task', 'Agent'].includes(payload.tool_name);
|
|
3064
|
-
// Demonstrated alias mapping (doc: "Host result aliases such as agentId
|
|
3065
|
-
// require a demonstrated capture mapping to the same subagent identity"):
|
|
3066
|
-
// the PostToolUse Task/Agent result surface reports the subagent id as
|
|
3067
|
-
// tool_response.agentId. No other alias is guessed.
|
|
3068
|
-
const responseAliasAgentId = recordOf(toolResponse) && typeof toolResponse.agentId === 'string' && toolResponse.agentId.trim() ? toolResponse.agentId : undefined;
|
|
3069
|
-
const captureId = `${event}:${new Date().toISOString()}:${process.pid}:${captureSequence += 1}`;
|
|
3070
|
-
const record = {
|
|
3071
|
-
captureId,
|
|
3072
|
-
// Stable origin ref: the reference the assessment looks up (the journal also keeps captureId and responseRef).
|
|
3073
|
-
ref: captureId,
|
|
3074
|
-
event,
|
|
3075
|
-
command: typeof toolInput.command === 'string' ? toolInput.command : '',
|
|
3076
|
-
tool_use_id: typeof payload.tool_use_id === 'string' ? payload.tool_use_id : '',
|
|
3077
|
-
session_id: payload.session_id === undefined && payload.sessionId === undefined ? '' : String(payload.session_id !== undefined ? payload.session_id : payload.sessionId),
|
|
3078
|
-
responseDigest: captureDigest(toolResponse),
|
|
3079
|
-
responseRef: `host-payload/${event}/${captureId}`,
|
|
3080
|
-
};
|
|
3081
|
-
if (typeof rawExitCode === 'number') record.exitCode = rawExitCode;
|
|
3082
|
-
const parsedWriterCommand = event === 'PreToolUse' && payload.tool_name === 'Bash'
|
|
3083
|
-
? safeTokenize(record.command.trim()) : null;
|
|
3084
|
-
const writerMayNeedCwd = OUTLINE_WRITE_TOOLS.includes(payload.tool_name)
|
|
3085
|
-
|| (parsedWriterCommand?.ok && parsedWriterCommand.tokens[0] === 'git'
|
|
3086
|
-
&& ['add', 'commit'].includes(parsedWriterCommand.tokens[1]));
|
|
3087
|
-
if (typeof payload.cwd === 'string' && payload.cwd) record.cwd = payload.cwd;
|
|
3088
|
-
else if (!writerMayNeedCwd && !['SubagentStart', 'SubagentStop'].includes(event)
|
|
3089
|
-
&& typeof workspaceRoot === 'string' && workspaceRoot) record.cwd = workspaceRoot;
|
|
3090
|
-
if (payload.prompt_id !== undefined) record.prompt_id = payload.prompt_id;
|
|
3091
|
-
if (payload.parent_tool_use_id !== undefined) record.parent_tool_use_id = payload.parent_tool_use_id;
|
|
3092
|
-
// The launch tool name separates the Agent/Task result surface and the subagent launch from executed tools (F4/F5).
|
|
3093
|
-
if (typeof payload.tool_name === 'string') record.tool_name = payload.tool_name;
|
|
3094
|
-
// The write target and its PreToolUse topology snapshot are path evidence for W1/W2; absent for other tools.
|
|
3095
|
-
if (OUTLINE_WRITE_TOOLS.includes(payload.tool_name)) record.writeTargets = writeTargetsOf(payload.tool_name, payload.tool_input);
|
|
3096
|
-
// shortcut: this snapshot cannot close capture-to-operation races; upgrade if the host can bind path proof atomically.
|
|
3097
|
-
if (event === 'PreToolUse') {
|
|
3098
|
-
let topologyTargets = OUTLINE_WRITE_TOOLS.includes(payload.tool_name) ? record.writeTargets : null;
|
|
3099
|
-
let allowMissing = OUTLINE_WRITE_TOOLS.includes(payload.tool_name);
|
|
3100
|
-
if (payload.tool_name === 'Bash') {
|
|
3101
|
-
const parsed = safeTokenize(record.command.trim());
|
|
3102
|
-
if (parsed.ok && parsed.tokens[0] === 'git' && parsed.tokens[1] === 'add') {
|
|
3103
|
-
const args = parsed.tokens.slice(2);
|
|
3104
|
-
topologyTargets = args[0] === '--' ? args.slice(1) : args;
|
|
3105
|
-
allowMissing = false;
|
|
3106
|
-
}
|
|
3107
|
-
}
|
|
3108
|
-
if (Array.isArray(topologyTargets)) {
|
|
3109
|
-
record.outlineWriteTopology = topologyTargets.map(target => {
|
|
3110
|
-
const recognized = recognizeOutlineTarget(target, { root: workspaceRoot, cwd: record.cwd, toolName: payload.tool_name });
|
|
3111
|
-
return recognized ? outlineFilesystemProof(workspaceRoot, record.cwd, recognized.candidate, allowMissing)
|
|
3112
|
-
: { path: null, state: 'unresolved' };
|
|
3113
|
-
});
|
|
3114
|
-
}
|
|
3115
|
-
}
|
|
3116
|
-
if (outlinePre) {
|
|
3117
|
-
if (Object.prototype.hasOwnProperty.call(toolInput, 'run_in_background')) record.run_in_background = toolInput.run_in_background;
|
|
3118
|
-
record.isolationSet = Object.prototype.hasOwnProperty.call(toolInput, 'isolation');
|
|
3119
|
-
}
|
|
3120
|
-
if (outlineResult && recordOf(toolResponse) && Object.prototype.hasOwnProperty.call(toolResponse, 'status')) {
|
|
3121
|
-
record.tool_response_status = toolResponse.status;
|
|
3122
|
-
}
|
|
3123
|
-
const resultAgentConflict = outlineResult && textOf(payload.agent_id) && textOf(responseAliasAgentId)
|
|
3124
|
-
&& payload.agent_id !== responseAliasAgentId;
|
|
3125
|
-
const agentId = outlineResult ? (resultAgentConflict ? undefined : responseAliasAgentId)
|
|
3126
|
-
: payload.agent_id !== undefined ? payload.agent_id : responseAliasAgentId;
|
|
3127
|
-
if (agentId !== undefined) {
|
|
3128
|
-
record.agent_id = agentId;
|
|
3129
|
-
if (payload.agent_type !== undefined) record.agent_type = payload.agent_type;
|
|
3130
|
-
}
|
|
3131
|
-
if (payload.duration_ms !== undefined) record.duration_ms = payload.duration_ms;
|
|
3132
|
-
if (event === 'PostToolUse') {
|
|
3133
|
-
// An absent interrupted field stays absent: it is unknown, not false (A3 section 1).
|
|
3134
|
-
if (recordOf(toolResponse) && typeof toolResponse.interrupted === 'boolean') record.interrupted = toolResponse.interrupted;
|
|
3135
|
-
// A registered doc-check invocation keeps its full stdout (capped), a digest of it, and the checked paths' digests
|
|
3136
|
-
// at observation time. Assessment re-parses the stdout; nothing is trusted from an agent-written field.
|
|
3137
|
-
const installedCheck = resolveDocCheckInvocation(record.command, record.cwd);
|
|
3138
|
-
if (installedCheck.kind === 'accepted' || installedCheck.reason === 'implementation-pin-mismatch') {
|
|
3139
|
-
// Record the observed bytes even when unpinned; only an accepted result may retain stdout.
|
|
3140
|
-
record.implementationDigest = installedCheck.digest;
|
|
3141
|
-
}
|
|
3142
|
-
// G0: an unpinned doc-check keeps its digest only; its output is never retained, so no capture credit can be recorded.
|
|
3143
|
-
if (installedCheck && record.implementationDigest === SHIPPED_DOC_CHECK_DIGEST) {
|
|
3144
|
-
const stdout = recordOf(toolResponse) && typeof toolResponse.stdout === 'string' ? toolResponse.stdout : '';
|
|
3145
|
-
record.stdoutDigest = crypto.createHash('sha256').update(stdout).digest('hex');
|
|
3146
|
-
if (Buffer.byteLength(stdout) <= STDOUT_CAP_BYTES) {
|
|
3147
|
-
record.stdout = stdout;
|
|
3148
|
-
// The full tool response is retained so assessment can recompute responseDigest from the same bytes.
|
|
3149
|
-
record.toolResponse = toolResponse;
|
|
3150
|
-
} else { record.stdout = null; record.stdoutTruncated = true; }
|
|
3151
|
-
let checkedPaths = [];
|
|
3152
|
-
let conflictCorpus = null;
|
|
3153
|
-
try {
|
|
3154
|
-
const report = JSON.parse(stdout);
|
|
3155
|
-
checkedPaths = ['doc-lint', 'link-check'].flatMap(capability => (recordOf(report.capabilities) && recordOf(report.capabilities[capability])
|
|
3156
|
-
&& Array.isArray(report.capabilities[capability].checkedPaths) ? report.capabilities[capability].checkedPaths : []));
|
|
3157
|
-
const derived = recordOf(report.capabilities) && report.capabilities['derived-regenerate'];
|
|
3158
|
-
const derivedBinding = recordOf(derived) && recordOf(derived.binding) ? derived.binding : null;
|
|
3159
|
-
if (installedCheck.derivedView && typeof workspaceRoot === 'string' && workspaceRoot && derivedBinding && derivedBinding.view === installedCheck.derivedView
|
|
3160
|
-
&& recordOf(derivedBinding.sourceCorpus) && Array.isArray(derivedBinding.sourceCorpus.paths)
|
|
3161
|
-
&& recordOf(derivedBinding.config) && Array.isArray(derivedBinding.config.sources)) {
|
|
3162
|
-
checkedPaths.push(derivedBinding.view);
|
|
3163
|
-
record.observedDerivedDigests = observedDigestsFor(workspaceRoot,
|
|
3164
|
-
[...derivedBinding.sourceCorpus.paths, derivedBinding.config.path, derivedBinding.view]);
|
|
3165
|
-
record.observedDerivedConfigSources = observedConfigSourcesFor(workspaceRoot, derivedBinding.config.sources);
|
|
3166
|
-
}
|
|
3167
|
-
const conflict = recordOf(report.capabilities) && report.capabilities['conflict-check'];
|
|
3168
|
-
if (installedCheck.conflictAssessment === true && report.mode === 'conflict-assessment'
|
|
3169
|
-
&& recordOf(conflict) && conflict.state === 'pass' && recordOf(conflict.corpus)) {
|
|
3170
|
-
checkedPaths.push(...(Array.isArray(conflict.checkedPaths) ? conflict.checkedPaths : []));
|
|
3171
|
-
conflictCorpus = report.conflictAssessment && report.conflictAssessment.corpus;
|
|
3172
|
-
}
|
|
3173
|
-
} catch { /* not JSON: no paths observed, the event will be withheld */ }
|
|
3174
|
-
record.observedDigests = typeof workspaceRoot === 'string' && workspaceRoot ? observedDigestsFor(workspaceRoot, [...new Set(checkedPaths)]) : {};
|
|
3175
|
-
if (recordOf(conflictCorpus) && Array.isArray(conflictCorpus.paths) && recordOf(conflictCorpus.config)) {
|
|
3176
|
-
record.observedCorpusDigests = typeof workspaceRoot === 'string' && workspaceRoot
|
|
3177
|
-
? observedDigestsFor(workspaceRoot, conflictCorpus.paths) : {};
|
|
3178
|
-
record.observedConfigDigest = typeof workspaceRoot === 'string' && workspaceRoot
|
|
3179
|
-
? observedDigestsFor(workspaceRoot, [conflictCorpus.config.path])[conflictCorpus.config.path] || null : null;
|
|
3180
|
-
}
|
|
3181
|
-
}
|
|
3182
|
-
} else if (event === 'PostToolUseFailure') {
|
|
3183
|
-
record.is_interrupt = Boolean(payload.is_interrupt);
|
|
3184
|
-
record.failureDisposition = /Exit code (\d+)/.exec(String(payload.error === undefined ? '' : payload.error)) ? 'nonzero-exit' : 'host-failure-error';
|
|
3185
|
-
} else if (event === 'SubagentStop') {
|
|
3186
|
-
record.reviewDigest = digestText(String(payload.last_assistant_message === undefined ? '' : payload.last_assistant_message));
|
|
3187
|
-
const verdict = parseReviewVerdict(payload.last_assistant_message);
|
|
3188
|
-
record.reviewVerdict = verdict ? verdict.verdict : null;
|
|
3189
|
-
record.reviewSummary = verdict ? verdict.summary : null;
|
|
3190
|
-
record.reviewedArtifactDigests = verdict ? verdict.reviewedArtifactDigests : {};
|
|
3191
|
-
if (payload.agent_transcript_path !== undefined) record.agentTranscriptPath = payload.agent_transcript_path;
|
|
3192
|
-
}
|
|
3193
|
-
const stateOperation = captureW6StateOperation(payload, event, record, options.sessionDir, workspaceRoot);
|
|
3194
|
-
if (stateOperation) record.stateOperation = stateOperation;
|
|
3195
|
-
return record;
|
|
3196
|
-
}
|
|
3197
|
-
|
|
3198
|
-
// ---- Immutable per-event capture records (I2c) ----------------------------------------------------------------------
|
|
3199
|
-
// Each capture is one event file, created exclusively and never rewritten by this code. The compatibility journal
|
|
3200
|
-
// `doc-reconciliation-capture.json` is rebuilt from those files, and readers compare the two. This detects accidental and
|
|
3201
|
-
// journal-only edits. It does not stop the local agent from rewriting event files, which the owner's bound accepts (F13).
|
|
3202
|
-
// F13 includes rewriting the reviewer Start event's W2 `outlineIdentity`; W2 revalidation assumes authentic captured
|
|
3203
|
-
// events and does not authenticate locally rewritten capture state.
|
|
3204
|
-
const EVENT_DIR = 'doc-reconciliation-capture';
|
|
3205
|
-
const JOURNAL_FILE = 'doc-reconciliation-capture.json';
|
|
3206
|
-
const EVENT_NAME = /^\d{8}\.json$/;
|
|
3207
|
-
|
|
3208
|
-
function immutableEventFiles(sessionDir) {
|
|
3209
|
-
const dir = path.join(sessionDir, EVENT_DIR);
|
|
3210
|
-
if (!fs.existsSync(dir)) return null;
|
|
3211
|
-
return fs.readdirSync(dir).filter(name => EVENT_NAME.test(name)).sort()
|
|
3212
|
-
.map(name => JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')));
|
|
3213
|
-
}
|
|
3214
|
-
|
|
3215
|
-
function writeImmutableEvent(sessionDir, entry) {
|
|
3216
|
-
const dir = path.join(sessionDir, EVENT_DIR);
|
|
3217
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
3218
|
-
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
3219
|
-
const sequence = fs.readdirSync(dir).filter(name => EVENT_NAME.test(name)).length + 1 + attempt;
|
|
3220
|
-
try {
|
|
3221
|
-
fs.writeFileSync(path.join(dir, String(sequence).padStart(8, '0') + '.json'), JSON.stringify(entry, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
|
|
3222
|
-
return;
|
|
3223
|
-
} catch (error) {
|
|
3224
|
-
if (error.code !== 'EEXIST') throw error;
|
|
3225
|
-
}
|
|
3226
|
-
}
|
|
3227
|
-
throw new Error('capture-sequence-exhausted');
|
|
3228
|
-
}
|
|
3229
|
-
|
|
3230
|
-
function rebuildJournalView(sessionDir) {
|
|
3231
|
-
const records = immutableEventFiles(sessionDir) || [];
|
|
3232
|
-
const journalFile = path.join(sessionDir, JOURNAL_FILE);
|
|
3233
|
-
const tempFile = `${journalFile}.${process.pid}.tmp`;
|
|
3234
|
-
fs.writeFileSync(tempFile, JSON.stringify({ version: 1, records }, null, 2), 'utf8');
|
|
3235
|
-
fs.renameSync(tempFile, journalFile);
|
|
3236
|
-
}
|
|
3237
|
-
|
|
3238
|
-
// The records a reader may use: the journal view, provided it still equals the immutable event files. Otherwise tampered.
|
|
3239
|
-
function readCaptureView(sessionDir) {
|
|
3240
|
-
let view = [];
|
|
3241
|
-
try {
|
|
3242
|
-
const journal = JSON.parse(fs.readFileSync(path.join(sessionDir, JOURNAL_FILE), 'utf8'));
|
|
3243
|
-
view = Array.isArray(journal.records) ? journal.records : [];
|
|
3244
|
-
} catch { view = []; }
|
|
3245
|
-
const events = immutableEventFiles(sessionDir);
|
|
3246
|
-
if (events && captureJson(events) !== captureJson(view)) return { records: [], tampered: true };
|
|
3247
|
-
return { records: view, tampered: false };
|
|
3248
|
-
}
|
|
3249
|
-
|
|
3250
|
-
function readOpencodeCaptureView(sessionDir) {
|
|
3251
|
-
const file = path.join(sessionDir, OPENCODE_CAPTURE_FILE);
|
|
3252
|
-
try {
|
|
3253
|
-
if (fs.statSync(file).size > OPENCODE_CAPTURE_LIMIT_BYTES) return { records: [], tampered: true };
|
|
3254
|
-
const text = fs.readFileSync(file, 'utf8');
|
|
3255
|
-
const records = text.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
|
|
3256
|
-
if (!records.every(item => recordOf(item) && item.schema === OPENCODE_CAPTURE_RECORD_VERSION
|
|
3257
|
-
&& item.hostId === OPENCODE_HOST_ID && textOf(item.session_id) && textOf(item.call_id)
|
|
3258
|
-
&& textOf(item.tool) && Object.prototype.hasOwnProperty.call(item, 'status'))) {
|
|
3259
|
-
return { records: [], tampered: true };
|
|
3260
|
-
}
|
|
3261
|
-
return { records, tampered: false };
|
|
3262
|
-
} catch (error) {
|
|
3263
|
-
if (error.code === 'ENOENT') return { records: [], tampered: false };
|
|
3264
|
-
return { records: [], tampered: true };
|
|
3265
|
-
}
|
|
3266
|
-
}
|
|
3267
|
-
|
|
3268
|
-
// Observation-time identity: the workflow and pin the host event was captured under. Absent before a workflow starts.
|
|
3269
|
-
function observedIdentityFor(sessionDir) {
|
|
3270
|
-
try {
|
|
3271
|
-
const workflow = JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8'));
|
|
3272
|
-
return { workflowId: workflow.workflowId, workflowRevision: workflow.revision,
|
|
3273
|
-
baselinePin: workflow.docReconciliationBaseline || null, taskPin: workflow.docReconciliationTask || null };
|
|
3274
|
-
} catch {
|
|
3275
|
-
return null;
|
|
3276
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
|
|
3279
|
-
// Independence rules for a completed host review (owner decision row 2), usable without the credit qualification gate:
|
|
3280
|
-
// the reviewer is a host agent_id that differs from the author session and every executor, the surfaces agree, the final
|
|
3281
|
-
// artifact digest is bound, and the verdict is an explicit approve with a non-empty summary. REJECT never approves.
|
|
3282
|
-
function reviewRecordIndependent(cap, captures, principals) {
|
|
3283
|
-
if (!recordOf(cap) || cap.event !== 'SubagentStop' || !textOf(cap.agent_id)) return false;
|
|
3284
|
-
const executors = [...new Set([...(recordOf(principals) && Array.isArray(principals.executors) ? principals.executors : []),
|
|
3285
|
-
...journalExecutors(captures, principals.author)])];
|
|
3286
|
-
if (cap.agent_id === principals.author || executors.includes(cap.agent_id)) return false;
|
|
3287
|
-
if (!finalReviewResultDecision(captures, cap.agent_id, cap.session_id).accepted) return false;
|
|
3288
|
-
if (!HEX64.test(String(cap.reviewDigest === undefined ? '' : cap.reviewDigest))) return false;
|
|
3289
|
-
if (!reviewedDigestsValid(cap.reviewedArtifactDigests)) return false;
|
|
3290
|
-
return cap.reviewVerdict === 'approve' && textOf(cap.reviewSummary);
|
|
3291
|
-
}
|
|
3292
|
-
|
|
3293
|
-
// Keep the old state-persist seam as an alias; it points at the single resolver above.
|
|
3294
|
-
module.exports = { createClaudeOriginProvider, createOpencodeOriginProvider, buildCaptureRecord, resolveDocCheckInvocation,
|
|
3295
|
-
registeredInstalledCheck: resolveDocCheckInvocation, installedDocCheck,
|
|
3296
|
-
fileDigest, SHIPPED_DOC_CHECK_DIGEST, trustRisk, journalExecutors, reviewRecordIndependent,
|
|
3297
|
-
captureOutlineDispatch, captureOutlineStartIdentity, writeImmutableEvent, rebuildJournalView, readCaptureView,
|
|
3298
|
-
readOpencodeCaptureView, observedIdentityFor, isW6StateCommand, isVerifiedW6StateOperation, pendingW6VerificationInvocation,
|
|
3299
|
-
_internals: { validateOutlineIdentity, captureJson, captureDigest, digestText, canonicalCapture, safeTokenize, parseOutlineDispatchPrompt,
|
|
3300
|
-
parseInventoryPinRows, validateOutlineInventoryPin, resolveInventoryRow, parseOutlineCitation, resolveOutlineAttempt,
|
|
3301
|
-
validateOutlineReview,
|
|
3302
|
-
captureOutlineDispatch, resolveOutlineEvidence, verifyOutlineMergeCorrespondence, validateOutlineCaptureQualification,
|
|
3303
|
-
outlineCaptureMappingValid, correlateOutlineDispatch, evaluateW6StateOperations, validateW6StateOperationPair,
|
|
3304
|
-
OUTLINE_CAPTURE_MAPPING, OUTLINE_INVENTORY_PIN, W6_STATE_OPERATION_SCHEMA, W6_ROW17_REQUIREMENTS } };
|