open-multi-agent-kit 0.98.2 → 0.98.4
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/CHANGELOG.md +45 -0
- package/README.md +11 -2
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +14 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/help.d.ts.map +1 -1
- package/dist/cli/help.js +3 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli/mcp-attach.d.ts +3 -3
- package/dist/cli/mcp-attach.d.ts.map +1 -1
- package/dist/cli/mcp-attach.js +5 -4
- package/dist/cli/mcp-attach.js.map +1 -1
- package/dist/cli/model-contract.d.ts +5 -0
- package/dist/cli/model-contract.d.ts.map +1 -0
- package/dist/cli/model-contract.js +45 -0
- package/dist/cli/model-contract.js.map +1 -0
- package/dist/commands/adaptorch-doctor-cli.d.ts.map +1 -1
- package/dist/commands/adaptorch-doctor-cli.js +32 -10
- package/dist/commands/adaptorch-doctor-cli.js.map +1 -1
- package/dist/commands/init-cli.d.ts +12 -0
- package/dist/commands/init-cli.d.ts.map +1 -0
- package/dist/commands/init-cli.js +76 -0
- package/dist/commands/init-cli.js.map +1 -0
- package/dist/commands/provider-sync-cli.d.ts +27 -0
- package/dist/commands/provider-sync-cli.d.ts.map +1 -0
- package/dist/commands/provider-sync-cli.js +177 -0
- package/dist/commands/provider-sync-cli.js.map +1 -0
- package/dist/commands/run-command.d.ts +8 -0
- package/dist/commands/run-command.d.ts.map +1 -0
- package/dist/commands/run-command.js +26 -0
- package/dist/commands/run-command.js.map +1 -0
- package/dist/core/active-skill-state.d.ts +7 -0
- package/dist/core/active-skill-state.d.ts.map +1 -0
- package/dist/core/active-skill-state.js +25 -0
- package/dist/core/active-skill-state.js.map +1 -0
- package/dist/core/advisory-judge-model.d.ts.map +1 -1
- package/dist/core/advisory-judge-model.js +8 -1
- package/dist/core/advisory-judge-model.js.map +1 -1
- package/dist/core/advisory-judge-types.d.ts +18 -1
- package/dist/core/advisory-judge-types.d.ts.map +1 -1
- package/dist/core/advisory-judge-types.js.map +1 -1
- package/dist/core/advisory-judge.d.ts.map +1 -1
- package/dist/core/advisory-judge.js +41 -6
- package/dist/core/advisory-judge.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +2 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +0 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +30 -85
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/codex-chatgpt-web-bridge.d.ts +99 -0
- package/dist/core/codex-chatgpt-web-bridge.d.ts.map +1 -0
- package/dist/core/codex-chatgpt-web-bridge.js +192 -0
- package/dist/core/codex-chatgpt-web-bridge.js.map +1 -0
- package/dist/core/codex-chatgpt-web-sync.d.ts +50 -0
- package/dist/core/codex-chatgpt-web-sync.d.ts.map +1 -0
- package/dist/core/codex-chatgpt-web-sync.js +119 -0
- package/dist/core/codex-chatgpt-web-sync.js.map +1 -0
- package/dist/core/compaction/compaction-headroom.d.ts +30 -0
- package/dist/core/compaction/compaction-headroom.d.ts.map +1 -0
- package/dist/core/compaction/compaction-headroom.js +48 -0
- package/dist/core/compaction/compaction-headroom.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +2 -29
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +19 -47
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/overflow-retry-guard.d.ts +20 -0
- package/dist/core/compaction/overflow-retry-guard.d.ts.map +1 -0
- package/dist/core/compaction/overflow-retry-guard.js +38 -0
- package/dist/core/compaction/overflow-retry-guard.js.map +1 -0
- package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
- package/dist/core/context-budget-headroom-types.js +1 -1
- package/dist/core/context-budget-headroom-types.js.map +1 -1
- package/dist/core/context-budget-token-counter-types.d.ts +27 -0
- package/dist/core/context-budget-token-counter-types.d.ts.map +1 -0
- package/dist/core/context-budget-token-counter-types.js +2 -0
- package/dist/core/context-budget-token-counter-types.js.map +1 -0
- package/dist/core/context-budget-token-counter.d.ts +2 -26
- package/dist/core/context-budget-token-counter.d.ts.map +1 -1
- package/dist/core/context-budget-token-counter.js +2 -0
- package/dist/core/context-budget-token-counter.js.map +1 -1
- package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
- package/dist/core/context-budget-v2-scoring.js +14 -10
- package/dist/core/context-budget-v2-scoring.js.map +1 -1
- package/dist/core/domain-router.d.ts.map +1 -1
- package/dist/core/domain-router.js +1 -1
- package/dist/core/domain-router.js.map +1 -1
- package/dist/core/grok-harness-dispatch.d.ts +4 -0
- package/dist/core/grok-harness-dispatch.d.ts.map +1 -1
- package/dist/core/grok-harness-dispatch.js +20 -3
- package/dist/core/grok-harness-dispatch.js.map +1 -1
- package/dist/core/grok-harness.d.ts +15 -9
- package/dist/core/grok-harness.d.ts.map +1 -1
- package/dist/core/grok-harness.js +34 -8
- package/dist/core/grok-harness.js.map +1 -1
- package/dist/core/mcp/tools.d.ts +2 -2
- package/dist/core/mcp/tools.d.ts.map +1 -1
- package/dist/core/mcp/tools.js +29 -3
- package/dist/core/mcp/tools.js.map +1 -1
- package/dist/core/model-registry-schema.d.ts +1081 -0
- package/dist/core/model-registry-schema.d.ts.map +1 -0
- package/dist/core/model-registry-schema.js +148 -0
- package/dist/core/model-registry-schema.js.map +1 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +1 -146
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +2 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +2 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/prompt-preset.d.ts +1 -1
- package/dist/core/prompt-preset.d.ts.map +1 -1
- package/dist/core/prompt-preset.js +16 -1
- package/dist/core/prompt-preset.js.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/provider-display-names.js +1 -0
- package/dist/core/provider-display-names.js.map +1 -1
- package/dist/core/provider-resilience.d.ts +8 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +20 -3
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-usage-types.d.ts +42 -0
- package/dist/core/provider-usage-types.d.ts.map +1 -0
- package/dist/core/provider-usage-types.js +2 -0
- package/dist/core/provider-usage-types.js.map +1 -0
- package/dist/core/provider-usage.d.ts +2 -31
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +4 -0
- package/dist/core/provider-usage.js.map +1 -1
- package/dist/core/redaction.d.ts.map +1 -1
- package/dist/core/redaction.js +18 -2
- package/dist/core/redaction.js.map +1 -1
- package/dist/core/sandbox/policy-merge.d.ts +6 -0
- package/dist/core/sandbox/policy-merge.d.ts.map +1 -0
- package/dist/core/sandbox/policy-merge.js +74 -0
- package/dist/core/sandbox/policy-merge.js.map +1 -0
- package/dist/core/sandbox/policy-paths.d.ts +4 -0
- package/dist/core/sandbox/policy-paths.d.ts.map +1 -0
- package/dist/core/sandbox/policy-paths.js +21 -0
- package/dist/core/sandbox/policy-paths.js.map +1 -0
- package/dist/core/sandbox/policy-types.d.ts +75 -0
- package/dist/core/sandbox/policy-types.d.ts.map +1 -0
- package/dist/core/sandbox/policy-types.js +2 -0
- package/dist/core/sandbox/policy-types.js.map +1 -0
- package/dist/core/sandbox/policy.d.ts +3 -77
- package/dist/core/sandbox/policy.d.ts.map +1 -1
- package/dist/core/sandbox/policy.js +3 -98
- package/dist/core/sandbox/policy.js.map +1 -1
- package/dist/core/sdk-provider-stream.d.ts +14 -0
- package/dist/core/sdk-provider-stream.d.ts.map +1 -0
- package/dist/core/sdk-provider-stream.js +38 -0
- package/dist/core/sdk-provider-stream.js.map +1 -0
- package/dist/core/sdk.d.ts +5 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +17 -33
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-bash-runtime.d.ts +7 -0
- package/dist/core/session-bash-runtime.d.ts.map +1 -1
- package/dist/core/session-bash-runtime.js +10 -1
- package/dist/core/session-bash-runtime.js.map +1 -1
- package/dist/core/session-failure-cause.d.ts.map +1 -1
- package/dist/core/session-failure-cause.js +10 -3
- package/dist/core/session-failure-cause.js.map +1 -1
- package/dist/core/session-run-termination.d.ts +18 -0
- package/dist/core/session-run-termination.d.ts.map +1 -0
- package/dist/core/session-run-termination.js +61 -0
- package/dist/core/session-run-termination.js.map +1 -0
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +1 -1
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/skill-selector.d.ts +40 -0
- package/dist/core/skill-selector.d.ts.map +1 -0
- package/dist/core/skill-selector.js +102 -0
- package/dist/core/skill-selector.js.map +1 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +2 -4
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/turn-metrics-record.d.ts +55 -0
- package/dist/core/turn-metrics-record.d.ts.map +1 -0
- package/dist/core/turn-metrics-record.js +149 -0
- package/dist/core/turn-metrics-record.js.map +1 -0
- package/dist/core/turn-metrics.d.ts +4 -56
- package/dist/core/turn-metrics.d.ts.map +1 -1
- package/dist/core/turn-metrics.js +12 -60
- package/dist/core/turn-metrics.js.map +1 -1
- package/dist/core/verified-bash-runtime.d.ts +40 -0
- package/dist/core/verified-bash-runtime.d.ts.map +1 -1
- package/dist/core/verified-bash-runtime.js +60 -13
- package/dist/core/verified-bash-runtime.js.map +1 -1
- package/dist/guardrails/evidence-system.d.ts +1 -1
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +18 -29
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/merge-gate-result.d.ts +4 -0
- package/dist/guardrails/merge-gate-result.d.ts.map +1 -0
- package/dist/guardrails/merge-gate-result.js +32 -0
- package/dist/guardrails/merge-gate-result.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +22 -22
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-login-options.d.ts +27 -0
- package/dist/modes/interactive/interactive-login-options.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-login-options.js +54 -0
- package/dist/modes/interactive/interactive-login-options.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +7 -4
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +138 -140
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/interactive-resume-command.d.ts +3 -0
- package/dist/modes/interactive/interactive-resume-command.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-resume-command.js +24 -0
- package/dist/modes/interactive/interactive-resume-command.js.map +1 -0
- package/dist/modes/interactive/interactive-tool-result.d.ts +32 -0
- package/dist/modes/interactive/interactive-tool-result.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-tool-result.js +59 -0
- package/dist/modes/interactive/interactive-tool-result.js.map +1 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +22 -0
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +10 -60
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/terminal-links.d.ts +13 -0
- package/dist/utils/terminal-links.d.ts.map +1 -0
- package/dist/utils/terminal-links.js +68 -0
- package/dist/utils/terminal-links.js.map +1 -0
- package/dist/utils/windows-clipboard-image.d.ts +16 -0
- package/dist/utils/windows-clipboard-image.d.ts.map +1 -0
- package/dist/utils/windows-clipboard-image.js +87 -0
- package/dist/utils/windows-clipboard-image.js.map +1 -0
- package/docs/adaptorch-onboarding.md +80 -0
- package/docs/advisory-selection.md +112 -0
- package/docs/containerization.md +12 -0
- package/docs/context-files.md +97 -0
- package/docs/correctness-wall.md +8 -0
- package/docs/custom-provider.md +35 -0
- package/docs/development.md +18 -3
- package/docs/environment-variables.md +2 -0
- package/docs/grok-harness.md +4 -0
- package/docs/harness-boundaries.md +154 -0
- package/docs/harness-improvements.md +90 -0
- package/docs/json.md +19 -0
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +22 -2
- package/docs/metrics.md +66 -16
- package/docs/model-catalog-refresh.md +190 -0
- package/docs/model-contract.md +168 -0
- package/docs/models.md +21 -4
- package/docs/provider-resilience.md +5 -3
- package/docs/providers.md +68 -1
- package/docs/quickstart.md +4 -0
- package/docs/release-audit-0.98.3.md +97 -0
- package/docs/release-audit-0.98.4.md +112 -0
- package/docs/review-bundle-followup.md +195 -0
- package/docs/run-protocol.md +3 -1
- package/docs/runtime-algorithms.md +38 -2
- package/docs/sdk.md +35 -3
- package/docs/sessions.md +1 -1
- package/docs/settings.md +17 -1
- package/docs/skills.md +2 -0
- package/docs/tb21-audit.md +131 -0
- package/docs/terminal-setup.md +20 -0
- package/docs/usage.md +23 -1
- package/docs/windows.md +48 -0
- package/examples/README.md +4 -0
- package/examples/context/AGENTS.md +64 -0
- package/examples/context/CLAUDE.md +17 -0
- package/examples/context/INTERNET.md +42 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +18 -18
- package/package.json +6 -6
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* exact legacy unverified path remains available as a byte-identical rollback.
|
|
6
6
|
*/
|
|
7
7
|
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
8
9
|
import { isNormalizedArtifactPath } from "../guardrails/workspace-fingerprint.js";
|
|
9
10
|
export function isVerifiedBashEnabled(env) {
|
|
10
11
|
const source = env ?? process.env;
|
|
@@ -17,6 +18,8 @@ const SCOPE_TTL_MS = 1_000;
|
|
|
17
18
|
const SCOPE_CACHE_MAX = 8;
|
|
18
19
|
const SCOPE_MAX_PATHS = 32;
|
|
19
20
|
const GIT_TIMEOUT_MS = 1_500;
|
|
21
|
+
/** Domain separator so an excluded-set digest can never collide with another digest. */
|
|
22
|
+
const EXCLUDED_SET_DOMAIN = "omk:evidence:session-scope-excluded:v1\0";
|
|
20
23
|
const scopeCache = new Map();
|
|
21
24
|
/**
|
|
22
25
|
* Workspace scope for session bash receipts. Inside a git worktree the scope
|
|
@@ -26,17 +29,40 @@ const scopeCache = new Map();
|
|
|
26
29
|
* empty artifact set under `cwd`. Never throws.
|
|
27
30
|
*/
|
|
28
31
|
export function resolveSessionWorkspaceScope(cwd, options) {
|
|
29
|
-
|
|
32
|
+
return resolveSessionWorkspaceScopeReport(cwd, options).scope;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The scope a receipt would bind, together with the completeness facts that say
|
|
36
|
+
* whether binding it proves anything about the whole workspace.
|
|
37
|
+
*
|
|
38
|
+
* Cached per `(cwd, maxPaths)` for {@link SCOPE_TTL_MS}: keying the cap in too
|
|
39
|
+
* keeps a capped probe from serving a later full request a truncated answer.
|
|
40
|
+
*/
|
|
41
|
+
export function resolveSessionWorkspaceScopeReport(cwd, options) {
|
|
42
|
+
const maxPaths = options?.maxPaths ?? SCOPE_MAX_PATHS;
|
|
43
|
+
const key = `${maxPaths}\0${cwd}`;
|
|
44
|
+
const cached = scopeCache.get(key);
|
|
30
45
|
if (cached && Date.now() - cached.at < SCOPE_TTL_MS)
|
|
31
|
-
return cached.
|
|
32
|
-
const
|
|
46
|
+
return cached.report;
|
|
47
|
+
const report = computeSessionWorkspaceScope(cwd, maxPaths);
|
|
33
48
|
if (scopeCache.size >= SCOPE_CACHE_MAX) {
|
|
34
49
|
const oldest = scopeCache.keys().next().value;
|
|
35
50
|
if (oldest !== undefined)
|
|
36
51
|
scopeCache.delete(oldest);
|
|
37
52
|
}
|
|
38
|
-
scopeCache.set(
|
|
39
|
-
return
|
|
53
|
+
scopeCache.set(key, { at: Date.now(), report });
|
|
54
|
+
return report;
|
|
55
|
+
}
|
|
56
|
+
/** Nothing was enumerated, so the empty artifact set proves nothing about the tree. */
|
|
57
|
+
function unavailableScope(root) {
|
|
58
|
+
return {
|
|
59
|
+
scope: { root, artifactPaths: [] },
|
|
60
|
+
totalDirtyPathCount: 0,
|
|
61
|
+
selectedPathCount: 0,
|
|
62
|
+
excludedPathCount: 0,
|
|
63
|
+
truncated: false,
|
|
64
|
+
completeness: "unavailable",
|
|
65
|
+
};
|
|
40
66
|
}
|
|
41
67
|
function computeSessionWorkspaceScope(cwd, maxPaths) {
|
|
42
68
|
try {
|
|
@@ -46,10 +72,10 @@ function computeSessionWorkspaceScope(cwd, maxPaths) {
|
|
|
46
72
|
stdio: ["ignore", "pipe", "ignore"],
|
|
47
73
|
});
|
|
48
74
|
if (top.status !== 0 || typeof top.stdout !== "string")
|
|
49
|
-
return
|
|
75
|
+
return unavailableScope(cwd);
|
|
50
76
|
const root = top.stdout.trim();
|
|
51
77
|
if (root.length === 0)
|
|
52
|
-
return
|
|
78
|
+
return unavailableScope(cwd);
|
|
53
79
|
// File-granular untracked listing: -unormal emits untracked directories as
|
|
54
80
|
// `dir/`, whose trailing slash fails assertNormalizedArtifactPath downstream
|
|
55
81
|
// and kills every verified bash call in the session.
|
|
@@ -59,9 +85,10 @@ function computeSessionWorkspaceScope(cwd, maxPaths) {
|
|
|
59
85
|
stdio: ["ignore", "pipe", "ignore"],
|
|
60
86
|
});
|
|
61
87
|
if (status.status !== 0 || !status.stdout)
|
|
62
|
-
return
|
|
88
|
+
return unavailableScope(root);
|
|
63
89
|
const fields = status.stdout.toString("utf8").split("\0");
|
|
64
|
-
const paths =
|
|
90
|
+
const paths = new Set();
|
|
91
|
+
const excluded = new Set();
|
|
65
92
|
for (let index = 0; index < fields.length; index++) {
|
|
66
93
|
const field = fields[index];
|
|
67
94
|
if (field.length < 4)
|
|
@@ -77,13 +104,33 @@ function computeSessionWorkspaceScope(cwd, maxPaths) {
|
|
|
77
104
|
// the parent's dirty digest) and names the receipt parser rejects, such
|
|
78
105
|
// as a mangled `\\wsl.localhost\...` directory containing a backslash.
|
|
79
106
|
if (isNormalizedArtifactPath(artifact))
|
|
80
|
-
paths.
|
|
107
|
+
paths.add(artifact);
|
|
108
|
+
else
|
|
109
|
+
excluded.add(artifact);
|
|
81
110
|
}
|
|
82
|
-
const
|
|
83
|
-
|
|
111
|
+
const eligible = [...paths].sort();
|
|
112
|
+
const artifactPaths = eligible.slice(0, maxPaths);
|
|
113
|
+
const truncated = artifactPaths.length < eligible.length;
|
|
114
|
+
return {
|
|
115
|
+
scope: { root, artifactPaths },
|
|
116
|
+
totalDirtyPathCount: eligible.length + excluded.size,
|
|
117
|
+
selectedPathCount: artifactPaths.length,
|
|
118
|
+
excludedPathCount: excluded.size,
|
|
119
|
+
truncated,
|
|
120
|
+
// Truncation outranks exclusion: an excluded path is named by the digest
|
|
121
|
+
// below, a capped one is an unbounded unknown.
|
|
122
|
+
completeness: truncated ? "partial_truncated" : excluded.size > 0 ? "partial_excluded" : "complete",
|
|
123
|
+
...(excluded.size === 0
|
|
124
|
+
? {}
|
|
125
|
+
: {
|
|
126
|
+
excludedPathSetSha256: createHash("sha256")
|
|
127
|
+
.update(`${EXCLUDED_SET_DOMAIN}${JSON.stringify([...excluded].sort())}`)
|
|
128
|
+
.digest("hex"),
|
|
129
|
+
}),
|
|
130
|
+
};
|
|
84
131
|
}
|
|
85
132
|
catch {
|
|
86
|
-
return
|
|
133
|
+
return unavailableScope(cwd);
|
|
87
134
|
}
|
|
88
135
|
}
|
|
89
136
|
//# sourceMappingURL=verified-bash-runtime.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verified-bash-runtime.js","sourceRoot":"","sources":["../../src/core/verified-bash-runtime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAGlF,MAAM,UAAU,qBAAqB,CAAC,GAAwC,EAAW;IACxF,MAAM,MAAM,GAAuC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;IACtE,OAAO,MAAM,CAAC,iBAAiB,KAAK,GAAG,CAAC;AAAA,CACxC;AAED,8EAA8E;AAC9E,0DAA0D;AAC1D,8EAA8E;AAE9E,MAAM,YAAY,GAAG,KAAK,CAAC;AAC3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,cAAc,GAAG,KAAK,CAAC;AAE7B,MAAM,UAAU,GAAG,IAAI,GAAG,EAAiD,CAAC;AAE5E;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAAC,GAAW,EAAE,OAA+B,EAAkB;IAC1G,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,EAAE,GAAG,YAAY;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC;IACzE,MAAM,KAAK,GAAG,4BAA4B,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,IAAI,eAAe,CAAC,CAAC;IACtF,IAAI,UAAU,CAAC,IAAI,IAAI,eAAe,EAAE,CAAC;QACxC,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E,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,aAAa,EAAE,EAAE,EAAE,CAAC;IACzC,CAAC;AAAA,CACD","sourcesContent":["/**\n * Default-on gate for the verified bash adapter (opt-out via OMK_VERIFIED_BASH=0).\n *\n * Mirrors ADR-OMP-009: the receipt-bound path is the default experience; the\n * exact legacy unverified path remains available as a byte-identical rollback.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { isNormalizedArtifactPath } from \"../guardrails/workspace-fingerprint.ts\";\nimport type { WorkspaceScope } from \"../types/evidence.ts\";\n\nexport function isVerifiedBashEnabled(env?: Record<string, string | undefined>): boolean {\n\tconst source: Record<string, string | undefined> = env ?? process.env;\n\treturn source.OMK_VERIFIED_BASH !== \"0\";\n}\n\n// ---------------------------------------------------------------------------\n// Git-aware session workspace scope (bounded, TTL-cached)\n// ---------------------------------------------------------------------------\n\nconst SCOPE_TTL_MS = 1_000;\nconst SCOPE_CACHE_MAX = 8;\nconst SCOPE_MAX_PATHS = 32;\nconst GIT_TIMEOUT_MS = 1_500;\n\nconst scopeCache = new Map<string, { at: number; scope: WorkspaceScope }>();\n\n/**\n * Workspace scope for session bash receipts. Inside a git worktree the scope\n * root is the toplevel and `artifactPaths` is the current dirty set (staged,\n * modified, untracked; capped and sorted), which lets `captureWorkspaceFingerprint`\n * bind HEAD plus a scope-limited dirty digest. Outside git, falls back to an\n * empty artifact set under `cwd`. Never throws.\n */\nexport function resolveSessionWorkspaceScope(cwd: string, options?: { maxPaths?: number }): WorkspaceScope {\n\tconst cached = scopeCache.get(cwd);\n\tif (cached && Date.now() - cached.at < SCOPE_TTL_MS) return cached.scope;\n\tconst scope = computeSessionWorkspaceScope(cwd, options?.maxPaths ?? SCOPE_MAX_PATHS);\n\tif (scopeCache.size >= SCOPE_CACHE_MAX) {\n\t\tconst oldest = scopeCache.keys().next().value;\n\t\tif (oldest !== undefined) scopeCache.delete(oldest);\n\t}\n\tscopeCache.set(cwd, { at: Date.now(), scope });\n\treturn scope;\n}\n\nfunction computeSessionWorkspaceScope(cwd: string, maxPaths: number): WorkspaceScope {\n\ttry {\n\t\tconst top = spawnSync(\"git\", [\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"], {\n\t\t\tencoding: \"utf8\",\n\t\t\ttimeout: GIT_TIMEOUT_MS,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tif (top.status !== 0 || typeof top.stdout !== \"string\") return { root: cwd, artifactPaths: [] };\n\t\tconst root = top.stdout.trim();\n\t\tif (root.length === 0) return { root: cwd, artifactPaths: [] };\n\t\t// File-granular untracked listing: -unormal emits untracked directories as\n\t\t// `dir/`, whose trailing slash fails assertNormalizedArtifactPath downstream\n\t\t// and kills every verified bash call in the session.\n\t\tconst status = spawnSync(\"git\", [\"-C\", cwd, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\"], {\n\t\t\ttimeout: GIT_TIMEOUT_MS,\n\t\t\tmaxBuffer: 4 * 1024 * 1024,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tif (status.status !== 0 || !status.stdout) return { root, artifactPaths: [] };\n\t\tconst fields = status.stdout.toString(\"utf8\").split(\"\\0\");\n\t\tconst paths: string[] = [];\n\t\tfor (let index = 0; index < fields.length; index++) {\n\t\t\tconst field = fields[index];\n\t\t\tif (field.length < 4) continue;\n\t\t\tconst xy = field.slice(0, 2);\n\t\t\tif (xy === \"!!\") continue;\n\t\t\tif (xy.includes(\"R\") || xy.includes(\"C\")) index++; // rename/copy: consume the source path field too\n\t\t\tconst artifact = field.slice(3);\n\t\t\t// Keep only entries the fingerprint can bind. This drops trailing-slash\n\t\t\t// survivors (untracked nested repositories, whose contents are outside\n\t\t\t// the parent's dirty digest) and names the receipt parser rejects, such\n\t\t\t// as a mangled `\\\\wsl.localhost\\...` directory containing a backslash.\n\t\t\tif (isNormalizedArtifactPath(artifact)) paths.push(artifact);\n\t\t}\n\t\tconst artifactPaths = [...new Set(paths)].sort().slice(0, maxPaths);\n\t\treturn { root, artifactPaths };\n\t} catch {\n\t\treturn { root: cwd, artifactPaths: [] };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"verified-bash-runtime.js","sourceRoot":"","sources":["../../src/core/verified-bash-runtime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAGlF,MAAM,UAAU,qBAAqB,CAAC,GAAwC,EAAW;IACxF,MAAM,MAAM,GAAuC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;IACtE,OAAO,MAAM,CAAC,iBAAiB,KAAK,GAAG,CAAC;AAAA,CACxC;AAED,8EAA8E;AAC9E,0DAA0D;AAC1D,8EAA8E;AAE9E,MAAM,YAAY,GAAG,KAAK,CAAC;AAC3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,wFAAwF;AACxF,MAAM,mBAAmB,GAAG,0CAA0C,CAAC;AAEvE,MAAM,UAAU,GAAG,IAAI,GAAG,EAA+D,CAAC;AAkC1F;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAAC,GAAW,EAAE,OAA+B,EAAkB;IAC1G,OAAO,kCAAkC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC;AAAA,CAC9D;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CACjD,GAAW,EACX,OAA+B,EACD;IAC9B,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,eAAe,CAAC;IACtD,MAAM,GAAG,GAAG,GAAG,QAAQ,KAAK,GAAG,EAAE,CAAC;IAClC,M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,mBAAmB,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;yBACvE,MAAM,CAAC,KAAK,CAAC;iBACf,CAAC;SACJ,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC9B,CAAC;AAAA,CACD","sourcesContent":["/**\n * Default-on gate for the verified bash adapter (opt-out via OMK_VERIFIED_BASH=0).\n *\n * Mirrors ADR-OMP-009: the receipt-bound path is the default experience; the\n * exact legacy unverified path remains available as a byte-identical rollback.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { isNormalizedArtifactPath } from \"../guardrails/workspace-fingerprint.ts\";\nimport type { WorkspaceScope } from \"../types/evidence.ts\";\n\nexport function isVerifiedBashEnabled(env?: Record<string, string | undefined>): boolean {\n\tconst source: Record<string, string | undefined> = env ?? process.env;\n\treturn source.OMK_VERIFIED_BASH !== \"0\";\n}\n\n// ---------------------------------------------------------------------------\n// Git-aware session workspace scope (bounded, TTL-cached)\n// ---------------------------------------------------------------------------\n\nconst SCOPE_TTL_MS = 1_000;\nconst SCOPE_CACHE_MAX = 8;\nconst SCOPE_MAX_PATHS = 32;\nconst GIT_TIMEOUT_MS = 1_500;\n/** Domain separator so an excluded-set digest can never collide with another digest. */\nconst EXCLUDED_SET_DOMAIN = \"omk:evidence:session-scope-excluded:v1\\0\";\n\nconst scopeCache = new Map<string, { at: number; report: SessionWorkspaceScopeReport }>();\n\n/**\n * Why a session scope is not a complete view of the workspace dirty set.\n *\n * `unavailable` is not `complete`: outside a worktree, or when git cannot be\n * read, nothing was enumerated, so an empty artifact set is an absence of\n * evidence rather than evidence of a clean tree.\n */\nexport type SessionScopeCompleteness = \"complete\" | \"partial_truncated\" | \"partial_excluded\" | \"unavailable\";\n\n/**\n * A session scope plus what it could not bind.\n *\n * The scope drops dirty paths two ways — a hard cap for availability, and the\n * normalized-path filter the receipt parser forces — and both were previously\n * silent, so a receipt built on a partial view read exactly like one that saw\n * the whole workspace. Dropping stays deliberate; hiding it was the defect.\n */\nexport interface SessionWorkspaceScopeReport {\n\treadonly scope: WorkspaceScope;\n\t/** Unique dirty entries git reported, before the cap and the path filter. */\n\treadonly totalDirtyPathCount: number;\n\t/** Entries the scope binds: always `scope.artifactPaths.length`. */\n\treadonly selectedPathCount: number;\n\t/** Unique dirty entries no receipt can bind, such as a name carrying a backslash. */\n\treadonly excludedPathCount: number;\n\t/** True when the cap, not the filter, kept an eligible path out of the scope. */\n\treadonly truncated: boolean;\n\treadonly completeness: SessionScopeCompleteness;\n\t/** Digest of the sorted excluded set, so two different losses are distinguishable. Absent when nothing was excluded. */\n\treadonly excludedPathSetSha256?: string;\n}\n\n/**\n * Workspace scope for session bash receipts. Inside a git worktree the scope\n * root is the toplevel and `artifactPaths` is the current dirty set (staged,\n * modified, untracked; capped and sorted), which lets `captureWorkspaceFingerprint`\n * bind HEAD plus a scope-limited dirty digest. Outside git, falls back to an\n * empty artifact set under `cwd`. Never throws.\n */\nexport function resolveSessionWorkspaceScope(cwd: string, options?: { maxPaths?: number }): WorkspaceScope {\n\treturn resolveSessionWorkspaceScopeReport(cwd, options).scope;\n}\n\n/**\n * The scope a receipt would bind, together with the completeness facts that say\n * whether binding it proves anything about the whole workspace.\n *\n * Cached per `(cwd, maxPaths)` for {@link SCOPE_TTL_MS}: keying the cap in too\n * keeps a capped probe from serving a later full request a truncated answer.\n */\nexport function resolveSessionWorkspaceScopeReport(\n\tcwd: string,\n\toptions?: { maxPaths?: number },\n): SessionWorkspaceScopeReport {\n\tconst maxPaths = options?.maxPaths ?? SCOPE_MAX_PATHS;\n\tconst key = `${maxPaths}\\0${cwd}`;\n\tconst cached = scopeCache.get(key);\n\tif (cached && Date.now() - cached.at < SCOPE_TTL_MS) return cached.report;\n\tconst report = computeSessionWorkspaceScope(cwd, maxPaths);\n\tif (scopeCache.size >= SCOPE_CACHE_MAX) {\n\t\tconst oldest = scopeCache.keys().next().value;\n\t\tif (oldest !== undefined) scopeCache.delete(oldest);\n\t}\n\tscopeCache.set(key, { at: Date.now(), report });\n\treturn report;\n}\n\n/** Nothing was enumerated, so the empty artifact set proves nothing about the tree. */\nfunction unavailableScope(root: string): SessionWorkspaceScopeReport {\n\treturn {\n\t\tscope: { root, artifactPaths: [] },\n\t\ttotalDirtyPathCount: 0,\n\t\tselectedPathCount: 0,\n\t\texcludedPathCount: 0,\n\t\ttruncated: false,\n\t\tcompleteness: \"unavailable\",\n\t};\n}\n\nfunction computeSessionWorkspaceScope(cwd: string, maxPaths: number): SessionWorkspaceScopeReport {\n\ttry {\n\t\tconst top = spawnSync(\"git\", [\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"], {\n\t\t\tencoding: \"utf8\",\n\t\t\ttimeout: GIT_TIMEOUT_MS,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tif (top.status !== 0 || typeof top.stdout !== \"string\") return unavailableScope(cwd);\n\t\tconst root = top.stdout.trim();\n\t\tif (root.length === 0) return unavailableScope(cwd);\n\t\t// File-granular untracked listing: -unormal emits untracked directories as\n\t\t// `dir/`, whose trailing slash fails assertNormalizedArtifactPath downstream\n\t\t// and kills every verified bash call in the session.\n\t\tconst status = spawnSync(\"git\", [\"-C\", cwd, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\"], {\n\t\t\ttimeout: GIT_TIMEOUT_MS,\n\t\t\tmaxBuffer: 4 * 1024 * 1024,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tif (status.status !== 0 || !status.stdout) return unavailableScope(root);\n\t\tconst fields = status.stdout.toString(\"utf8\").split(\"\\0\");\n\t\tconst paths = new Set<string>();\n\t\tconst excluded = new Set<string>();\n\t\tfor (let index = 0; index < fields.length; index++) {\n\t\t\tconst field = fields[index];\n\t\t\tif (field.length < 4) continue;\n\t\t\tconst xy = field.slice(0, 2);\n\t\t\tif (xy === \"!!\") continue;\n\t\t\tif (xy.includes(\"R\") || xy.includes(\"C\")) index++; // rename/copy: consume the source path field too\n\t\t\tconst artifact = field.slice(3);\n\t\t\t// Keep only entries the fingerprint can bind. This drops trailing-slash\n\t\t\t// survivors (untracked nested repositories, whose contents are outside\n\t\t\t// the parent's dirty digest) and names the receipt parser rejects, such\n\t\t\t// as a mangled `\\\\wsl.localhost\\...` directory containing a backslash.\n\t\t\tif (isNormalizedArtifactPath(artifact)) paths.add(artifact);\n\t\t\telse excluded.add(artifact);\n\t\t}\n\t\tconst eligible = [...paths].sort();\n\t\tconst artifactPaths = eligible.slice(0, maxPaths);\n\t\tconst truncated = artifactPaths.length < eligible.length;\n\t\treturn {\n\t\t\tscope: { root, artifactPaths },\n\t\t\ttotalDirtyPathCount: eligible.length + excluded.size,\n\t\t\tselectedPathCount: artifactPaths.length,\n\t\t\texcludedPathCount: excluded.size,\n\t\t\ttruncated,\n\t\t\t// Truncation outranks exclusion: an excluded path is named by the digest\n\t\t\t// below, a capped one is an unbounded unknown.\n\t\t\tcompleteness: truncated ? \"partial_truncated\" : excluded.size > 0 ? \"partial_excluded\" : \"complete\",\n\t\t\t...(excluded.size === 0\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\texcludedPathSetSha256: createHash(\"sha256\")\n\t\t\t\t\t\t\t.update(`${EXCLUDED_SET_DOMAIN}${JSON.stringify([...excluded].sort())}`)\n\t\t\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\t\t}),\n\t\t};\n\t} catch {\n\t\treturn unavailableScope(cwd);\n\t}\n}\n"]}
|
|
@@ -77,7 +77,7 @@ export declare class EvidenceGate {
|
|
|
77
77
|
check(contract: TaskContract): MergeGateResult;
|
|
78
78
|
}
|
|
79
79
|
export declare class FailClosedMergeGate {
|
|
80
|
-
private gates;
|
|
80
|
+
private readonly gates;
|
|
81
81
|
constructor(gates?: EvidenceGate[]);
|
|
82
82
|
check(contract: TaskContract): MergeGateResult;
|
|
83
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evidence-system.d.ts","sourceRoot":"","sources":["../../src/guardrails/evidence-system.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,yBAAyB,EACzB,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EAEf,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,4BAA4B,EAC5B,cAAc,EACd,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,KAAK,iBAAiB,EAMtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AA+B/E,qBAAa,mBAAmB;IAC/B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAAc;IACrC,OAAO,CAAC,gBAAgB,CAAsB;IAC9C,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,OAAO,CAA2C;IAC1D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,MAAM,EAAE,MAAM,EAKzB;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAI5B;IAED,mBAAmB,CAAC,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,WAAW,GAAG,QAAQ,CAAC,GAAG,IAAI,CAQ9E;IAED,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAI/B;IAED,+FAA+F;IAC/F,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,GAAG,IAAI,CAIzD;IAED,oGAAoG;IACpG,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CASpF;IAED,OAAO,CAAC,KAAK;IAIb,KAAK,IAAI,YAAY,CAUpB;IAED,yFAAyF;IACzF,MAAM,CA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Y,OAAO,EAAE,uBAAuB,EAE3C;IAED,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,GAAG,MAAM,CAuCjE;IAED,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,GAAG,MAAM,CAMhE;CACD","sourcesContent":["// allow: SIZE_OK - evidence ledger guardrails: tamper-evident replay chain + fail-closed parsing.\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n\tEvidenceCommandDescriptor,\n\tEvidenceItem,\n\tEvidenceReceiptMode,\n\tEvidenceStatus,\n\tMergeGateResult,\n\tMergeGateStatus,\n\tReplayEvent,\n\tReplayLedger,\n\tReplayLedgerHead,\n\tTaskContract,\n\tVerifiedReplayLedgerSnapshot,\n\tWorkspaceScope,\n} from \"../types/evidence.ts\";\nimport { redactCommandDescriptor } from \"./command-redaction.ts\";\nimport {\n\ttype CommandHmacBinder,\n\tlatestRelevantWorkspaceMutationSeq,\n\tparseVerifiedLedgerSnapshot,\n\treplayPayloadMatches,\n\tverifyCommandAttestation,\n\tverifyWorkspaceBinding,\n} from \"./evidence-attestation.ts\";\n\nexport { latestRelevantWorkspaceMutationSeq } from \"./evidence-attestation.ts\";\n\nimport {\n\tcomputeEvidenceCommandSha256,\n\tconstantTimeSha256Equal,\n\tevidenceReceiptReplayPayload,\n\tparseSha256Hex,\n\tvalidateEvidenceReceipt,\n} from \"./evidence-receipt.ts\";\nimport { ReplayLedgerStore, replayLedgerHeadsEqual } from \"./replay-ledger-store.ts\";\nimport {\n\tcomputeReplayPayloadHash,\n\tJCS_REPLAY_PAYLOAD_HASH_ALGORITHM,\n\tLEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM,\n} from \"./replay-payload-hash.ts\";\n\nfunction sha256(input: string): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction ensureDir(path: string): void {\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n}\n\n// ============================================================================\n// TaskContract\n// ============================================================================\n\nexport class TaskContractBuilder {\n\tprivate goalId: string;\n\tprivate completionClaim: string = \"\";\n\tprivate requiredEvidence: EvidenceItem[] = [];\n\tprivate finalRisk: string = \"\";\n\tprivate verdict: \"pass\" | \"fail\" | \"conditional\" = \"fail\";\n\tprivate createdAt: string;\n\tprivate updatedAt: string;\n\n\tconstructor(goalId: string) {\n\t\tthis.goalId = goalId;\n\t\tconst now = new Date().toISOString();\n\t\tthis.createdAt = now;\n\t\tthis.updatedAt = now;\n\t}\n\n\tsetClaim(claim: string): this {\n\t\tthis.completionClaim = claim;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\taddRequiredEvidence(evidence: Omit<EvidenceItem, \"timestamp\" | \"status\">): this {\n\t\tthis.requiredEvidence.push({\n\t\t\t...evidence,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tstatus: \"pending\",\n\t\t});\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\tsetFinalRisk(risk: string): this {\n\t\tthis.finalRisk = risk;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\t/** @deprecated Use `evaluateTask()` from `omk-protocol`; verdicts are derived, not mutated. */\n\tsetVerdict(verdict: \"pass\" | \"fail\" | \"conditional\"): this {\n\t\tthis.verdict = verdict;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\t/** @deprecated Append a protocol Observation and re-evaluate instead of mutating evidence state. */\n\tupdateEvidenceStatus(claim: string, status: EvidenceStatus, gapReason?: string): this {\n\t\tconst item = this.requiredEvidence.find((e) => e.claim === claim);\n\t\tif (item) {\n\t\t\titem.status = status;\n\t\t\titem.gapReason = gapReason;\n\t\t\titem.timestamp = new Date().toISOString();\n\t\t\tthis.touch();\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate touch(): void {\n\t\tthis.updatedAt = new Date().toISOString();\n\t}\n\n\tbuild(): TaskContract {\n\t\treturn structuredClone({\n\t\t\tgoalId: this.goalId,\n\t\t\tcompletionClaim: this.completionClaim,\n\t\t\trequiredEvidence: this.requiredEvidence,\n\t\t\tfinalRisk: this.finalRisk,\n\t\t\tverdict: this.verdict,\n\t\t\tcreatedAt: this.createdAt,\n\t\t\tupdatedAt: this.updatedAt,\n\t\t});\n\t}\n\n\t/** Parse and validate a serialized TaskContract. Fails closed on any shape violation. */\n\tstatic fromJSON(json: string): TaskContract {\n\t\tconst raw: unknown = JSON.parse(json);\n\t\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\t\tthrow new Error(\"TaskContract JSON must be an object\");\n\t\t}\n\t\tconst { goalId, completionClaim, finalRisk, verdict, createdAt, updatedAt, requiredEvidence } = raw as Record<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>;\n\t\tif (\n\t\t\ttypeof goalId !== \"string\" ||\n\t\t\ttypeof completionClaim !== \"string\" ||\n\t\t\ttypeof finalRisk !== \"string\" ||\n\t\t\ttypeof createdAt !== \"string\" ||\n\t\t\ttypeof updatedAt !== \"string\"\n\t\t) {\n\t\t\tthrow new Error(\"TaskContract JSON has missing or mistyped string fields\");\n\t\t}\n\t\tif (verdict !== \"pass\" && verdict !== \"fail\" && verdict !== \"conditional\") {\n\t\t\tthrow new Error(`TaskContract verdict must be pass|fail|conditional, got ${String(verdict)}`);\n\t\t}\n\t\tif (!Array.isArray(requiredEvidence)) {\n\t\t\tthrow new Error(\"TaskContract requiredEvidence must be an array\");\n\t\t}\n\t\treturn {\n\t\t\tgoalId,\n\t\t\tcompletionClaim,\n\t\t\tfinalRisk,\n\t\t\tverdict,\n\t\t\tcreatedAt,\n\t\t\tupdatedAt,\n\t\t\trequiredEvidence: requiredEvidence.map((item, index) => parseEvidenceItem(item, index)),\n\t\t};\n\t}\n\n\tstatic toJSON(contract: TaskContract): string {\n\t\treturn JSON.stringify(contract, null, 2);\n\t}\n}\n\nconst EVIDENCE_STATUSES: ReadonlySet<string> = new Set([\"pending\", \"gathering\", \"satisfied\", \"failed\", \"waived\"]);\n\nfunction optionalStringField(value: unknown, field: string, index: number): string | undefined {\n\tif (value !== undefined && typeof value !== \"string\") {\n\t\tthrow new Error(`TaskContract evidence[${index}].${field} must be a string when present`);\n\t}\n\treturn value;\n}\n\nfunction parseEvidenceItem(raw: unknown, index: number): EvidenceItem {\n\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\tthrow new Error(`TaskContract evidence[${index}] must be an object`);\n\t}\n\tconst item = raw as Record<string, unknown>;\n\tconst { claim, category, timestamp, status } = item;\n\tif (typeof claim !== \"string\" || typeof category !== \"string\" || typeof timestamp !== \"string\") {\n\t\tthrow new Error(`TaskContract evidence[${index}] has missing or mistyped fields`);\n\t}\n\tif (typeof status !== \"string\" || !EVIDENCE_STATUSES.has(status)) {\n\t\tthrow new Error(`TaskContract evidence[${index}] has invalid status ${String(status)}`);\n\t}\n\tconst receiptSchemaVersion = item.receiptSchemaVersion;\n\tif (receiptSchemaVersion !== undefined && receiptSchemaVersion !== 3) {\n\t\tthrow new Error(`TaskContract evidence[${index}].receiptSchemaVersion must be 3 when present`);\n\t}\n\tconst receiptCommandSha256 = optionalStringField(item.receiptCommandSha256, \"receiptCommandSha256\", index);\n\treturn {\n\t\tclaim,\n\t\tcategory: category as EvidenceItem[\"category\"],\n\t\ttimestamp,\n\t\tstatus: status as EvidenceStatus,\n\t\tartifactPath: optionalStringField(item.artifactPath, \"artifactPath\", index),\n\t\tverificationCommand: optionalStringField(item.verificationCommand, \"verificationCommand\", index),\n\t\thash: optionalStringField(item.hash, \"hash\", index),\n\t\treceiptId: optionalStringField(item.receiptId, \"receiptId\", index),\n\t\treceiptSchemaVersion,\n\t\t...(receiptCommandSha256 !== undefined\n\t\t\t? { receiptCommandSha256: parseSha256Hex(receiptCommandSha256, \"receiptCommandSha256\") }\n\t\t\t: {}),\n\t\treceiptLaneId: optionalStringField(item.receiptLaneId, \"receiptLaneId\", index),\n\t\tgapReason: optionalStringField(item.gapReason, \"gapReason\", index),\n\t};\n}\n\n// ============================================================================\n// ReplayLedger\n// ============================================================================\n\n/** prevHash sentinel for the first event in a replay chain. */\nconst GENESIS_HASH = \"genesis\";\n\nfunction computeEventHash(event: Omit<ReplayEvent, \"eventHash\">): string {\n\tconst metadata = [event.seq, event.type, event.timestamp, event.goalId, event.laneId ?? null];\n\tconst material =\n\t\tevent.payloadHashAlgorithm === undefined\n\t\t\t? [...metadata, event.payloadHash, event.prevHash]\n\t\t\t: [...metadata, event.payloadHashAlgorithm, event.payloadHash, event.prevHash];\n\treturn sha256(JSON.stringify(material));\n}\n\nfunction parseReplayEventLine(line: string, lineNumber: number): ReplayEvent {\n\tlet raw: unknown;\n\ttry {\n\t\traw = JSON.parse(line);\n\t} catch {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: invalid JSON`);\n\t}\n\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: event must be an object`);\n\t}\n\tconst event = raw as Record<string, unknown>;\n\tconst { seq, type, timestamp, goalId, laneId, payloadHashAlgorithm, payloadHash, prevHash, eventHash } = event;\n\tif (\n\t\ttypeof seq !== \"number\" ||\n\t\ttypeof type !== \"string\" ||\n\t\ttypeof timestamp !== \"string\" ||\n\t\ttypeof goalId !== \"string\" ||\n\t\ttypeof payloadHash !== \"string\" ||\n\t\ttypeof prevHash !== \"string\" ||\n\t\ttypeof eventHash !== \"string\" ||\n\t\t(laneId !== undefined && typeof laneId !== \"string\") ||\n\t\t!(\"payload\" in event)\n\t) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: event fields are missing or mistyped`);\n\t}\n\tif (\n\t\tpayloadHashAlgorithm !== undefined &&\n\t\tpayloadHashAlgorithm !== LEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM &&\n\t\tpayloadHashAlgorithm !== JCS_REPLAY_PAYLOAD_HASH_ALGORITHM\n\t) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: unsupported payload hash algorithm`);\n\t}\n\tconst parsed: ReplayEvent = {\n\t\tseq,\n\t\ttype: type as ReplayEvent[\"type\"],\n\t\ttimestamp,\n\t\tgoalId,\n\t\tlaneId,\n\t\tpayload: event.payload,\n\t\tpayloadHash,\n\t\tprevHash,\n\t\teventHash,\n\t};\n\treturn payloadHashAlgorithm === undefined ? parsed : { ...parsed, payloadHashAlgorithm };\n}\n\nfunction parseReplayLedgerBytes(bytes: Buffer, goalId: string): ReplayEvent[] {\n\tconst lines = bytes\n\t\t.toString(\"utf8\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.trim().length > 0);\n\tconst events: ReplayEvent[] = [];\n\tlet prevHash = GENESIS_HASH;\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst event = parseReplayEventLine(lines[index], index + 1);\n\t\tif (event.goalId !== goalId) throw new Error(`Replay ledger goal mismatch at line ${index + 1}`);\n\t\tif (event.seq !== index + 1) {\n\t\t\tthrow new Error(`Replay ledger corrupted at line ${index + 1}: expected seq ${index + 1}, got ${event.seq}`);\n\t\t}\n\t\tif (event.prevHash !== prevHash) throw new Error(`Replay ledger chain broken at line ${index + 1}`);\n\t\tconst payloadHashAlgorithm = event.payloadHashAlgorithm ?? LEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM;\n\t\tif (computeReplayPayloadHash(event.payload, payloadHashAlgorithm) !== event.payloadHash) {\n\t\t\tthrow new Error(`Replay ledger payload tampered at line ${index + 1} (seq ${event.seq})`);\n\t\t}\n\t\tif (computeEventHash(event) !== event.eventHash) {\n\t\t\tthrow new Error(`Replay ledger event hash mismatch at line ${index + 1} (seq ${event.seq})`);\n\t\t}\n\t\tprevHash = event.eventHash;\n\t\tevents.push(event);\n\t}\n\treturn events;\n}\n\nexport class ReplayLedgerManager {\n\tprivate readonly goalId: string;\n\tprivate readonly ledgerPath: string;\n\tprivate readonly store: ReplayLedgerStore;\n\tprivate events: ReplayEvent[] = [];\n\tprivate committedHead: ReplayLedgerHead;\n\n\tconstructor(goalId: string, ledgerPath: string, expectedHead?: ReplayLedgerHead) {\n\t\tthis.goalId = goalId;\n\t\tthis.ledgerPath = ledgerPath;\n\t\tthis.committedHead = { fileIdentity: null, size: 0, lastSeq: 0, lastHash: GENESIS_HASH };\n\t\tthis.store = new ReplayLedgerStore(ledgerPath, (bytes) => {\n\t\t\tconst events = parseReplayLedgerBytes(bytes, goalId);\n\t\t\tconst last = events[events.length - 1];\n\t\t\treturn { lastSeq: last?.seq ?? 0, lastHash: last?.eventHash ?? GENESIS_HASH };\n\t\t});\n\t\tthis.refresh(expectedHead);\n\t}\n\n\tprivate refresh(expectedHead?: ReplayLedgerHead): void {\n\t\tconst snapshot = this.store.load(expectedHead);\n\t\tthis.events = parseReplayLedgerBytes(snapshot.bytes, this.goalId);\n\t\tthis.committedHead = snapshot.head;\n\t}\n\n\tappend(\n\t\tevent: Omit<ReplayEvent, \"seq\" | \"timestamp\" | \"payloadHashAlgorithm\" | \"payloadHash\" | \"prevHash\" | \"eventHash\">,\n\t\texpectedHead: ReplayLedgerHead = this.committedHead,\n\t): ReplayEvent {\n\t\tif (event.goalId !== this.goalId) throw new Error(\"Replay event goalId does not match the ledger\");\n\t\tif (!replayLedgerHeadsEqual(expectedHead, this.committedHead)) {\n\t\t\tthrow new Error(\"Replay manager expected-head CAS is stale\");\n\t\t}\n\t\tconst payloadHashAlgorithm = JCS_REPLAY_PAYLOAD_HASH_ALGORITHM;\n\t\tconst payloadHash = computeReplayPayloadHash(event.payload, payloadHashAlgorithm);\n\t\tconst chained: Omit<ReplayEvent, \"eventHash\"> = {\n\t\t\t...event,\n\t\t\tseq: expectedHead.lastSeq + 1,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayloadHashAlgorithm,\n\t\t\tpayloadHash,\n\t\t\tprevHash: expectedHead.lastHash,\n\t\t};\n\t\tconst fullEvent: ReplayEvent = { ...chained, eventHash: computeEventHash(chained) };\n\t\tthis.committedHead = this.store.append(\n\t\t\tBuffer.from(`${JSON.stringify(fullEvent)}\\n`, \"utf8\"),\n\t\t\tfullEvent.seq,\n\t\t\tfullEvent.eventHash,\n\t\t\texpectedHead,\n\t\t);\n\t\tthis.events.push(fullEvent);\n\t\treturn structuredClone(fullEvent);\n\t}\n\n\t/** Compatibility no-op that still verifies the caller's expected committed head. */\n\tpersist(expectedHead: ReplayLedgerHead = this.committedHead): void {\n\t\tthis.getVerifiedSnapshot(expectedHead);\n\t}\n\n\tload(expectedHead: ReplayLedgerHead = this.committedHead): void {\n\t\tthis.refresh(expectedHead);\n\t}\n\n\tgetCommittedHead(): ReplayLedgerHead {\n\t\treturn structuredClone(this.committedHead);\n\t}\n\n\tgetVerifiedSnapshot(expectedHead: ReplayLedgerHead = this.committedHead): VerifiedReplayLedgerSnapshot {\n\t\tthis.refresh(expectedHead);\n\t\treturn structuredClone({ events: this.events, head: this.committedHead });\n\t}\n\n\tgetEvents(): ReadonlyArray<ReplayEvent> {\n\t\treturn structuredClone(this.events);\n\t}\n\n\tgetLedger(): Readonly<ReplayLedger> {\n\t\treturn structuredClone({\n\t\t\tgoalId: this.goalId,\n\t\t\tevents: this.events,\n\t\t\tledgerPath: this.ledgerPath,\n\t\t\tlastPersistedSeq: this.committedHead.lastSeq,\n\t\t});\n\t}\n\n\treplay<T>(handler: (event: ReplayEvent) => T | undefined): T[] {\n\t\treturn this.events.map(handler).filter((result): result is T => result !== undefined);\n\t}\n\n\texportToFile(path: string): void {\n\t\tensureDir(path);\n\t\twriteFileSync(path, JSON.stringify(this.events, null, 2), \"utf8\");\n\t}\n}\n\n// ============================================================================\n// EvidenceGate\n// ============================================================================\n\nexport interface EvidenceGateOptions {\n\t/** Minimum number of satisfied evidence items required. */\n\tminEvidenceCount?: number;\n\t/** Require at least one artifact with a SHA-256 hash in explicit legacy mode. */\n\trequireHash?: boolean;\n\t/** Require at least one verification command in explicit legacy mode. */\n\trequireVerificationCommand?: boolean;\n\t/** Receipt policy. Defaults to prefer; legacy must be selected explicitly. */\n\treceiptMode?: EvidenceReceiptMode;\n\t/** Resolve a serialized or decoded receipt by ID. The gate validates the returned value. */\n\tresolveReceipt?: (receiptId: string) => unknown;\n\t/** Strict source: one expected-head, file-identity, suffix, and chain-verified snapshot. */\n\tresolveVerifiedLedgerSnapshot?: () => VerifiedReplayLedgerSnapshot;\n\t/** Prefer-mode migration source; strict mode requires resolveVerifiedLedgerSnapshot. */\n\tresolveLedgerEvent?: (seq: number) => ReplayEvent | undefined;\n\t/** Recapture the receipt's workspace scope (same kind and scope) for freshness comparison. */\n\tcaptureWorkspaceFingerprint?: (scope: WorkspaceScope) => unknown;\n\t/**\n\t * Optional freshness source: the latest replay-ledger sequence of a workspace mutation\n\t * relevant to the given scope, or null/undefined when none is known. When configured,\n\t * the receipt's verified ledger seq must strictly exceed this value; a throwing or\n\t * out-of-contract source is a hard block (positive safe integers only).\n\t */\n\tresolveLatestWorkspaceMutationSeq?: (scope: WorkspaceScope) => number | null | undefined;\n\t/** Ephemeral trust anchor used to verify the original command's keyed attestation. */\n\tcommandAttestationBinder?: Pick<CommandHmacBinder, \"verify\">;\n\t/** Resolve the original command inside the same trust boundary as the binder. */\n\tresolveAttestedCommand?: (receiptId: string) => EvidenceCommandDescriptor | undefined;\n}\n\ninterface ReceiptCheckIssue {\n\treadonly message: string;\n\treadonly hard: boolean;\n}\n\nfunction receiptCheckIssue(message: string, hard: boolean): ReceiptCheckIssue {\n\treturn { message, hard };\n}\n\nfunction receiptIssue(\n\titem: EvidenceItem,\n\tcontract: TaskContract,\n\toptions: EvidenceGateOptions,\n): ReceiptCheckIssue | undefined {\n\tif (!item.receiptId) {\n\t\treturn receiptCheckIssue(`Execution receipt is missing for evidence \"${item.claim}\".`, false);\n\t}\n\tconst strict = options.receiptMode === \"strict\";\n\tif (item.receiptSchemaVersion !== 3 && (item.receiptSchemaVersion !== undefined || strict)) {\n\t\treturn receiptCheckIssue(`Execution receipt schema metadata is invalid for evidence \"${item.claim}\".`, true);\n\t}\n\tif (!options.resolveReceipt) {\n\t\treturn receiptCheckIssue(`Execution receipt resolver is missing for evidence \"${item.claim}\".`, false);\n\t}\n\n\tlet rawReceipt: unknown;\n\ttry {\n\t\trawReceipt = options.resolveReceipt(item.receiptId);\n\t} catch {\n\t\treturn receiptCheckIssue(`Execution receipt resolver failed for evidence \"${item.claim}\".`, true);\n\t}\n\tif (rawReceipt === undefined) {\n\t\treturn receiptCheckIssue(`Execution receipt is missing for evidence \"${item.claim}\".`, false);\n\t}\n\n\ttry {\n\t\tconst receipt = validateEvidenceReceipt(rawReceipt);\n\t\tif (receipt.core.receiptId !== item.receiptId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt ID does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.goalId !== contract.goalId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt goal does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.claim !== item.claim) {\n\t\t\treturn receiptCheckIssue(`Execution receipt claim does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.status !== \"passed\" || receipt.core.exitCode !== 0) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt for evidence \"${item.claim}\" did not pass with exit code 0.`,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t}\n\n\t\tif (item.receiptCommandSha256 === undefined) {\n\t\t\treturn receiptCheckIssue(`Execution receipt command binding is missing for evidence \"${item.claim}\".`, false);\n\t\t}\n\t\tconst receiptCommandSha256 = computeEvidenceCommandSha256(receipt.core.command);\n\t\tif (!constantTimeSha256Equal(item.receiptCommandSha256, receiptCommandSha256)) {\n\t\t\treturn receiptCheckIssue(`Execution receipt command does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tconst attestationIssue = verifyCommandAttestation({\n\t\t\treceiptId: receipt.core.receiptId,\n\t\t\tbinding: receipt.core.commandBinding,\n\t\t\tpersistedCommand: receipt.core.command,\n\t\t\tpersistedSummary: receipt.core.commandRedaction,\n\t\t\tbinder: options.commandAttestationBinder,\n\t\t\tresolveCommand: options.resolveAttestedCommand,\n\t\t\tredact: redactCommandDescriptor,\n\t\t});\n\t\tif (attestationIssue !== undefined) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt command attestation ${attestationIssue.detail} for evidence \"${item.claim}\".`,\n\t\t\t\tattestationIssue.hard,\n\t\t\t);\n\t\t}\n\n\t\tif (receipt.core.laneId !== undefined && item.receiptLaneId === undefined) {\n\t\t\treturn receiptCheckIssue(`Execution receipt lane binding is missing for evidence \"${item.claim}\".`, false);\n\t\t}\n\t\tif (item.receiptLaneId !== receipt.core.laneId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt lane does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\n\t\tconst workspaceIssue = verifyWorkspaceBinding(receipt.core.workspaceAfter, options.captureWorkspaceFingerprint);\n\t\tif (workspaceIssue !== undefined) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ${workspaceIssue.detail} for evidence \"${item.claim}\".`,\n\t\t\t\tworkspaceIssue.hard,\n\t\t\t);\n\t\t}\n\n\t\tlet snapshot: VerifiedReplayLedgerSnapshot | undefined;\n\t\tif (options.resolveVerifiedLedgerSnapshot !== undefined) {\n\t\t\ttry {\n\t\t\t\tsnapshot = parseVerifiedLedgerSnapshot(\n\t\t\t\t\toptions.resolveVerifiedLedgerSnapshot(),\n\t\t\t\t\tcontract.goalId,\n\t\t\t\t\tparseReplayLedgerBytes,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t`Execution receipt verified ledger snapshot failed for evidence \"${item.claim}\".`,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (strict) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt verified ledger snapshot is missing for evidence \"${item.claim}\".`,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tlet latestMutationSeq =\n\t\t\tsnapshot === undefined\n\t\t\t\t? null\n\t\t\t\t: latestRelevantWorkspaceMutationSeq(snapshot.events, receipt.core.workspaceAfter.scope);\n\t\tif (snapshot === undefined && options.resolveLatestWorkspaceMutationSeq !== undefined) {\n\t\t\tlet resolved: unknown;\n\t\t\ttry {\n\t\t\t\tresolved = options.resolveLatestWorkspaceMutationSeq(receipt.core.workspaceAfter.scope);\n\t\t\t} catch {\n\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t`Execution receipt workspace-mutation freshness source failed for evidence \"${item.claim}\".`,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (resolved !== null && resolved !== undefined) {\n\t\t\t\tif (!Number.isSafeInteger(resolved) || (resolved as number) <= 0) {\n\t\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t\t`Execution receipt workspace-mutation freshness source is malformed for evidence \"${item.claim}\".`,\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlatestMutationSeq = resolved as number;\n\t\t\t}\n\t\t}\n\n\t\tconst binding = receipt.envelope.ledgerBinding;\n\t\tif (!binding) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ledger binding is missing for evidence \"${item.claim}\".`,\n\t\t\t\tlatestMutationSeq !== null,\n\t\t\t);\n\t\t}\n\t\tconst event = snapshot\n\t\t\t? snapshot.events.find((candidate) => candidate.seq === binding.seq)\n\t\t\t: options.resolveLedgerEvent?.(binding.seq);\n\t\tif (!event && snapshot === undefined && !options.resolveLedgerEvent) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ledger resolver is missing for evidence \"${item.claim}\".`,\n\t\t\t\tlatestMutationSeq !== null,\n\t\t\t);\n\t\t}\n\t\tconst replayPayload = evidenceReceiptReplayPayload(receipt);\n\t\tif (\n\t\t\t!event ||\n\t\t\tevent.seq !== binding.seq ||\n\t\t\tevent.type !== \"evidence_receipt\" ||\n\t\t\tevent.goalId !== contract.goalId ||\n\t\t\tevent.laneId !== receipt.core.laneId ||\n\t\t\t!constantTimeSha256Equal(event.eventHash, binding.eventHash) ||\n\t\t\t!replayPayloadMatches(event.payload, replayPayload.receiptId, replayPayload.coreSha256)\n\t\t) {\n\t\t\treturn receiptCheckIssue(`Execution receipt ledger binding does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (latestMutationSeq !== null && event.seq <= latestMutationSeq) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt is stale: workspace mutation seq ${latestMutationSeq} does not precede receipt ledger seq ${event.seq} for evidence \"${item.claim}\".`,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t}\n\t} catch {\n\t\treturn receiptCheckIssue(`Execution receipt is invalid for evidence \"${item.claim}\".`, true);\n\t}\n\treturn undefined;\n}\n\nexport class EvidenceGate {\n\tprivate options: EvidenceGateOptions;\n\n\tconstructor(options: EvidenceGateOptions = {}) {\n\t\tthis.options = {\n\t\t\tminEvidenceCount: 1,\n\t\t\trequireHash: true,\n\t\t\trequireVerificationCommand: true,\n\t\t\treceiptMode: \"prefer\",\n\t\t\t...options,\n\t\t};\n\t}\n\n\tcheck(contract: TaskContract): MergeGateResult {\n\t\tconst evidence = contract.requiredEvidence;\n\t\tconst satisfied = evidence.filter((e) => e.status === \"satisfied\");\n\t\tconst failed = evidence.filter((e) => e.status === \"failed\");\n\t\tconst pending = evidence.filter((e) => e.status === \"pending\" || e.status === \"gathering\");\n\t\tconst mode = this.options.receiptMode ?? \"prefer\";\n\t\tconst checks: string[] = [];\n\t\tlet hardReceiptFailure = false;\n\n\t\tif (satisfied.length < (this.options.minEvidenceCount ?? 1)) {\n\t\t\tchecks.push(`Only ${satisfied.length}/${this.options.minEvidenceCount} required evidence items satisfied.`);\n\t\t}\n\t\tif (failed.length > 0) {\n\t\t\tchecks.push(`${failed.length} evidence item(s) failed.`);\n\t\t}\n\n\t\tif (mode === \"legacy\") {\n\t\t\tif (this.options.requireHash) {\n\t\t\t\tconst hashed = satisfied.filter((e) => e.hash && e.hash.length > 0);\n\t\t\t\tif (hashed.length === 0) checks.push(\"No satisfied evidence has a SHA-256 hash.\");\n\t\t\t}\n\t\t\tif (this.options.requireVerificationCommand) {\n\t\t\t\tconst withCommand = satisfied.filter((e) => e.verificationCommand && e.verificationCommand.length > 0);\n\t\t\t\tif (withCommand.length === 0) checks.push(\"No satisfied evidence has a verification command.\");\n\t\t\t}\n\t\t} else {\n\t\t\tconst unsatisfied = evidence.filter((item) => item.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\tchecks.push(`${unsatisfied.length} required evidence item(s) are not satisfied.`);\n\t\t\t}\n\t\t\tfor (const item of satisfied) {\n\t\t\t\tconst issue = receiptIssue(item, contract, this.options);\n\t\t\t\tif (issue) {\n\t\t\t\t\tchecks.push(issue.message);\n\t\t\t\t\thardReceiptFailure ||= issue.hard;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (contract.verdict === \"fail\" || (mode !== \"legacy\" && contract.verdict !== \"pass\")) {\n\t\t\tchecks.push(`Task contract verdict is '${contract.verdict}'.`);\n\t\t}\n\n\t\tlet status: MergeGateStatus;\n\t\tlet reason: string;\n\t\tlet suggestion: string | undefined;\n\t\tif (checks.length === 0) {\n\t\t\tstatus = \"open\";\n\t\t\treason = `Evidence gate passed: ${satisfied.length}/${evidence.length} evidence items satisfied.`;\n\t\t} else {\n\t\t\tconst contractFailure = mode === \"legacy\" ? contract.verdict === \"fail\" : contract.verdict !== \"pass\";\n\t\t\tconst hasHardFailure = failed.length > 0 || contractFailure || hardReceiptFailure || mode === \"strict\";\n\t\t\tstatus = hasHardFailure ? \"blocked\" : mode === \"prefer\" || pending.length > 0 ? \"conditional\" : \"blocked\";\n\t\t\treason = checks.join(\"; \");\n\t\t\tsuggestion = `Gather remaining evidence (${pending.length} pending) and re-run verification.`;\n\t\t}\n\n\t\treturn {\n\t\t\tgateId: \"evidence-gate\",\n\t\t\tstatus,\n\t\t\treason,\n\t\t\tsuggestion,\n\t\t\tevidenceChecked: evidence,\n\t\t};\n\t}\n}\n\n// ============================================================================\n// FailClosedMergeGate\n// ============================================================================\n\nexport class FailClosedMergeGate {\n\tprivate gates: EvidenceGate[];\n\n\tconstructor(gates: EvidenceGate[] = [new EvidenceGate()]) {\n\t\tthis.gates = gates;\n\t}\n\n\tcheck(contract: TaskContract): MergeGateResult {\n\t\tconst results = this.gates.map((gate) => gate.check(contract));\n\t\tconst blocked = results.filter((r) => r.status === \"blocked\");\n\t\tconst conditional = results.filter((r) => r.status === \"conditional\");\n\n\t\tif (blocked.length > 0) {\n\t\t\treturn {\n\t\t\t\tgateId: \"fail-closed-merge-gate\",\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\treason: `Blocked by ${blocked.length} gate(s): ${blocked.map((b) => b.reason).join(\"; \")}`,\n\t\t\t\tsuggestion: \"Resolve all blocking conditions before merge.\",\n\t\t\t\tevidenceChecked: contract.requiredEvidence,\n\t\t\t};\n\t\t}\n\n\t\tif (conditional.length > 0) {\n\t\t\treturn {\n\t\t\t\tgateId: \"fail-closed-merge-gate\",\n\t\t\t\tstatus: \"conditional\",\n\t\t\t\treason: `Conditional pass: ${conditional.length} gate(s) have pending conditions.`,\n\t\t\t\tsuggestion: \"Complete pending evidence or waive with explicit approval.\",\n\t\t\t\tevidenceChecked: contract.requiredEvidence,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tgateId: \"fail-closed-merge-gate\",\n\t\t\tstatus: \"open\",\n\t\t\treason: \"All merge gates passed. Evidence verified and contract verdict is acceptable.\",\n\t\t\tevidenceChecked: contract.requiredEvidence,\n\t\t};\n\t}\n}\n\n// ============================================================================\n// Verify Reporter v2\n// ============================================================================\n\n/** Escape pipes/newlines so untrusted claim or command text cannot restructure the report table. */\nfunction escapeTableCell(value: string): string {\n\treturn value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n}\n\nexport interface VerifyReporterV2Options {\n\toutputDir: string;\n\tgoalId: string;\n}\n\nexport class VerifyReporterV2 {\n\tprivate options: VerifyReporterV2Options;\n\n\tconstructor(options: VerifyReporterV2Options) {\n\t\tthis.options = options;\n\t}\n\n\trender(contract: TaskContract, mergeGate: MergeGateResult): string {\n\t\tconst lines: string[] = [\n\t\t\t`## OMK Verification Report v2 — ${contract.goalId}`,\n\t\t\t\"\",\n\t\t\t\"### Contract\",\n\t\t\t\"\",\n\t\t\t`| Field | Value |`,\n\t\t\t`|-------|-------|`,\n\t\t\t`| Claim | ${escapeTableCell(contract.completionClaim)} |`,\n\t\t\t`| Verdict | ${contract.verdict} |`,\n\t\t\t`| Final Risk | ${escapeTableCell(contract.finalRisk)} |`,\n\t\t\t\"\",\n\t\t\t\"### Evidence\",\n\t\t\t\"\",\n\t\t\t`| Claim | Status | Artifact | Command |`,\n\t\t\t`|-------|--------|----------|----------|`,\n\t\t];\n\n\t\tfor (const ev of contract.requiredEvidence) {\n\t\t\tlines.push(\n\t\t\t\t`| ${escapeTableCell(ev.claim)} | ${ev.status} | ${escapeTableCell(ev.artifactPath ?? \"—\")} | ${escapeTableCell(ev.verificationCommand ?? \"—\")} |`,\n\t\t\t);\n\t\t}\n\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"### Merge Gate\",\n\t\t\t\"\",\n\t\t\t`| Gate | Status | Reason |`,\n\t\t\t`|------|--------|--------|`,\n\t\t\t`| ${mergeGate.gateId} | ${mergeGate.status} | ${escapeTableCell(mergeGate.reason)} |`,\n\t\t\t\"\",\n\t\t);\n\n\t\tif (mergeGate.suggestion) {\n\t\t\tlines.push(`**Suggestion:** ${mergeGate.suggestion}`, \"\");\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\twrite(contract: TaskContract, mergeGate: MergeGateResult): string {\n\t\tconst markdown = this.render(contract, mergeGate);\n\t\tconst path = join(this.options.outputDir, `${this.options.goalId}.verify.md`);\n\t\tensureDir(path);\n\t\twriteFileSync(path, markdown, \"utf-8\");\n\t\treturn path;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"evidence-system.d.ts","sourceRoot":"","sources":["../../src/guardrails/evidence-system.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,yBAAyB,EACzB,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EAEf,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,4BAA4B,EAC5B,cAAc,EACd,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,KAAK,iBAAiB,EAMtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAgC/E,qBAAa,mBAAmB;IAC/B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAAc;IACrC,OAAO,CAAC,gBAAgB,CAAsB;IAC9C,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,OAAO,CAA2C;IAC1D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,MAAM,EAAE,MAAM,EAKzB;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAI5B;IAED,mBAAmB,CAAC,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,WAAW,GAAG,QAAQ,CAAC,GAAG,IAAI,CAQ9E;IAED,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAI/B;IAED,+FAA+F;IAC/F,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,GAAG,IAAI,CAIzD;IAED,oGAAoG;IACpG,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CASpF;IAED,OAAO,CAAC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AM,CAAC;CACf;AAED,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,OAAO,CAA0B;IAEzC,YAAY,OAAO,EAAE,uBAAuB,EAE3C;IAED,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,GAAG,MAAM,CAuCjE;IAED,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,GAAG,MAAM,CAMhE;CACD","sourcesContent":["// allow: SIZE_OK - evidence ledger guardrails: tamper-evident replay chain + fail-closed parsing.\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n\tEvidenceCommandDescriptor,\n\tEvidenceItem,\n\tEvidenceReceiptMode,\n\tEvidenceStatus,\n\tMergeGateResult,\n\tMergeGateStatus,\n\tReplayEvent,\n\tReplayLedger,\n\tReplayLedgerHead,\n\tTaskContract,\n\tVerifiedReplayLedgerSnapshot,\n\tWorkspaceScope,\n} from \"../types/evidence.ts\";\nimport { redactCommandDescriptor } from \"./command-redaction.ts\";\nimport {\n\ttype CommandHmacBinder,\n\tlatestRelevantWorkspaceMutationSeq,\n\tparseVerifiedLedgerSnapshot,\n\treplayPayloadMatches,\n\tverifyCommandAttestation,\n\tverifyWorkspaceBinding,\n} from \"./evidence-attestation.ts\";\n\nexport { latestRelevantWorkspaceMutationSeq } from \"./evidence-attestation.ts\";\n\nimport {\n\tcomputeEvidenceCommandSha256,\n\tconstantTimeSha256Equal,\n\tevidenceReceiptReplayPayload,\n\tparseSha256Hex,\n\tvalidateEvidenceReceipt,\n} from \"./evidence-receipt.ts\";\nimport { combineMergeGateResults } from \"./merge-gate-result.ts\";\nimport { ReplayLedgerStore, replayLedgerHeadsEqual } from \"./replay-ledger-store.ts\";\nimport {\n\tcomputeReplayPayloadHash,\n\tJCS_REPLAY_PAYLOAD_HASH_ALGORITHM,\n\tLEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM,\n} from \"./replay-payload-hash.ts\";\n\nfunction sha256(input: string): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction ensureDir(path: string): void {\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n}\n\n// ============================================================================\n// TaskContract\n// ============================================================================\n\nexport class TaskContractBuilder {\n\tprivate goalId: string;\n\tprivate completionClaim: string = \"\";\n\tprivate requiredEvidence: EvidenceItem[] = [];\n\tprivate finalRisk: string = \"\";\n\tprivate verdict: \"pass\" | \"fail\" | \"conditional\" = \"fail\";\n\tprivate createdAt: string;\n\tprivate updatedAt: string;\n\n\tconstructor(goalId: string) {\n\t\tthis.goalId = goalId;\n\t\tconst now = new Date().toISOString();\n\t\tthis.createdAt = now;\n\t\tthis.updatedAt = now;\n\t}\n\n\tsetClaim(claim: string): this {\n\t\tthis.completionClaim = claim;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\taddRequiredEvidence(evidence: Omit<EvidenceItem, \"timestamp\" | \"status\">): this {\n\t\tthis.requiredEvidence.push({\n\t\t\t...evidence,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tstatus: \"pending\",\n\t\t});\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\tsetFinalRisk(risk: string): this {\n\t\tthis.finalRisk = risk;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\t/** @deprecated Use `evaluateTask()` from `omk-protocol`; verdicts are derived, not mutated. */\n\tsetVerdict(verdict: \"pass\" | \"fail\" | \"conditional\"): this {\n\t\tthis.verdict = verdict;\n\t\tthis.touch();\n\t\treturn this;\n\t}\n\n\t/** @deprecated Append a protocol Observation and re-evaluate instead of mutating evidence state. */\n\tupdateEvidenceStatus(claim: string, status: EvidenceStatus, gapReason?: string): this {\n\t\tconst item = this.requiredEvidence.find((e) => e.claim === claim);\n\t\tif (item) {\n\t\t\titem.status = status;\n\t\t\titem.gapReason = gapReason;\n\t\t\titem.timestamp = new Date().toISOString();\n\t\t\tthis.touch();\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate touch(): void {\n\t\tthis.updatedAt = new Date().toISOString();\n\t}\n\n\tbuild(): TaskContract {\n\t\treturn structuredClone({\n\t\t\tgoalId: this.goalId,\n\t\t\tcompletionClaim: this.completionClaim,\n\t\t\trequiredEvidence: this.requiredEvidence,\n\t\t\tfinalRisk: this.finalRisk,\n\t\t\tverdict: this.verdict,\n\t\t\tcreatedAt: this.createdAt,\n\t\t\tupdatedAt: this.updatedAt,\n\t\t});\n\t}\n\n\t/** Parse and validate a serialized TaskContract. Fails closed on any shape violation. */\n\tstatic fromJSON(json: string): TaskContract {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = JSON.parse(json);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) throw new SyntaxError(\"Invalid TaskContract JSON\");\n\t\t\tthrow error;\n\t\t}\n\t\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\t\tthrow new Error(\"TaskContract JSON must be an object\");\n\t\t}\n\t\tconst { goalId, completionClaim, finalRisk, verdict, createdAt, updatedAt, requiredEvidence } = raw as Record<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>;\n\t\tif (\n\t\t\ttypeof goalId !== \"string\" ||\n\t\t\ttypeof completionClaim !== \"string\" ||\n\t\t\ttypeof finalRisk !== \"string\" ||\n\t\t\ttypeof createdAt !== \"string\" ||\n\t\t\ttypeof updatedAt !== \"string\"\n\t\t) {\n\t\t\tthrow new Error(\"TaskContract JSON has missing or mistyped string fields\");\n\t\t}\n\t\tif (verdict !== \"pass\" && verdict !== \"fail\" && verdict !== \"conditional\") {\n\t\t\tthrow new Error(`TaskContract verdict must be pass|fail|conditional, got ${String(verdict)}`);\n\t\t}\n\t\tif (!Array.isArray(requiredEvidence)) {\n\t\t\tthrow new Error(\"TaskContract requiredEvidence must be an array\");\n\t\t}\n\t\treturn {\n\t\t\tgoalId,\n\t\t\tcompletionClaim,\n\t\t\tfinalRisk,\n\t\t\tverdict,\n\t\t\tcreatedAt,\n\t\t\tupdatedAt,\n\t\t\trequiredEvidence: requiredEvidence.map((item, index) => parseEvidenceItem(item, index)),\n\t\t};\n\t}\n\n\tstatic toJSON(contract: TaskContract): string {\n\t\treturn JSON.stringify(contract, null, 2);\n\t}\n}\n\nconst EVIDENCE_STATUSES: ReadonlySet<string> = new Set([\"pending\", \"gathering\", \"satisfied\", \"failed\", \"waived\"]);\n\nfunction optionalStringField(value: unknown, field: string, index: number): string | undefined {\n\tif (value !== undefined && typeof value !== \"string\") {\n\t\tthrow new Error(`TaskContract evidence[${index}].${field} must be a string when present`);\n\t}\n\treturn value;\n}\n\nfunction parseEvidenceItem(raw: unknown, index: number): EvidenceItem {\n\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\tthrow new Error(`TaskContract evidence[${index}] must be an object`);\n\t}\n\tconst item = raw as Record<string, unknown>;\n\tconst { claim, category, timestamp, status } = item;\n\tif (typeof claim !== \"string\" || typeof category !== \"string\" || typeof timestamp !== \"string\") {\n\t\tthrow new Error(`TaskContract evidence[${index}] has missing or mistyped fields`);\n\t}\n\tif (typeof status !== \"string\" || !EVIDENCE_STATUSES.has(status)) {\n\t\tthrow new Error(`TaskContract evidence[${index}] has invalid status ${String(status)}`);\n\t}\n\tconst receiptSchemaVersion = item.receiptSchemaVersion;\n\tif (receiptSchemaVersion !== undefined && receiptSchemaVersion !== 3) {\n\t\tthrow new Error(`TaskContract evidence[${index}].receiptSchemaVersion must be 3 when present`);\n\t}\n\tconst receiptCommandSha256 = optionalStringField(item.receiptCommandSha256, \"receiptCommandSha256\", index);\n\treturn {\n\t\tclaim,\n\t\tcategory: category as EvidenceItem[\"category\"],\n\t\ttimestamp,\n\t\tstatus: status as EvidenceStatus,\n\t\tartifactPath: optionalStringField(item.artifactPath, \"artifactPath\", index),\n\t\tverificationCommand: optionalStringField(item.verificationCommand, \"verificationCommand\", index),\n\t\thash: optionalStringField(item.hash, \"hash\", index),\n\t\treceiptId: optionalStringField(item.receiptId, \"receiptId\", index),\n\t\treceiptSchemaVersion,\n\t\t...(receiptCommandSha256 !== undefined\n\t\t\t? { receiptCommandSha256: parseSha256Hex(receiptCommandSha256, \"receiptCommandSha256\") }\n\t\t\t: {}),\n\t\treceiptLaneId: optionalStringField(item.receiptLaneId, \"receiptLaneId\", index),\n\t\tgapReason: optionalStringField(item.gapReason, \"gapReason\", index),\n\t};\n}\n\n// ============================================================================\n// ReplayLedger\n// ============================================================================\n\n/** prevHash sentinel for the first event in a replay chain. */\nconst GENESIS_HASH = \"genesis\";\n\nfunction computeEventHash(event: Omit<ReplayEvent, \"eventHash\">): string {\n\tconst metadata = [event.seq, event.type, event.timestamp, event.goalId, event.laneId ?? null];\n\tconst material =\n\t\tevent.payloadHashAlgorithm === undefined\n\t\t\t? [...metadata, event.payloadHash, event.prevHash]\n\t\t\t: [...metadata, event.payloadHashAlgorithm, event.payloadHash, event.prevHash];\n\treturn sha256(JSON.stringify(material));\n}\n\nfunction parseReplayEventLine(line: string, lineNumber: number): ReplayEvent {\n\tlet raw: unknown;\n\ttry {\n\t\traw = JSON.parse(line);\n\t} catch {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: invalid JSON`);\n\t}\n\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: event must be an object`);\n\t}\n\tconst event = raw as Record<string, unknown>;\n\tconst { seq, type, timestamp, goalId, laneId, payloadHashAlgorithm, payloadHash, prevHash, eventHash } = event;\n\tif (\n\t\ttypeof seq !== \"number\" ||\n\t\ttypeof type !== \"string\" ||\n\t\ttypeof timestamp !== \"string\" ||\n\t\ttypeof goalId !== \"string\" ||\n\t\ttypeof payloadHash !== \"string\" ||\n\t\ttypeof prevHash !== \"string\" ||\n\t\ttypeof eventHash !== \"string\" ||\n\t\t(laneId !== undefined && typeof laneId !== \"string\") ||\n\t\t!(\"payload\" in event)\n\t) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: event fields are missing or mistyped`);\n\t}\n\tif (\n\t\tpayloadHashAlgorithm !== undefined &&\n\t\tpayloadHashAlgorithm !== LEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM &&\n\t\tpayloadHashAlgorithm !== JCS_REPLAY_PAYLOAD_HASH_ALGORITHM\n\t) {\n\t\tthrow new Error(`Replay ledger corrupted at line ${lineNumber}: unsupported payload hash algorithm`);\n\t}\n\tconst parsed: ReplayEvent = {\n\t\tseq,\n\t\ttype: type as ReplayEvent[\"type\"],\n\t\ttimestamp,\n\t\tgoalId,\n\t\tlaneId,\n\t\tpayload: event.payload,\n\t\tpayloadHash,\n\t\tprevHash,\n\t\teventHash,\n\t};\n\treturn payloadHashAlgorithm === undefined ? parsed : { ...parsed, payloadHashAlgorithm };\n}\n\nfunction parseReplayLedgerBytes(bytes: Buffer, goalId: string): ReplayEvent[] {\n\tconst lines = bytes\n\t\t.toString(\"utf8\")\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.trim().length > 0);\n\tconst events: ReplayEvent[] = [];\n\tlet prevHash = GENESIS_HASH;\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst event = parseReplayEventLine(lines[index], index + 1);\n\t\tif (event.goalId !== goalId) throw new Error(`Replay ledger goal mismatch at line ${index + 1}`);\n\t\tif (event.seq !== index + 1) {\n\t\t\tthrow new Error(`Replay ledger corrupted at line ${index + 1}: expected seq ${index + 1}, got ${event.seq}`);\n\t\t}\n\t\tif (event.prevHash !== prevHash) throw new Error(`Replay ledger chain broken at line ${index + 1}`);\n\t\tconst payloadHashAlgorithm = event.payloadHashAlgorithm ?? LEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM;\n\t\tif (computeReplayPayloadHash(event.payload, payloadHashAlgorithm) !== event.payloadHash) {\n\t\t\tthrow new Error(`Replay ledger payload tampered at line ${index + 1} (seq ${event.seq})`);\n\t\t}\n\t\tif (computeEventHash(event) !== event.eventHash) {\n\t\t\tthrow new Error(`Replay ledger event hash mismatch at line ${index + 1} (seq ${event.seq})`);\n\t\t}\n\t\tprevHash = event.eventHash;\n\t\tevents.push(event);\n\t}\n\treturn events;\n}\n\nexport class ReplayLedgerManager {\n\tprivate readonly goalId: string;\n\tprivate readonly ledgerPath: string;\n\tprivate readonly store: ReplayLedgerStore;\n\tprivate events: ReplayEvent[] = [];\n\tprivate committedHead: ReplayLedgerHead;\n\n\tconstructor(goalId: string, ledgerPath: string, expectedHead?: ReplayLedgerHead) {\n\t\tthis.goalId = goalId;\n\t\tthis.ledgerPath = ledgerPath;\n\t\tthis.committedHead = { fileIdentity: null, size: 0, lastSeq: 0, lastHash: GENESIS_HASH };\n\t\tthis.store = new ReplayLedgerStore(ledgerPath, (bytes) => {\n\t\t\tconst events = parseReplayLedgerBytes(bytes, goalId);\n\t\t\tconst last = events[events.length - 1];\n\t\t\treturn { lastSeq: last?.seq ?? 0, lastHash: last?.eventHash ?? GENESIS_HASH };\n\t\t});\n\t\tthis.refresh(expectedHead);\n\t}\n\n\tprivate refresh(expectedHead?: ReplayLedgerHead): void {\n\t\tconst snapshot = this.store.load(expectedHead);\n\t\tthis.events = parseReplayLedgerBytes(snapshot.bytes, this.goalId);\n\t\tthis.committedHead = snapshot.head;\n\t}\n\n\tappend(\n\t\tevent: Omit<ReplayEvent, \"seq\" | \"timestamp\" | \"payloadHashAlgorithm\" | \"payloadHash\" | \"prevHash\" | \"eventHash\">,\n\t\texpectedHead: ReplayLedgerHead = this.committedHead,\n\t): ReplayEvent {\n\t\tif (event.goalId !== this.goalId) throw new Error(\"Replay event goalId does not match the ledger\");\n\t\tif (!replayLedgerHeadsEqual(expectedHead, this.committedHead)) {\n\t\t\tthrow new Error(\"Replay manager expected-head CAS is stale\");\n\t\t}\n\t\tconst payloadHashAlgorithm = JCS_REPLAY_PAYLOAD_HASH_ALGORITHM;\n\t\tconst payloadHash = computeReplayPayloadHash(event.payload, payloadHashAlgorithm);\n\t\tconst chained: Omit<ReplayEvent, \"eventHash\"> = {\n\t\t\t...event,\n\t\t\tseq: expectedHead.lastSeq + 1,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayloadHashAlgorithm,\n\t\t\tpayloadHash,\n\t\t\tprevHash: expectedHead.lastHash,\n\t\t};\n\t\tconst fullEvent: ReplayEvent = { ...chained, eventHash: computeEventHash(chained) };\n\t\tthis.committedHead = this.store.append(\n\t\t\tBuffer.from(`${JSON.stringify(fullEvent)}\\n`, \"utf8\"),\n\t\t\tfullEvent.seq,\n\t\t\tfullEvent.eventHash,\n\t\t\texpectedHead,\n\t\t);\n\t\tthis.events.push(fullEvent);\n\t\treturn structuredClone(fullEvent);\n\t}\n\n\t/** Compatibility no-op that still verifies the caller's expected committed head. */\n\tpersist(expectedHead: ReplayLedgerHead = this.committedHead): void {\n\t\tthis.getVerifiedSnapshot(expectedHead);\n\t}\n\n\tload(expectedHead: ReplayLedgerHead = this.committedHead): void {\n\t\tthis.refresh(expectedHead);\n\t}\n\n\tgetCommittedHead(): ReplayLedgerHead {\n\t\treturn structuredClone(this.committedHead);\n\t}\n\n\tgetVerifiedSnapshot(expectedHead: ReplayLedgerHead = this.committedHead): VerifiedReplayLedgerSnapshot {\n\t\tthis.refresh(expectedHead);\n\t\treturn structuredClone({ events: this.events, head: this.committedHead });\n\t}\n\n\tgetEvents(): ReadonlyArray<ReplayEvent> {\n\t\treturn structuredClone(this.events);\n\t}\n\n\tgetLedger(): Readonly<ReplayLedger> {\n\t\treturn structuredClone({\n\t\t\tgoalId: this.goalId,\n\t\t\tevents: this.events,\n\t\t\tledgerPath: this.ledgerPath,\n\t\t\tlastPersistedSeq: this.committedHead.lastSeq,\n\t\t});\n\t}\n\n\treplay<T>(handler: (event: ReplayEvent) => T | undefined): T[] {\n\t\treturn this.events.map(handler).filter((result): result is T => result !== undefined);\n\t}\n\n\texportToFile(path: string): void {\n\t\tensureDir(path);\n\t\twriteFileSync(path, JSON.stringify(this.events, null, 2), \"utf8\");\n\t}\n}\n\n// ============================================================================\n// EvidenceGate\n// ============================================================================\n\nexport interface EvidenceGateOptions {\n\t/** Minimum number of satisfied evidence items required. */\n\tminEvidenceCount?: number;\n\t/** Require at least one artifact with a SHA-256 hash in explicit legacy mode. */\n\trequireHash?: boolean;\n\t/** Require at least one verification command in explicit legacy mode. */\n\trequireVerificationCommand?: boolean;\n\t/** Receipt policy. Defaults to prefer; legacy must be selected explicitly. */\n\treceiptMode?: EvidenceReceiptMode;\n\t/** Resolve a serialized or decoded receipt by ID. The gate validates the returned value. */\n\tresolveReceipt?: (receiptId: string) => unknown;\n\t/** Strict source: one expected-head, file-identity, suffix, and chain-verified snapshot. */\n\tresolveVerifiedLedgerSnapshot?: () => VerifiedReplayLedgerSnapshot;\n\t/** Prefer-mode migration source; strict mode requires resolveVerifiedLedgerSnapshot. */\n\tresolveLedgerEvent?: (seq: number) => ReplayEvent | undefined;\n\t/** Recapture the receipt's workspace scope (same kind and scope) for freshness comparison. */\n\tcaptureWorkspaceFingerprint?: (scope: WorkspaceScope) => unknown;\n\t/**\n\t * Optional freshness source: the latest replay-ledger sequence of a workspace mutation\n\t * relevant to the given scope, or null/undefined when none is known. When configured,\n\t * the receipt's verified ledger seq must strictly exceed this value; a throwing or\n\t * out-of-contract source is a hard block (positive safe integers only).\n\t */\n\tresolveLatestWorkspaceMutationSeq?: (scope: WorkspaceScope) => number | null | undefined;\n\t/** Ephemeral trust anchor used to verify the original command's keyed attestation. */\n\tcommandAttestationBinder?: Pick<CommandHmacBinder, \"verify\">;\n\t/** Resolve the original command inside the same trust boundary as the binder. */\n\tresolveAttestedCommand?: (receiptId: string) => EvidenceCommandDescriptor | undefined;\n}\n\ninterface ReceiptCheckIssue {\n\treadonly message: string;\n\treadonly hard: boolean;\n}\n\nfunction receiptCheckIssue(message: string, hard: boolean): ReceiptCheckIssue {\n\treturn { message, hard };\n}\n\nfunction receiptIssue(\n\titem: EvidenceItem,\n\tcontract: TaskContract,\n\toptions: EvidenceGateOptions,\n): ReceiptCheckIssue | undefined {\n\tif (!item.receiptId) {\n\t\treturn receiptCheckIssue(`Execution receipt is missing for evidence \"${item.claim}\".`, false);\n\t}\n\tconst strict = options.receiptMode === \"strict\";\n\tif (item.receiptSchemaVersion !== 3 && (item.receiptSchemaVersion !== undefined || strict)) {\n\t\treturn receiptCheckIssue(`Execution receipt schema metadata is invalid for evidence \"${item.claim}\".`, true);\n\t}\n\tif (!options.resolveReceipt) {\n\t\treturn receiptCheckIssue(`Execution receipt resolver is missing for evidence \"${item.claim}\".`, false);\n\t}\n\n\tlet rawReceipt: unknown;\n\ttry {\n\t\trawReceipt = options.resolveReceipt(item.receiptId);\n\t} catch {\n\t\treturn receiptCheckIssue(`Execution receipt resolver failed for evidence \"${item.claim}\".`, true);\n\t}\n\tif (rawReceipt === undefined) {\n\t\treturn receiptCheckIssue(`Execution receipt is missing for evidence \"${item.claim}\".`, false);\n\t}\n\n\ttry {\n\t\tconst receipt = validateEvidenceReceipt(rawReceipt);\n\t\tif (receipt.core.receiptId !== item.receiptId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt ID does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.goalId !== contract.goalId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt goal does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.claim !== item.claim) {\n\t\t\treturn receiptCheckIssue(`Execution receipt claim does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (receipt.core.status !== \"passed\" || receipt.core.exitCode !== 0) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt for evidence \"${item.claim}\" did not pass with exit code 0.`,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t}\n\n\t\tif (item.receiptCommandSha256 === undefined) {\n\t\t\treturn receiptCheckIssue(`Execution receipt command binding is missing for evidence \"${item.claim}\".`, false);\n\t\t}\n\t\tconst receiptCommandSha256 = computeEvidenceCommandSha256(receipt.core.command);\n\t\tif (!constantTimeSha256Equal(item.receiptCommandSha256, receiptCommandSha256)) {\n\t\t\treturn receiptCheckIssue(`Execution receipt command does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tconst attestationIssue = verifyCommandAttestation({\n\t\t\treceiptId: receipt.core.receiptId,\n\t\t\tbinding: receipt.core.commandBinding,\n\t\t\tpersistedCommand: receipt.core.command,\n\t\t\tpersistedSummary: receipt.core.commandRedaction,\n\t\t\tbinder: options.commandAttestationBinder,\n\t\t\tresolveCommand: options.resolveAttestedCommand,\n\t\t\tredact: redactCommandDescriptor,\n\t\t});\n\t\tif (attestationIssue !== undefined) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt command attestation ${attestationIssue.detail} for evidence \"${item.claim}\".`,\n\t\t\t\tattestationIssue.hard,\n\t\t\t);\n\t\t}\n\n\t\tif (receipt.core.laneId !== undefined && item.receiptLaneId === undefined) {\n\t\t\treturn receiptCheckIssue(`Execution receipt lane binding is missing for evidence \"${item.claim}\".`, false);\n\t\t}\n\t\tif (item.receiptLaneId !== receipt.core.laneId) {\n\t\t\treturn receiptCheckIssue(`Execution receipt lane does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\n\t\tconst workspaceIssue = verifyWorkspaceBinding(receipt.core.workspaceAfter, options.captureWorkspaceFingerprint);\n\t\tif (workspaceIssue !== undefined) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ${workspaceIssue.detail} for evidence \"${item.claim}\".`,\n\t\t\t\tworkspaceIssue.hard,\n\t\t\t);\n\t\t}\n\n\t\tlet snapshot: VerifiedReplayLedgerSnapshot | undefined;\n\t\tif (options.resolveVerifiedLedgerSnapshot !== undefined) {\n\t\t\ttry {\n\t\t\t\tsnapshot = parseVerifiedLedgerSnapshot(\n\t\t\t\t\toptions.resolveVerifiedLedgerSnapshot(),\n\t\t\t\t\tcontract.goalId,\n\t\t\t\t\tparseReplayLedgerBytes,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t`Execution receipt verified ledger snapshot failed for evidence \"${item.claim}\".`,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (strict) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt verified ledger snapshot is missing for evidence \"${item.claim}\".`,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tlet latestMutationSeq =\n\t\t\tsnapshot === undefined\n\t\t\t\t? null\n\t\t\t\t: latestRelevantWorkspaceMutationSeq(snapshot.events, receipt.core.workspaceAfter.scope);\n\t\tif (snapshot === undefined && options.resolveLatestWorkspaceMutationSeq !== undefined) {\n\t\t\tlet resolved: unknown;\n\t\t\ttry {\n\t\t\t\tresolved = options.resolveLatestWorkspaceMutationSeq(receipt.core.workspaceAfter.scope);\n\t\t\t} catch {\n\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t`Execution receipt workspace-mutation freshness source failed for evidence \"${item.claim}\".`,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (resolved !== null && resolved !== undefined) {\n\t\t\t\tif (!Number.isSafeInteger(resolved) || (resolved as number) <= 0) {\n\t\t\t\t\treturn receiptCheckIssue(\n\t\t\t\t\t\t`Execution receipt workspace-mutation freshness source is malformed for evidence \"${item.claim}\".`,\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlatestMutationSeq = resolved as number;\n\t\t\t}\n\t\t}\n\n\t\tconst binding = receipt.envelope.ledgerBinding;\n\t\tif (!binding) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ledger binding is missing for evidence \"${item.claim}\".`,\n\t\t\t\tlatestMutationSeq !== null,\n\t\t\t);\n\t\t}\n\t\tconst event = snapshot\n\t\t\t? snapshot.events.find((candidate) => candidate.seq === binding.seq)\n\t\t\t: options.resolveLedgerEvent?.(binding.seq);\n\t\tif (!event && snapshot === undefined && !options.resolveLedgerEvent) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt ledger resolver is missing for evidence \"${item.claim}\".`,\n\t\t\t\tlatestMutationSeq !== null,\n\t\t\t);\n\t\t}\n\t\tconst replayPayload = evidenceReceiptReplayPayload(receipt);\n\t\tif (\n\t\t\t!event ||\n\t\t\tevent.seq !== binding.seq ||\n\t\t\tevent.type !== \"evidence_receipt\" ||\n\t\t\tevent.goalId !== contract.goalId ||\n\t\t\tevent.laneId !== receipt.core.laneId ||\n\t\t\t!constantTimeSha256Equal(event.eventHash, binding.eventHash) ||\n\t\t\t!replayPayloadMatches(event.payload, replayPayload.receiptId, replayPayload.coreSha256)\n\t\t) {\n\t\t\treturn receiptCheckIssue(`Execution receipt ledger binding does not match evidence \"${item.claim}\".`, true);\n\t\t}\n\t\tif (latestMutationSeq !== null && event.seq <= latestMutationSeq) {\n\t\t\treturn receiptCheckIssue(\n\t\t\t\t`Execution receipt is stale: workspace mutation seq ${latestMutationSeq} does not precede receipt ledger seq ${event.seq} for evidence \"${item.claim}\".`,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t}\n\t} catch {\n\t\treturn receiptCheckIssue(`Execution receipt is invalid for evidence \"${item.claim}\".`, true);\n\t}\n\treturn undefined;\n}\n\nexport class EvidenceGate {\n\tprivate options: EvidenceGateOptions;\n\n\tconstructor(options: EvidenceGateOptions = {}) {\n\t\tthis.options = {\n\t\t\tminEvidenceCount: 1,\n\t\t\trequireHash: true,\n\t\t\trequireVerificationCommand: true,\n\t\t\treceiptMode: \"prefer\",\n\t\t\t...options,\n\t\t};\n\t}\n\n\tcheck(contract: TaskContract): MergeGateResult {\n\t\tconst evidence = contract.requiredEvidence;\n\t\tconst satisfied = evidence.filter((e) => e.status === \"satisfied\");\n\t\tconst failed = evidence.filter((e) => e.status === \"failed\");\n\t\tconst pending = evidence.filter((e) => e.status === \"pending\" || e.status === \"gathering\");\n\t\tconst mode = this.options.receiptMode ?? \"prefer\";\n\t\tconst checks: string[] = [];\n\t\tlet hardReceiptFailure = false;\n\n\t\tif (satisfied.length < (this.options.minEvidenceCount ?? 1)) {\n\t\t\tchecks.push(`Only ${satisfied.length}/${this.options.minEvidenceCount} required evidence items satisfied.`);\n\t\t}\n\t\tif (failed.length > 0) {\n\t\t\tchecks.push(`${failed.length} evidence item(s) failed.`);\n\t\t}\n\n\t\tif (mode === \"legacy\") {\n\t\t\tif (this.options.requireHash) {\n\t\t\t\tconst hashed = satisfied.filter((e) => e.hash && e.hash.length > 0);\n\t\t\t\tif (hashed.length === 0) checks.push(\"No satisfied evidence has a SHA-256 hash.\");\n\t\t\t}\n\t\t\tif (this.options.requireVerificationCommand) {\n\t\t\t\tconst withCommand = satisfied.filter((e) => e.verificationCommand && e.verificationCommand.length > 0);\n\t\t\t\tif (withCommand.length === 0) checks.push(\"No satisfied evidence has a verification command.\");\n\t\t\t}\n\t\t} else {\n\t\t\tconst unsatisfied = evidence.filter((item) => item.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\tchecks.push(`${unsatisfied.length} required evidence item(s) are not satisfied.`);\n\t\t\t}\n\t\t\tfor (const item of satisfied) {\n\t\t\t\tconst issue = receiptIssue(item, contract, this.options);\n\t\t\t\tif (issue) {\n\t\t\t\t\tchecks.push(issue.message);\n\t\t\t\t\thardReceiptFailure ||= issue.hard;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (contract.verdict === \"fail\" || (mode !== \"legacy\" && contract.verdict !== \"pass\")) {\n\t\t\tchecks.push(`Task contract verdict is '${contract.verdict}'.`);\n\t\t}\n\n\t\tlet status: MergeGateStatus;\n\t\tlet reason: string;\n\t\tlet suggestion: string | undefined;\n\t\tif (checks.length === 0) {\n\t\t\tstatus = \"open\";\n\t\t\treason = `Evidence gate passed: ${satisfied.length}/${evidence.length} evidence items satisfied.`;\n\t\t} else {\n\t\t\tconst contractFailure = mode === \"legacy\" ? contract.verdict === \"fail\" : contract.verdict !== \"pass\";\n\t\t\tconst hasHardFailure = failed.length > 0 || contractFailure || hardReceiptFailure || mode === \"strict\";\n\t\t\tstatus = hasHardFailure ? \"blocked\" : mode === \"prefer\" || pending.length > 0 ? \"conditional\" : \"blocked\";\n\t\t\treason = checks.join(\"; \");\n\t\t\tsuggestion = `Gather remaining evidence (${pending.length} pending) and re-run verification.`;\n\t\t}\n\n\t\treturn {\n\t\t\tgateId: \"evidence-gate\",\n\t\t\tstatus,\n\t\t\treason,\n\t\t\tsuggestion,\n\t\t\tevidenceChecked: evidence,\n\t\t};\n\t}\n}\n\n// ============================================================================\n// FailClosedMergeGate\n// ============================================================================\n\nexport class FailClosedMergeGate {\n\tprivate readonly gates: readonly EvidenceGate[];\n\n\tconstructor(gates: EvidenceGate[] = [new EvidenceGate()]) {\n\t\tif (!Array.isArray(gates) || gates.length === 0) throw new TypeError(\"At least one evidence gate is required\");\n\t\tthis.gates = Object.freeze(\n\t\t\tArray.from(gates, (gate) => {\n\t\t\t\tif (!(gate instanceof EvidenceGate)) throw new TypeError(\"Invalid evidence gate\");\n\t\t\t\treturn gate;\n\t\t\t}),\n\t\t);\n\t}\n\n\tcheck(contract: TaskContract): MergeGateResult {\n\t\treturn combineMergeGateResults(\n\t\t\tcontract,\n\t\t\tthis.gates.map((gate) => gate.check(contract)),\n\t\t);\n\t}\n}\n\n// ============================================================================\n// Verify Reporter v2\n// ============================================================================\n\n/** Escape pipes/newlines so untrusted claim or command text cannot restructure the report table. */\nfunction escapeTableCell(value: string): string {\n\treturn value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n}\n\nexport interface VerifyReporterV2Options {\n\toutputDir: string;\n\tgoalId: string;\n}\n\nexport class VerifyReporterV2 {\n\tprivate options: VerifyReporterV2Options;\n\n\tconstructor(options: VerifyReporterV2Options) {\n\t\tthis.options = options;\n\t}\n\n\trender(contract: TaskContract, mergeGate: MergeGateResult): string {\n\t\tconst lines: string[] = [\n\t\t\t`## OMK Verification Report v2 — ${contract.goalId}`,\n\t\t\t\"\",\n\t\t\t\"### Contract\",\n\t\t\t\"\",\n\t\t\t`| Field | Value |`,\n\t\t\t`|-------|-------|`,\n\t\t\t`| Claim | ${escapeTableCell(contract.completionClaim)} |`,\n\t\t\t`| Verdict | ${contract.verdict} |`,\n\t\t\t`| Final Risk | ${escapeTableCell(contract.finalRisk)} |`,\n\t\t\t\"\",\n\t\t\t\"### Evidence\",\n\t\t\t\"\",\n\t\t\t`| Claim | Status | Artifact | Command |`,\n\t\t\t`|-------|--------|----------|----------|`,\n\t\t];\n\n\t\tfor (const ev of contract.requiredEvidence) {\n\t\t\tlines.push(\n\t\t\t\t`| ${escapeTableCell(ev.claim)} | ${ev.status} | ${escapeTableCell(ev.artifactPath ?? \"—\")} | ${escapeTableCell(ev.verificationCommand ?? \"—\")} |`,\n\t\t\t);\n\t\t}\n\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"### Merge Gate\",\n\t\t\t\"\",\n\t\t\t`| Gate | Status | Reason |`,\n\t\t\t`|------|--------|--------|`,\n\t\t\t`| ${mergeGate.gateId} | ${mergeGate.status} | ${escapeTableCell(mergeGate.reason)} |`,\n\t\t\t\"\",\n\t\t);\n\n\t\tif (mergeGate.suggestion) {\n\t\t\tlines.push(`**Suggestion:** ${mergeGate.suggestion}`, \"\");\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\twrite(contract: TaskContract, mergeGate: MergeGateResult): string {\n\t\tconst markdown = this.render(contract, mergeGate);\n\t\tconst path = join(this.options.outputDir, `${this.options.goalId}.verify.md`);\n\t\tensureDir(path);\n\t\twriteFileSync(path, markdown, \"utf-8\");\n\t\treturn path;\n\t}\n}\n"]}
|
|
@@ -6,6 +6,7 @@ import { redactCommandDescriptor } from "./command-redaction.js";
|
|
|
6
6
|
import { latestRelevantWorkspaceMutationSeq, parseVerifiedLedgerSnapshot, replayPayloadMatches, verifyCommandAttestation, verifyWorkspaceBinding, } from "./evidence-attestation.js";
|
|
7
7
|
export { latestRelevantWorkspaceMutationSeq } from "./evidence-attestation.js";
|
|
8
8
|
import { computeEvidenceCommandSha256, constantTimeSha256Equal, evidenceReceiptReplayPayload, parseSha256Hex, validateEvidenceReceipt, } from "./evidence-receipt.js";
|
|
9
|
+
import { combineMergeGateResults } from "./merge-gate-result.js";
|
|
9
10
|
import { ReplayLedgerStore, replayLedgerHeadsEqual } from "./replay-ledger-store.js";
|
|
10
11
|
import { computeReplayPayloadHash, JCS_REPLAY_PAYLOAD_HASH_ALGORITHM, LEGACY_REPLAY_PAYLOAD_HASH_ALGORITHM, } from "./replay-payload-hash.js";
|
|
11
12
|
function sha256(input) {
|
|
@@ -86,7 +87,15 @@ export class TaskContractBuilder {
|
|
|
86
87
|
}
|
|
87
88
|
/** Parse and validate a serialized TaskContract. Fails closed on any shape violation. */
|
|
88
89
|
static fromJSON(json) {
|
|
89
|
-
|
|
90
|
+
let raw;
|
|
91
|
+
try {
|
|
92
|
+
raw = JSON.parse(json);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error instanceof SyntaxError)
|
|
96
|
+
throw new SyntaxError("Invalid TaskContract JSON");
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
90
99
|
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
91
100
|
throw new Error("TaskContract JSON must be an object");
|
|
92
101
|
}
|
|
@@ -525,36 +534,16 @@ export class EvidenceGate {
|
|
|
525
534
|
export class FailClosedMergeGate {
|
|
526
535
|
gates;
|
|
527
536
|
constructor(gates = [new EvidenceGate()]) {
|
|
528
|
-
|
|
537
|
+
if (!Array.isArray(gates) || gates.length === 0)
|
|
538
|
+
throw new TypeError("At least one evidence gate is required");
|
|
539
|
+
this.gates = Object.freeze(Array.from(gates, (gate) => {
|
|
540
|
+
if (!(gate instanceof EvidenceGate))
|
|
541
|
+
throw new TypeError("Invalid evidence gate");
|
|
542
|
+
return gate;
|
|
543
|
+
}));
|
|
529
544
|
}
|
|
530
545
|
check(contract) {
|
|
531
|
-
|
|
532
|
-
const blocked = results.filter((r) => r.status === "blocked");
|
|
533
|
-
const conditional = results.filter((r) => r.status === "conditional");
|
|
534
|
-
if (blocked.length > 0) {
|
|
535
|
-
return {
|
|
536
|
-
gateId: "fail-closed-merge-gate",
|
|
537
|
-
status: "blocked",
|
|
538
|
-
reason: `Blocked by ${blocked.length} gate(s): ${blocked.map((b) => b.reason).join("; ")}`,
|
|
539
|
-
suggestion: "Resolve all blocking conditions before merge.",
|
|
540
|
-
evidenceChecked: contract.requiredEvidence,
|
|
541
|
-
};
|
|
542
|
-
}
|
|
543
|
-
if (conditional.length > 0) {
|
|
544
|
-
return {
|
|
545
|
-
gateId: "fail-closed-merge-gate",
|
|
546
|
-
status: "conditional",
|
|
547
|
-
reason: `Conditional pass: ${conditional.length} gate(s) have pending conditions.`,
|
|
548
|
-
suggestion: "Complete pending evidence or waive with explicit approval.",
|
|
549
|
-
evidenceChecked: contract.requiredEvidence,
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
return {
|
|
553
|
-
gateId: "fail-closed-merge-gate",
|
|
554
|
-
status: "open",
|
|
555
|
-
reason: "All merge gates passed. Evidence verified and contract verdict is acceptable.",
|
|
556
|
-
evidenceChecked: contract.requiredEvidence,
|
|
557
|
-
};
|
|
546
|
+
return combineMergeGateResults(contract, this.gates.map((gate) => gate.check(contract)));
|
|
558
547
|
}
|
|
559
548
|
}
|
|
560
549
|
// ============================================================================
|