minicode-ai 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -66
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +17 -7
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +54 -18
- package/src/ui/i18n/en.ts +62 -6
- package/src/ui/i18n/id.ts +62 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +598 -133
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -165
- package/docs/USAGE.md +0 -11
|
@@ -0,0 +1,1623 @@
|
|
|
1
|
+
// P2.10 — canonical execution evidence and explicit external-effect observation.
|
|
2
|
+
//
|
|
3
|
+
// Layering:
|
|
4
|
+
// - ToolInvocationId = application-owned invocation identity.
|
|
5
|
+
// - EffectIntent = durable pre-effect record in the existing mutation journal.
|
|
6
|
+
// - EffectReceipt = durable post-execution terminal in the same journal.
|
|
7
|
+
// - VerificationRecord = a separate durable journal record produced ONLY by
|
|
8
|
+
// explicit observation. Untrusted prose and unrelated lifecycle,
|
|
9
|
+
// observation, authorization, or persistence-watermark authorities are never
|
|
10
|
+
// accepted as effect proof.
|
|
11
|
+
// - Idempotency reuses outcome.note, following the proven MCP-server pattern.
|
|
12
|
+
// - Child effect correlation reads child-journal evidence and explicit child
|
|
13
|
+
// observation; it never treats delegation prose as effect evidence.
|
|
14
|
+
//
|
|
15
|
+
// This module writes only journal evidence. It never writes conversation,
|
|
16
|
+
// derived, observation, lifecycle, or watermark stores. It also never imports
|
|
17
|
+
// presentation, context, persistence, task, or CLI modules.
|
|
18
|
+
|
|
19
|
+
import { spawnSync } from "node:child_process"
|
|
20
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
21
|
+
import { isAbsolute, relative, resolve } from "node:path"
|
|
22
|
+
import type { Tool, ToolContext } from "#minicore"
|
|
23
|
+
import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
|
|
24
|
+
import { safeReadFile, safeStat } from "../lib/safe-open.ts"
|
|
25
|
+
import { sanitizeSessionPart } from "../lib/session-id.ts"
|
|
26
|
+
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
27
|
+
import { scrubSecrets } from "../policy/scrub.ts"
|
|
28
|
+
import type { VerifyResult } from "../policy/verifier.ts"
|
|
29
|
+
import {
|
|
30
|
+
appendMutationIntent,
|
|
31
|
+
appendMutationTerminal,
|
|
32
|
+
appendVerificationRecord,
|
|
33
|
+
type ChildResultEnvelope,
|
|
34
|
+
type ChildStatus,
|
|
35
|
+
hashArgs,
|
|
36
|
+
isCanonicalEvidenceCovered,
|
|
37
|
+
isJournalHealthy,
|
|
38
|
+
isVerificationMethod,
|
|
39
|
+
type JournalOutcome,
|
|
40
|
+
type JournalRecord,
|
|
41
|
+
loadJournal,
|
|
42
|
+
type VerificationMethod,
|
|
43
|
+
type VerificationVerdict,
|
|
44
|
+
verifyPaths,
|
|
45
|
+
} from "./journal.ts"
|
|
46
|
+
|
|
47
|
+
// Status observasi anak dipakai pemanggil delegate (tipe milik journal,
|
|
48
|
+
// diekspor ulang agar factory receipt punya satu seam bukti).
|
|
49
|
+
export type { ChildStatus } from "./journal.ts"
|
|
50
|
+
|
|
51
|
+
import { isGitRepo } from "./shadow-git.ts"
|
|
52
|
+
|
|
53
|
+
const MAX_ID = 200
|
|
54
|
+
const MAX_ACK = 200
|
|
55
|
+
const GIT_OBSERVE_TIMEOUT_MS = 10_000
|
|
56
|
+
const SHA_RE = /^[0-9a-f]{7,64}$/i
|
|
57
|
+
const TRUNCATION_MARKERS = ["[truncated", "[output truncated]"]
|
|
58
|
+
const BASH_EXIT_RE = /^exit (-?\d+)(?:\D|$)/
|
|
59
|
+
const GIT_HEAD_RE = /HEAD:\s*([0-9a-f]{7,40})\b/i
|
|
60
|
+
|
|
61
|
+
export type SpecialEvidencePath = "delegate-task" | "mcp-server"
|
|
62
|
+
export type EffectAckSource =
|
|
63
|
+
| "bash-exit"
|
|
64
|
+
| "sandbox-exit"
|
|
65
|
+
| "git-commit"
|
|
66
|
+
| "external-response"
|
|
67
|
+
| "absent"
|
|
68
|
+
export type ReceiptLoss = "none" | "response" | "persistence" | "unknown"
|
|
69
|
+
export type ReceiptUncertainty =
|
|
70
|
+
| "none"
|
|
71
|
+
| "ambiguous-effect"
|
|
72
|
+
| "unverified-external"
|
|
73
|
+
| "evidence-incomplete"
|
|
74
|
+
export type IdempotencyScope = "session" | "mcp"
|
|
75
|
+
export type IdempotencyStatus = "proceed" | "committed" | "failed" | "pending" | "conflict"
|
|
76
|
+
export type ChildDelegationStatus = "committed" | "failed" | "pending" | "absent"
|
|
77
|
+
export type ChildJournalStatus = "committed" | "failed" | "pending" | "absent"
|
|
78
|
+
export type ChildVerificationStatus = "present" | "absent" | "inconclusive" | "absent-record"
|
|
79
|
+
|
|
80
|
+
export interface ToolInvocationRequestLocator {
|
|
81
|
+
tool: string
|
|
82
|
+
providerToolCallId?: string
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface ToolInvocationRequest {
|
|
86
|
+
sessionId: string
|
|
87
|
+
threadId: string
|
|
88
|
+
turnIndex?: number | null
|
|
89
|
+
tool: string
|
|
90
|
+
providerToolCallId?: string
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface ToolInvocationId {
|
|
94
|
+
version: 1
|
|
95
|
+
sessionId: string
|
|
96
|
+
threadId: string
|
|
97
|
+
turnIndex: number | null
|
|
98
|
+
tool: string
|
|
99
|
+
providerToolCallId?: string
|
|
100
|
+
allocationSequence: number
|
|
101
|
+
nonce: string
|
|
102
|
+
value: string
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface InvocationAllocation {
|
|
106
|
+
allocationSequence: number
|
|
107
|
+
nonce?: string
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function asNonEmpty(value: unknown, field: string): string {
|
|
111
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
112
|
+
throw new Error(`verification: refusing invocation without ${field}`)
|
|
113
|
+
}
|
|
114
|
+
return value
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function normalizeTurnIndex(value: unknown): number | null {
|
|
118
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normalizeProviderToolCallId(value: unknown): string | undefined {
|
|
122
|
+
if (typeof value !== "string") return undefined
|
|
123
|
+
const trimmed = value.trim()
|
|
124
|
+
if (!trimmed) return undefined
|
|
125
|
+
return scrubSecrets(trimmed).slice(0, MAX_ID)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function normalizeNonce(nonce: string | undefined): string {
|
|
129
|
+
if (typeof nonce === "string" && /^[0-9a-f]{16}$/.test(nonce)) return nonce
|
|
130
|
+
return randomUUID().replace(/-/g, "").slice(0, 16)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Application-owned invocation identity. Provider identifiers are locators only. */
|
|
134
|
+
export function allocateToolInvocationId(
|
|
135
|
+
request: ToolInvocationRequest,
|
|
136
|
+
allocation: InvocationAllocation,
|
|
137
|
+
): ToolInvocationId {
|
|
138
|
+
const sessionId = asNonEmpty(request.sessionId, "sessionId")
|
|
139
|
+
const threadId = asNonEmpty(request.threadId, "threadId")
|
|
140
|
+
const tool = asNonEmpty(request.tool, "tool")
|
|
141
|
+
const turnIndex = normalizeTurnIndex(request.turnIndex)
|
|
142
|
+
const providerToolCallId = normalizeProviderToolCallId(request.providerToolCallId)
|
|
143
|
+
if (!Number.isInteger(allocation.allocationSequence) || allocation.allocationSequence < 0) {
|
|
144
|
+
throw new Error("verification: refusing invocation without journal allocation sequence")
|
|
145
|
+
}
|
|
146
|
+
const nonce = normalizeNonce(allocation.nonce)
|
|
147
|
+
const locatorHash = createHash("sha256")
|
|
148
|
+
.update(`${tool}\u0000${providerToolCallId ?? ""}`)
|
|
149
|
+
.digest("hex")
|
|
150
|
+
.slice(0, 16)
|
|
151
|
+
const value = [
|
|
152
|
+
"inv",
|
|
153
|
+
sanitizeSessionPart(sessionId),
|
|
154
|
+
sanitizeSessionPart(threadId),
|
|
155
|
+
`t${turnIndex ?? "x"}`,
|
|
156
|
+
`s${allocation.allocationSequence}`,
|
|
157
|
+
locatorHash,
|
|
158
|
+
nonce,
|
|
159
|
+
].join(":")
|
|
160
|
+
return {
|
|
161
|
+
version: 1,
|
|
162
|
+
sessionId,
|
|
163
|
+
threadId,
|
|
164
|
+
turnIndex,
|
|
165
|
+
tool,
|
|
166
|
+
...(providerToolCallId ? { providerToolCallId } : {}),
|
|
167
|
+
allocationSequence: allocation.allocationSequence,
|
|
168
|
+
nonce,
|
|
169
|
+
value,
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export interface EffectIntentRequest {
|
|
174
|
+
sessionId: string
|
|
175
|
+
threadId: string
|
|
176
|
+
turnIndex?: number | null
|
|
177
|
+
tool: string
|
|
178
|
+
providerToolCallId?: string
|
|
179
|
+
cwd: string
|
|
180
|
+
childOf?: string
|
|
181
|
+
args?: unknown
|
|
182
|
+
paths?: string[]
|
|
183
|
+
idempotencyKey?: string
|
|
184
|
+
idempotencyScope?: IdempotencyScope
|
|
185
|
+
childSessionId?: string
|
|
186
|
+
specialPath?: SpecialEvidencePath
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface EffectIntentResult {
|
|
190
|
+
invocation: ToolInvocationId
|
|
191
|
+
record: JournalRecord
|
|
192
|
+
argsHash: string
|
|
193
|
+
idempotencyKey?: string
|
|
194
|
+
durable: boolean
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function normalizeIdempotencyKey(
|
|
198
|
+
sessionId: string,
|
|
199
|
+
key: unknown,
|
|
200
|
+
scope: IdempotencyScope = "session",
|
|
201
|
+
): string {
|
|
202
|
+
if (scope === "mcp") {
|
|
203
|
+
// Preserve the proven MCP request/id + args-hash key byte-for-byte.
|
|
204
|
+
if (typeof key !== "string" || !key) {
|
|
205
|
+
throw new Error("verification: refusing MCP intent without idempotency key")
|
|
206
|
+
}
|
|
207
|
+
return key
|
|
208
|
+
}
|
|
209
|
+
if (typeof key !== "string" || !key.trim()) {
|
|
210
|
+
throw new Error("verification: refusing intent without idempotency key")
|
|
211
|
+
}
|
|
212
|
+
const safe = scrubSecrets(key.trim()).slice(0, MAX_ID)
|
|
213
|
+
if (!safe) throw new Error("verification: refusing empty idempotency key")
|
|
214
|
+
return `p210:intent:session:${sanitizeSessionPart(sessionId)}:${safe}`
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function requireWorkspaceRoot(cwd: unknown): string {
|
|
218
|
+
// Evidence storage must use an explicit workspace. ToolContext.cwd remains
|
|
219
|
+
// the authority for file effects; this root only selects the journal file.
|
|
220
|
+
if (typeof cwd !== "string" || !cwd) {
|
|
221
|
+
throw new Error("verification: refusing evidence without explicit workspace root")
|
|
222
|
+
}
|
|
223
|
+
return resolve(cwd)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Write one canonical pre-effect intent and await its durable result. */
|
|
227
|
+
export async function persistEffectIntent(
|
|
228
|
+
request: EffectIntentRequest,
|
|
229
|
+
): Promise<EffectIntentResult> {
|
|
230
|
+
const tool = asNonEmpty(request.tool, "tool")
|
|
231
|
+
if (request.specialPath === undefined && !isCanonicalEvidenceCovered(tool)) {
|
|
232
|
+
throw new Error(`verification: refusing intent for non-covered tool ${tool}`)
|
|
233
|
+
}
|
|
234
|
+
if (request.specialPath === "delegate-task" && tool !== "delegate_task") {
|
|
235
|
+
throw new Error("verification: delegate-task special path requires delegate_task")
|
|
236
|
+
}
|
|
237
|
+
const sessionId = asNonEmpty(request.sessionId, "sessionId")
|
|
238
|
+
const threadId = asNonEmpty(request.threadId, "threadId")
|
|
239
|
+
const root = requireWorkspaceRoot(request.cwd)
|
|
240
|
+
const argsHash = hashArgs(request.args ?? {})
|
|
241
|
+
const idempotencyKey = request.idempotencyKey
|
|
242
|
+
? normalizeIdempotencyKey(
|
|
243
|
+
sessionId,
|
|
244
|
+
request.idempotencyKey,
|
|
245
|
+
request.idempotencyScope ?? "session",
|
|
246
|
+
)
|
|
247
|
+
: undefined
|
|
248
|
+
const providerToolCallId = normalizeProviderToolCallId(request.providerToolCallId)
|
|
249
|
+
const nonce = randomUUID().replace(/-/g, "").slice(0, 16)
|
|
250
|
+
const record = await appendMutationIntent({
|
|
251
|
+
session: sessionId,
|
|
252
|
+
...(request.childOf ? { childOf: request.childOf } : {}),
|
|
253
|
+
turn: normalizeTurnIndex(request.turnIndex),
|
|
254
|
+
tool,
|
|
255
|
+
threadId,
|
|
256
|
+
providerToolCallId,
|
|
257
|
+
allocateInvocationId: (allocationSequence) =>
|
|
258
|
+
allocateToolInvocationId(
|
|
259
|
+
{
|
|
260
|
+
sessionId,
|
|
261
|
+
threadId,
|
|
262
|
+
turnIndex: normalizeTurnIndex(request.turnIndex),
|
|
263
|
+
tool,
|
|
264
|
+
...(providerToolCallId ? { providerToolCallId } : {}),
|
|
265
|
+
},
|
|
266
|
+
{ allocationSequence, nonce },
|
|
267
|
+
).value,
|
|
268
|
+
cwd: root,
|
|
269
|
+
paths: request.paths ?? verifyPaths(tool, request.args ?? {}, root),
|
|
270
|
+
argsHash,
|
|
271
|
+
...(request.childSessionId ? { childSessionId: request.childSessionId } : {}),
|
|
272
|
+
...(idempotencyKey ? { note: idempotencyKey } : {}),
|
|
273
|
+
})
|
|
274
|
+
const invocation = allocateToolInvocationId(
|
|
275
|
+
{
|
|
276
|
+
sessionId,
|
|
277
|
+
threadId,
|
|
278
|
+
turnIndex: normalizeTurnIndex(request.turnIndex),
|
|
279
|
+
tool,
|
|
280
|
+
...(providerToolCallId ? { providerToolCallId } : {}),
|
|
281
|
+
},
|
|
282
|
+
{ allocationSequence: record.seq, nonce },
|
|
283
|
+
)
|
|
284
|
+
const durable = isJournalHealthy(sessionId, root)
|
|
285
|
+
return { invocation, record, argsHash, ...(idempotencyKey ? { idempotencyKey } : {}), durable }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export interface ObservedAck {
|
|
289
|
+
ack: string | number | boolean | null
|
|
290
|
+
ackSource: EffectAckSource
|
|
291
|
+
ackAuthority?: "application-observed"
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function extractObservedAck(tool: string, result: unknown): ObservedAck {
|
|
295
|
+
const absent: ObservedAck = { ack: null, ackSource: "absent" }
|
|
296
|
+
if (typeof result !== "string") return absent
|
|
297
|
+
if (tool === "bash" || tool === "code_run") {
|
|
298
|
+
const match = BASH_EXIT_RE.exec(result)
|
|
299
|
+
if (!match) return absent
|
|
300
|
+
const code = Number(match[1])
|
|
301
|
+
if (!Number.isFinite(code)) return absent
|
|
302
|
+
return {
|
|
303
|
+
ack: code,
|
|
304
|
+
ackSource: tool === "bash" ? "bash-exit" : "sandbox-exit",
|
|
305
|
+
ackAuthority: "application-observed",
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (tool === "git_commit") {
|
|
309
|
+
const match = GIT_HEAD_RE.exec(result)
|
|
310
|
+
if (!match?.[1]) return absent
|
|
311
|
+
return {
|
|
312
|
+
ack: match[1],
|
|
313
|
+
ackSource: "git-commit",
|
|
314
|
+
ackAuthority: "application-observed",
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
// Delegation text, MCP prose, and file-tool prose are observations, not
|
|
318
|
+
// structured external acknowledgements. Keep them absent rather than guess.
|
|
319
|
+
return absent
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function hasTruncationMarker(result: unknown): boolean {
|
|
323
|
+
return typeof result === "string" && TRUNCATION_MARKERS.some((marker) => result.includes(marker))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Batas ringkasan amplop anak (P9.2.1): SAMA dengan batas string parent
|
|
328
|
+
* `slice(0, 2000)` di pemanggil (satuan code-unit UTF-16 — `length`/`slice`
|
|
329
|
+
* JS memang berhitung begitu). Durable menyimpan apa yang dilihat parent,
|
|
330
|
+
* bukan lebih. Bukan limit retensi/transkrip baru.
|
|
331
|
+
*/
|
|
332
|
+
export const CHILD_RESULT_SUMMARY_MAX = 2_000
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Klasifikasi observasi turn anak dari error terstruktur (P9.2.1).
|
|
336
|
+
* Hanya membaca `kind` terstruktur (taksonomi AgentError vendor) — TIDAK
|
|
337
|
+
* menebak dari wording pesan (isTimeoutOutcome/isAbortOutcome berbasis pesan
|
|
338
|
+
* sengaja tak dipakai di sini). Tanpa `kind` yang dikenal = `error`
|
|
339
|
+
* konservatif: terlihat gagal, sebab tak terpetakan. Bukan vonis kausal.
|
|
340
|
+
*/
|
|
341
|
+
export function classifyChildStatus(
|
|
342
|
+
error: unknown,
|
|
343
|
+
): "timeout" | "aborted" | "max_steps_exceeded" | "error" {
|
|
344
|
+
const kind = (error as { kind?: unknown } | null)?.kind
|
|
345
|
+
if (kind === "timeout") return "timeout"
|
|
346
|
+
if (kind === "aborted") return "aborted"
|
|
347
|
+
if (kind === "max_steps_exceeded") return "max_steps_exceeded"
|
|
348
|
+
return "error"
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Flag outcome-level untuk status anak (P9.2.1): memakai kosakata outcome
|
|
353
|
+
* yang sudah ada (`timeout`/`aborted`, konsisten dengan
|
|
354
|
+
* summarizeObservedReturn) — BUKAN status baru. Parameter bertipe gabungan
|
|
355
|
+
* penuh agar pemanggil yang variabelnya disempitkan CFA (penugasan di dalam
|
|
356
|
+
* closure tak terbaca di situs finally) tetap bisa memakainya jujur.
|
|
357
|
+
*/
|
|
358
|
+
export function childStatusOutcomeFlags(status: ChildStatus): {
|
|
359
|
+
timeout?: true
|
|
360
|
+
aborted?: true
|
|
361
|
+
} {
|
|
362
|
+
return {
|
|
363
|
+
...(status === "timeout" ? { timeout: true as const } : {}),
|
|
364
|
+
...(status === "aborted" ? { aborted: true as const } : {}),
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** [Fase 7 / LOOP-INV-13/15] Verdict consequence-engine (ACE-Lite) dari hasil anak. */
|
|
369
|
+
export interface AceResultSnapshot {
|
|
370
|
+
readonly verdict: import("../policy/consequence-engine.ts").AceVerdict
|
|
371
|
+
readonly failureClass: import("../policy/consequence-engine.ts").AceFailureClass
|
|
372
|
+
readonly nextAction: import("../policy/consequence-engine.ts").AceNextAction
|
|
373
|
+
readonly rationale?: string
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Bangun amplop hasil anak (P9.2.1): sanitasi salinan DENGAN primitif yang
|
|
378
|
+
* sudah mapan (`scrubSecrets`, sama seperti ack/evidenceReference), lalu
|
|
379
|
+
* potong ke `CHILD_RESULT_SUMMARY_MAX`. `summary` adalah string yang sudah
|
|
380
|
+
* dilihat parent (atau pesan rejection bila tak ada) — JANGAN umpan teks
|
|
381
|
+
* mentah tak terbatas ke sini; pemanggil memotong di batas parent dulu.
|
|
382
|
+
* `runId`/`steps` null bila memang tak tersedia di jalur itu.
|
|
383
|
+
* ACE verdict opsional: bila ada, disimpan bersama outcome untuk auditability.
|
|
384
|
+
*/
|
|
385
|
+
export function buildChildResultEnvelope(input: {
|
|
386
|
+
childStatus: ChildStatus
|
|
387
|
+
summary: string
|
|
388
|
+
runId: string | null
|
|
389
|
+
steps: number | null
|
|
390
|
+
aceVerdict?: AceResultSnapshot
|
|
391
|
+
}): ChildResultEnvelope {
|
|
392
|
+
const clean = scrubSecrets(input.summary)
|
|
393
|
+
const truncated = clean.length > CHILD_RESULT_SUMMARY_MAX
|
|
394
|
+
return {
|
|
395
|
+
childStatus: input.childStatus,
|
|
396
|
+
resultSummary: truncated ? clean.slice(0, CHILD_RESULT_SUMMARY_MAX) : clean,
|
|
397
|
+
runId: input.runId,
|
|
398
|
+
steps: typeof input.steps === "number" && Number.isFinite(input.steps) ? input.steps : null,
|
|
399
|
+
truncated,
|
|
400
|
+
...(input.aceVerdict !== undefined ? { aceVerdict: input.aceVerdict } : {}),
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function isSignalAborted(signal: AbortSignal | undefined): boolean {
|
|
405
|
+
return signal?.aborted === true
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function isAbortOutcome(error: unknown, signalAborted: boolean): boolean {
|
|
409
|
+
if (signalAborted) return true
|
|
410
|
+
const outcome = error as { name?: unknown; message?: unknown; code?: unknown } | null
|
|
411
|
+
if (!outcome || typeof outcome !== "object") return false
|
|
412
|
+
if (outcome.name === "AbortError" || outcome.code === "ABORT_ERR") return true
|
|
413
|
+
return outcome.message === "aborted"
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function isTimeoutOutcome(error: unknown): boolean {
|
|
417
|
+
const outcome = error as { name?: unknown; message?: unknown; code?: unknown } | null
|
|
418
|
+
if (!outcome || typeof outcome !== "object") return false
|
|
419
|
+
if (
|
|
420
|
+
outcome.name === "TimeoutError" ||
|
|
421
|
+
outcome.code === "ETIMEDOUT" ||
|
|
422
|
+
outcome.code === "TIMEOUT"
|
|
423
|
+
) {
|
|
424
|
+
return true
|
|
425
|
+
}
|
|
426
|
+
return (
|
|
427
|
+
typeof outcome.message === "string" &&
|
|
428
|
+
(/\btimed out\b/i.test(outcome.message) || /\btimeout\b/i.test(outcome.message))
|
|
429
|
+
)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Summarize an observed return without storing tool output or inferring effects. */
|
|
433
|
+
export function summarizeObservedReturn(input: {
|
|
434
|
+
tool: string
|
|
435
|
+
result?: unknown
|
|
436
|
+
error?: unknown
|
|
437
|
+
signalAborted?: boolean
|
|
438
|
+
observedAt?: number
|
|
439
|
+
}): JournalOutcome {
|
|
440
|
+
const signalAborted = input.signalAborted === true
|
|
441
|
+
const observedAt =
|
|
442
|
+
typeof input.observedAt === "number" && Number.isFinite(input.observedAt)
|
|
443
|
+
? input.observedAt
|
|
444
|
+
: Date.now()
|
|
445
|
+
if (input.error !== undefined) {
|
|
446
|
+
const aborted = isAbortOutcome(input.error, signalAborted)
|
|
447
|
+
return {
|
|
448
|
+
...(aborted ? { aborted: true as const } : {}),
|
|
449
|
+
...(!aborted && isTimeoutOutcome(input.error) ? { timeout: true as const } : {}),
|
|
450
|
+
loss: "unknown",
|
|
451
|
+
uncertainty: "ambiguous-effect",
|
|
452
|
+
observedAt,
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const ack = extractObservedAck(input.tool, input.result)
|
|
456
|
+
const outcome: JournalOutcome = {
|
|
457
|
+
loss: "none",
|
|
458
|
+
uncertainty: "unverified-external",
|
|
459
|
+
observedAt,
|
|
460
|
+
}
|
|
461
|
+
if (ack.ack !== null && ack.ack !== undefined) {
|
|
462
|
+
const value = typeof ack.ack === "string" ? scrubSecrets(ack.ack).slice(0, MAX_ACK) : ack.ack
|
|
463
|
+
return {
|
|
464
|
+
...outcome,
|
|
465
|
+
ack: value,
|
|
466
|
+
ackSource: ack.ackSource,
|
|
467
|
+
ackAuthority: "application-observed",
|
|
468
|
+
...(hasTruncationMarker(input.result) ? { truncated: true as const } : {}),
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
...outcome,
|
|
473
|
+
ack: null,
|
|
474
|
+
ackSource: "absent",
|
|
475
|
+
...(hasTruncationMarker(input.result) ? { truncated: true as const } : {}),
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export interface EffectReceiptRequest {
|
|
480
|
+
sessionId: string
|
|
481
|
+
threadId: string
|
|
482
|
+
tool: string
|
|
483
|
+
providerToolCallId?: string
|
|
484
|
+
cwd: string
|
|
485
|
+
invocation: ToolInvocationId
|
|
486
|
+
intent: Pick<JournalRecord, "id" | "seq" | "tool" | "session" | "invocationId" | "argsHash">
|
|
487
|
+
state: "committed" | "failed"
|
|
488
|
+
result?: unknown
|
|
489
|
+
error?: unknown
|
|
490
|
+
signalAborted?: boolean
|
|
491
|
+
outcome?: Omit<JournalOutcome, "observedAt"> & { observedAt?: number }
|
|
492
|
+
childSessionId?: string
|
|
493
|
+
dedup?: boolean
|
|
494
|
+
specialPath?: SpecialEvidencePath
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function findIntentRecord(
|
|
498
|
+
records: JournalRecord[],
|
|
499
|
+
request: EffectReceiptRequest,
|
|
500
|
+
): JournalRecord | undefined {
|
|
501
|
+
return records.find(
|
|
502
|
+
(record) =>
|
|
503
|
+
(!record.kind || record.kind === "mutation") &&
|
|
504
|
+
record.id === request.intent.id &&
|
|
505
|
+
record.seq === request.intent.seq &&
|
|
506
|
+
record.session === request.sessionId &&
|
|
507
|
+
record.tool === request.tool &&
|
|
508
|
+
record.invocationId === request.invocation.value,
|
|
509
|
+
)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function hasTerminalRecord(records: JournalRecord[], request: EffectReceiptRequest): boolean {
|
|
513
|
+
return records.some(
|
|
514
|
+
(record) =>
|
|
515
|
+
(!record.kind || record.kind === "mutation") &&
|
|
516
|
+
record.id === request.intent.id &&
|
|
517
|
+
(record.state === "committed" || record.state === "failed"),
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Write one canonical post-execution terminal for a durable intent. */
|
|
522
|
+
export async function persistEffectReceipt(
|
|
523
|
+
request: EffectReceiptRequest,
|
|
524
|
+
): Promise<{ durable: boolean }> {
|
|
525
|
+
const sessionId = asNonEmpty(request.sessionId, "sessionId")
|
|
526
|
+
const threadId = asNonEmpty(request.threadId, "threadId")
|
|
527
|
+
const tool = asNonEmpty(request.tool, "tool")
|
|
528
|
+
if (request.state !== "committed" && request.state !== "failed") {
|
|
529
|
+
throw new Error("verification: refusing receipt with unsupported state")
|
|
530
|
+
}
|
|
531
|
+
if (request.invocation.sessionId !== sessionId || request.invocation.tool !== tool) {
|
|
532
|
+
throw new Error("verification: refusing receipt for mismatched invocation")
|
|
533
|
+
}
|
|
534
|
+
const root = requireWorkspaceRoot(request.cwd)
|
|
535
|
+
const loaded = await loadJournal(sessionId, root)
|
|
536
|
+
if (loaded.status === "unreadable") {
|
|
537
|
+
throw new Error("verification: refusing receipt while intent evidence is unreadable")
|
|
538
|
+
}
|
|
539
|
+
const intent = findIntentRecord(loaded.records, request)
|
|
540
|
+
if (!intent) {
|
|
541
|
+
throw new Error("verification: refusing terminal without durable intent")
|
|
542
|
+
}
|
|
543
|
+
if (hasTerminalRecord(loaded.records, request)) {
|
|
544
|
+
throw new Error("verification: refusing duplicate terminal for invocation")
|
|
545
|
+
}
|
|
546
|
+
const summary = summarizeObservedReturn({
|
|
547
|
+
tool,
|
|
548
|
+
result: request.result,
|
|
549
|
+
error: request.error,
|
|
550
|
+
signalAborted: request.signalAborted,
|
|
551
|
+
observedAt: request.outcome?.observedAt,
|
|
552
|
+
})
|
|
553
|
+
const outcome: JournalOutcome = {
|
|
554
|
+
...(request.outcome?.code !== undefined ? { code: request.outcome.code } : {}),
|
|
555
|
+
...(request.outcome?.note !== undefined ? { note: request.outcome.note } : {}),
|
|
556
|
+
...(request.outcome?.ack !== undefined
|
|
557
|
+
? {
|
|
558
|
+
ack:
|
|
559
|
+
typeof request.outcome.ack === "string"
|
|
560
|
+
? scrubSecrets(request.outcome.ack).slice(0, MAX_ACK)
|
|
561
|
+
: request.outcome.ack,
|
|
562
|
+
}
|
|
563
|
+
: { ack: summary.ack ?? null }),
|
|
564
|
+
...(request.outcome?.ackSource !== undefined
|
|
565
|
+
? { ackSource: request.outcome.ackSource }
|
|
566
|
+
: { ackSource: summary.ackSource ?? "absent" }),
|
|
567
|
+
...(request.outcome?.ackAuthority !== undefined
|
|
568
|
+
? { ackAuthority: request.outcome.ackAuthority }
|
|
569
|
+
: summary.ackAuthority
|
|
570
|
+
? { ackAuthority: summary.ackAuthority }
|
|
571
|
+
: {}),
|
|
572
|
+
...(request.outcome?.truncated === true || summary.truncated === true
|
|
573
|
+
? { truncated: true as const }
|
|
574
|
+
: {}),
|
|
575
|
+
...(request.outcome?.timeout === true || summary.timeout === true
|
|
576
|
+
? { timeout: true as const }
|
|
577
|
+
: {}),
|
|
578
|
+
...(request.outcome?.aborted === true || summary.aborted === true
|
|
579
|
+
? { aborted: true as const }
|
|
580
|
+
: {}),
|
|
581
|
+
...(request.outcome?.loss !== undefined
|
|
582
|
+
? { loss: request.outcome.loss }
|
|
583
|
+
: summary.loss
|
|
584
|
+
? { loss: summary.loss }
|
|
585
|
+
: {}),
|
|
586
|
+
...(request.outcome?.uncertainty !== undefined
|
|
587
|
+
? { uncertainty: request.outcome.uncertainty }
|
|
588
|
+
: summary.uncertainty
|
|
589
|
+
? { uncertainty: summary.uncertainty }
|
|
590
|
+
: {}),
|
|
591
|
+
...(request.outcome?.observedAt !== undefined
|
|
592
|
+
? { observedAt: request.outcome.observedAt }
|
|
593
|
+
: summary.observedAt !== undefined
|
|
594
|
+
? { observedAt: summary.observedAt }
|
|
595
|
+
: {}),
|
|
596
|
+
// P9.2.1: amplop anak diteruskan eksplisit (allowlist seperti field
|
|
597
|
+
// lain di atas — JANGAN spread buta seluruh outcome). Batas + sanitasi
|
|
598
|
+
// dijamin produsen via buildChildResultEnvelope; di sini hanya
|
|
599
|
+
// penerusan agar bentuk record lama tak berubah.
|
|
600
|
+
...(request.outcome?.childResult !== undefined
|
|
601
|
+
? { childResult: request.outcome.childResult }
|
|
602
|
+
: {}),
|
|
603
|
+
}
|
|
604
|
+
await appendMutationTerminal(
|
|
605
|
+
sessionId,
|
|
606
|
+
root,
|
|
607
|
+
intent.id,
|
|
608
|
+
intent.seq,
|
|
609
|
+
tool,
|
|
610
|
+
request.state,
|
|
611
|
+
outcome,
|
|
612
|
+
request.childSessionId,
|
|
613
|
+
{
|
|
614
|
+
...(request.dedup === true || outcome.note !== undefined ? { dedup: true as const } : {}),
|
|
615
|
+
threadId,
|
|
616
|
+
invocationId: request.invocation.value,
|
|
617
|
+
...(request.providerToolCallId ? { providerToolCallId: request.providerToolCallId } : {}),
|
|
618
|
+
...(intent.argsHash ? { argsHash: intent.argsHash } : {}),
|
|
619
|
+
receipt: {
|
|
620
|
+
...(outcome.ack !== undefined ? { ack: outcome.ack } : {}),
|
|
621
|
+
...(outcome.ackSource !== undefined ? { ackSource: outcome.ackSource } : {}),
|
|
622
|
+
...(outcome.ackAuthority !== undefined ? { ackAuthority: outcome.ackAuthority } : {}),
|
|
623
|
+
...(outcome.truncated === true ? { truncated: true as const } : {}),
|
|
624
|
+
...(outcome.timeout === true ? { timeout: true as const } : {}),
|
|
625
|
+
...(outcome.aborted === true ? { aborted: true as const } : {}),
|
|
626
|
+
...(outcome.loss !== undefined ? { loss: outcome.loss } : {}),
|
|
627
|
+
...(outcome.uncertainty !== undefined ? { uncertainty: outcome.uncertainty } : {}),
|
|
628
|
+
...(outcome.observedAt !== undefined ? { observedAt: outcome.observedAt } : {}),
|
|
629
|
+
},
|
|
630
|
+
},
|
|
631
|
+
)
|
|
632
|
+
return { durable: isJournalHealthy(sessionId, root) }
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export class EvidenceIncompleteError extends Error {
|
|
636
|
+
readonly code = "REFUSED_VERIFICATION_EVIDENCE"
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
export class IdempotentDuplicateError extends Error {
|
|
640
|
+
readonly code: string
|
|
641
|
+
readonly status: Exclude<IdempotencyStatus, "proceed">
|
|
642
|
+
constructor(status: Exclude<IdempotencyStatus, "proceed">, message: string) {
|
|
643
|
+
super(message)
|
|
644
|
+
this.code =
|
|
645
|
+
status === "pending" ? "UNKNOWN_IDEMPOTENT_INVOCATION" : "REFUSED_IDEMPOTENT_DUPLICATE"
|
|
646
|
+
this.status = status
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
export function buildIdempotencyKey(sessionId: string, key: unknown): string {
|
|
651
|
+
const sid = asNonEmpty(sessionId, "sessionId")
|
|
652
|
+
if (typeof key !== "string" || !key.trim()) {
|
|
653
|
+
throw new Error("verification: refusing empty idempotency key")
|
|
654
|
+
}
|
|
655
|
+
const safe = scrubSecrets(key.trim()).slice(0, MAX_ID)
|
|
656
|
+
if (!safe) throw new Error("verification: refusing empty idempotency key")
|
|
657
|
+
return `p210:intent:session:${sanitizeSessionPart(sid)}:${safe}`
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
export interface IdempotencyLookup {
|
|
661
|
+
status: IdempotencyStatus
|
|
662
|
+
invocationId?: string
|
|
663
|
+
recordId?: string
|
|
664
|
+
message?: string
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** Durable duplicate lookup for one session-scoped idempotency key. */
|
|
668
|
+
export async function findIdempotentInvocation(input: {
|
|
669
|
+
sessionId: string
|
|
670
|
+
cwd: string
|
|
671
|
+
idempotencyKey: string
|
|
672
|
+
argsHash: string
|
|
673
|
+
}): Promise<IdempotencyLookup> {
|
|
674
|
+
const sessionId = asNonEmpty(input.sessionId, "sessionId")
|
|
675
|
+
if (typeof input.idempotencyKey !== "string" || !input.idempotencyKey) {
|
|
676
|
+
throw new Error("verification: refusing idempotency lookup without key")
|
|
677
|
+
}
|
|
678
|
+
if (typeof input.argsHash !== "string" || !input.argsHash) {
|
|
679
|
+
throw new Error("verification: refusing idempotency lookup without args hash")
|
|
680
|
+
}
|
|
681
|
+
const root = requireWorkspaceRoot(input.cwd)
|
|
682
|
+
const loaded = await loadJournal(sessionId, root)
|
|
683
|
+
if (loaded.status === "unreadable") return { status: "proceed" }
|
|
684
|
+
let exactTerminal: JournalRecord | undefined
|
|
685
|
+
let exactPending: JournalRecord | undefined
|
|
686
|
+
let conflict: JournalRecord | undefined
|
|
687
|
+
for (const record of loaded.records) {
|
|
688
|
+
if (record.outcome?.note !== input.idempotencyKey) continue
|
|
689
|
+
if ((!record.kind || record.kind === "mutation") === false) continue
|
|
690
|
+
if (record.argsHash !== input.argsHash) {
|
|
691
|
+
conflict = record
|
|
692
|
+
continue
|
|
693
|
+
}
|
|
694
|
+
if (record.state === "committed" || record.state === "failed") {
|
|
695
|
+
// First terminal wins elsewhere in recovery; keep the same rule here.
|
|
696
|
+
exactTerminal = exactTerminal ?? record
|
|
697
|
+
continue
|
|
698
|
+
}
|
|
699
|
+
if (record.state === "pending") exactPending = exactPending ?? record
|
|
700
|
+
}
|
|
701
|
+
if (exactTerminal?.state === "committed" || exactTerminal?.state === "failed") {
|
|
702
|
+
const state = exactTerminal.state
|
|
703
|
+
return {
|
|
704
|
+
status: state,
|
|
705
|
+
...(exactTerminal.invocationId ? { invocationId: exactTerminal.invocationId } : {}),
|
|
706
|
+
recordId: exactTerminal.id,
|
|
707
|
+
message:
|
|
708
|
+
state === "committed"
|
|
709
|
+
? `duplicate idempotency key: already committed — do not execute again blindly; verify state before retrying with a new key`
|
|
710
|
+
: `duplicate idempotency key: previous attempt failed — inspect state, then retry with a new key`,
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
if (exactPending) {
|
|
714
|
+
return {
|
|
715
|
+
status: "pending",
|
|
716
|
+
...(exactPending.invocationId ? { invocationId: exactPending.invocationId } : {}),
|
|
717
|
+
recordId: exactPending.id,
|
|
718
|
+
message: `duplicate idempotency key: previous attempt status unknown — verify state before retrying with a new key`,
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (conflict) {
|
|
722
|
+
return {
|
|
723
|
+
status: "conflict",
|
|
724
|
+
...(conflict.invocationId ? { invocationId: conflict.invocationId } : {}),
|
|
725
|
+
recordId: conflict.id,
|
|
726
|
+
message: `idempotency conflict: same key with different arguments — explicit refusal`,
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
return { status: "proceed" }
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
const idempotentExecutions = new Map<string, Promise<unknown>>()
|
|
733
|
+
|
|
734
|
+
async function runOncePerIdempotencyKey(key: string, runner: () => Promise<unknown>) {
|
|
735
|
+
const prior = idempotentExecutions.get(key)
|
|
736
|
+
if (prior) return prior
|
|
737
|
+
const task = (async () => runner())()
|
|
738
|
+
idempotentExecutions.set(key, task)
|
|
739
|
+
try {
|
|
740
|
+
return await task
|
|
741
|
+
} finally {
|
|
742
|
+
if (idempotentExecutions.get(key) === task) idempotentExecutions.delete(key)
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
export interface CanonicalScope {
|
|
747
|
+
sessionId: string
|
|
748
|
+
threadId: string
|
|
749
|
+
cwd: string
|
|
750
|
+
childOf?: string
|
|
751
|
+
getTurnIndex?: () => number | null
|
|
752
|
+
idempotencyKeyFor?: (tool: string, args: unknown) => string | undefined
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export interface EvidenceWriter {
|
|
756
|
+
writeIntent: (input: EffectIntentRequest) => Promise<EffectIntentResult>
|
|
757
|
+
writeReceipt: (input: EffectReceiptRequest) => Promise<{ durable: boolean }>
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const journalEvidenceWriter: EvidenceWriter = {
|
|
761
|
+
writeIntent: (input) => persistEffectIntent(input),
|
|
762
|
+
writeReceipt: (input) => persistEffectReceipt(input),
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Canonical awaited wrapper around one covered mutation-tool execution.
|
|
767
|
+
*
|
|
768
|
+
* Ordering is deliberate: awaited intent, then inner execute, then awaited
|
|
769
|
+
* receipt. Intent failure refuses execution; receipt failure preserves the
|
|
770
|
+
* observed tool outcome but leaves evidence incomplete.
|
|
771
|
+
*/
|
|
772
|
+
export async function executeCanonicalInvocation(
|
|
773
|
+
tool: Tool,
|
|
774
|
+
input: unknown,
|
|
775
|
+
ctx: ToolContext,
|
|
776
|
+
scope: CanonicalScope,
|
|
777
|
+
writer: EvidenceWriter = journalEvidenceWriter,
|
|
778
|
+
): Promise<unknown> {
|
|
779
|
+
if (!isCanonicalEvidenceCovered(tool.name)) return tool.execute(input, ctx)
|
|
780
|
+
const sessionId = asNonEmpty(scope.sessionId, "sessionId")
|
|
781
|
+
const threadId = asNonEmpty(scope.threadId, "threadId")
|
|
782
|
+
// File effects use ToolContext.cwd first; scope.cwd only selects evidence storage.
|
|
783
|
+
const effectRoot = (ctx as { cwd?: string }).cwd ?? scope.cwd
|
|
784
|
+
if (!effectRoot)
|
|
785
|
+
throw new EvidenceIncompleteError("verification: refusing invocation without cwd")
|
|
786
|
+
const evidenceRoot = requireWorkspaceRoot(scope.cwd)
|
|
787
|
+
const turnIndex =
|
|
788
|
+
scope.getTurnIndex?.() ?? normalizeTurnIndex((ctx.state as { turnCount?: unknown })?.turnCount)
|
|
789
|
+
const argsHash = hashArgs(input ?? {})
|
|
790
|
+
const baseKey = scope.idempotencyKeyFor?.(tool.name, input)
|
|
791
|
+
const idempotencyKey = baseKey === undefined ? undefined : buildIdempotencyKey(sessionId, baseKey)
|
|
792
|
+
const runOnce = async (): Promise<unknown> => {
|
|
793
|
+
const intent = await writer.writeIntent({
|
|
794
|
+
sessionId,
|
|
795
|
+
threadId,
|
|
796
|
+
turnIndex,
|
|
797
|
+
tool: tool.name,
|
|
798
|
+
cwd: evidenceRoot,
|
|
799
|
+
...(scope.childOf ? { childOf: scope.childOf } : {}),
|
|
800
|
+
args: input,
|
|
801
|
+
...(idempotencyKey ? { idempotencyKey, idempotencyScope: "session" as const } : {}),
|
|
802
|
+
})
|
|
803
|
+
if (!intent.durable) {
|
|
804
|
+
throw new EvidenceIncompleteError(
|
|
805
|
+
"verification: refusing execution without durable EffectIntent",
|
|
806
|
+
)
|
|
807
|
+
}
|
|
808
|
+
if (isSignalAborted(ctx.signal)) {
|
|
809
|
+
throw new EvidenceIncompleteError("verification: aborted before tool execution")
|
|
810
|
+
}
|
|
811
|
+
let result: unknown
|
|
812
|
+
try {
|
|
813
|
+
result = await tool.execute(input, ctx)
|
|
814
|
+
} catch (error) {
|
|
815
|
+
await writer.writeReceipt({
|
|
816
|
+
sessionId,
|
|
817
|
+
threadId,
|
|
818
|
+
tool: tool.name,
|
|
819
|
+
cwd: evidenceRoot,
|
|
820
|
+
invocation: intent.invocation,
|
|
821
|
+
intent: {
|
|
822
|
+
id: intent.record.id,
|
|
823
|
+
seq: intent.record.seq,
|
|
824
|
+
tool: intent.record.tool,
|
|
825
|
+
session: intent.record.session,
|
|
826
|
+
...(intent.record.invocationId ? { invocationId: intent.record.invocationId } : {}),
|
|
827
|
+
...(intent.record.argsHash ? { argsHash: intent.record.argsHash } : {}),
|
|
828
|
+
},
|
|
829
|
+
state: "failed",
|
|
830
|
+
error,
|
|
831
|
+
signalAborted: isSignalAborted(ctx.signal),
|
|
832
|
+
...(idempotencyKey ? { outcome: { note: idempotencyKey }, dedup: true } : {}),
|
|
833
|
+
})
|
|
834
|
+
throw error
|
|
835
|
+
}
|
|
836
|
+
const receipt = await writer.writeReceipt({
|
|
837
|
+
sessionId,
|
|
838
|
+
threadId,
|
|
839
|
+
tool: tool.name,
|
|
840
|
+
cwd: evidenceRoot,
|
|
841
|
+
invocation: intent.invocation,
|
|
842
|
+
intent: {
|
|
843
|
+
id: intent.record.id,
|
|
844
|
+
seq: intent.record.seq,
|
|
845
|
+
tool: intent.record.tool,
|
|
846
|
+
session: intent.record.session,
|
|
847
|
+
...(intent.record.invocationId ? { invocationId: intent.record.invocationId } : {}),
|
|
848
|
+
...(intent.record.argsHash ? { argsHash: intent.record.argsHash } : {}),
|
|
849
|
+
},
|
|
850
|
+
state: "committed",
|
|
851
|
+
result,
|
|
852
|
+
signalAborted: isSignalAborted(ctx.signal),
|
|
853
|
+
...(idempotencyKey ? { outcome: { note: idempotencyKey }, dedup: true } : {}),
|
|
854
|
+
})
|
|
855
|
+
// Receipt failure after an observed return preserves the tool outcome and
|
|
856
|
+
// leaves the intent pending/unknown. It never fabricates a terminal.
|
|
857
|
+
void receipt.durable
|
|
858
|
+
return result
|
|
859
|
+
}
|
|
860
|
+
if (!idempotencyKey) return runOnce()
|
|
861
|
+
const flightKey = `${evidenceRoot}::${idempotencyKey}`
|
|
862
|
+
return runOncePerIdempotencyKey(flightKey, async () => {
|
|
863
|
+
const duplicate = await findIdempotentInvocation({
|
|
864
|
+
sessionId,
|
|
865
|
+
cwd: evidenceRoot,
|
|
866
|
+
idempotencyKey,
|
|
867
|
+
argsHash,
|
|
868
|
+
})
|
|
869
|
+
if (duplicate.status !== "proceed") {
|
|
870
|
+
throw new IdempotentDuplicateError(
|
|
871
|
+
duplicate.status,
|
|
872
|
+
duplicate.message ?? `duplicate idempotency key: refusing blind re-execution`,
|
|
873
|
+
)
|
|
874
|
+
}
|
|
875
|
+
return runOnce()
|
|
876
|
+
})
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
export interface FilesystemVerificationTarget {
|
|
880
|
+
path: string
|
|
881
|
+
expected?: "present" | "absent"
|
|
882
|
+
expectedContent?: string
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
export interface FilesystemVerificationRequest {
|
|
886
|
+
sessionId: string
|
|
887
|
+
threadId?: string
|
|
888
|
+
tool: string
|
|
889
|
+
invocationId: string
|
|
890
|
+
cwd: string
|
|
891
|
+
expected: "present" | "absent"
|
|
892
|
+
targets: FilesystemVerificationTarget[]
|
|
893
|
+
childSessionId?: string
|
|
894
|
+
observedAt?: number
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
type FilesystemObservation = "present" | "absent" | "unreadable"
|
|
898
|
+
|
|
899
|
+
interface FilesystemTargetObservation {
|
|
900
|
+
observed: FilesystemObservation
|
|
901
|
+
usable: boolean
|
|
902
|
+
reason?: string
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function observationReason(error: unknown, fallback: string): string {
|
|
906
|
+
const code = (error as NodeJS.ErrnoException)?.code
|
|
907
|
+
const detail = typeof code === "string" && code ? code : fallback
|
|
908
|
+
return scrubSecrets(detail).slice(0, 120)
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
async function observeFilesystemTarget(
|
|
912
|
+
root: string,
|
|
913
|
+
target: FilesystemVerificationTarget,
|
|
914
|
+
): Promise<FilesystemTargetObservation> {
|
|
915
|
+
const abs = resolve(root, target.path)
|
|
916
|
+
const rel = relative(root, abs).replace(/\\/g, "/")
|
|
917
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
|
|
918
|
+
return { observed: "unreadable", usable: false, reason: "outside-workspace" }
|
|
919
|
+
}
|
|
920
|
+
let stat: Awaited<ReturnType<typeof safeStat>> | null
|
|
921
|
+
try {
|
|
922
|
+
stat = await safeStat(abs, root)
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
925
|
+
return { observed: "absent", usable: true }
|
|
926
|
+
}
|
|
927
|
+
return {
|
|
928
|
+
observed: "unreadable",
|
|
929
|
+
usable: false,
|
|
930
|
+
reason: observationReason(error, "stat-unavailable"),
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
if (!stat || stat.isDirectory()) {
|
|
934
|
+
if (target.expectedContent !== undefined) {
|
|
935
|
+
return { observed: "present", usable: false, reason: "directory-content-uncomparable" }
|
|
936
|
+
}
|
|
937
|
+
return { observed: "present", usable: true }
|
|
938
|
+
}
|
|
939
|
+
let content: string
|
|
940
|
+
try {
|
|
941
|
+
content = await safeReadFile(abs, root)
|
|
942
|
+
} catch (error) {
|
|
943
|
+
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
944
|
+
return { observed: "absent", usable: true }
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
observed: "unreadable",
|
|
948
|
+
usable: false,
|
|
949
|
+
reason: observationReason(error, "read-unavailable"),
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (target.expectedContent !== undefined && content !== target.expectedContent) {
|
|
953
|
+
return { observed: "present", usable: false, reason: "content-mismatch" }
|
|
954
|
+
}
|
|
955
|
+
return { observed: "present", usable: true }
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/** Explicit filesystem read-back around checkpoint file-snapshot primitives. */
|
|
959
|
+
export async function verifyFilesystemEffect(
|
|
960
|
+
input: FilesystemVerificationRequest,
|
|
961
|
+
): Promise<{ record: JournalRecord; durable: boolean; verdict: VerificationVerdict }> {
|
|
962
|
+
const sessionId = asNonEmpty(input.sessionId, "sessionId")
|
|
963
|
+
const invocationId = asNonEmpty(input.invocationId, "invocationId")
|
|
964
|
+
const tool = asNonEmpty(input.tool, "tool")
|
|
965
|
+
const root = requireWorkspaceRoot(input.cwd)
|
|
966
|
+
if (!Array.isArray(input.targets) || input.targets.length === 0) {
|
|
967
|
+
throw new Error("verification: refusing filesystem observation without targets")
|
|
968
|
+
}
|
|
969
|
+
if (input.expected !== "present" && input.expected !== "absent") {
|
|
970
|
+
throw new Error("verification: refusing filesystem observation without expected state")
|
|
971
|
+
}
|
|
972
|
+
const observations = []
|
|
973
|
+
for (const target of input.targets) {
|
|
974
|
+
if (!target || typeof target.path !== "string" || !target.path) {
|
|
975
|
+
throw new Error("verification: refusing filesystem observation without path")
|
|
976
|
+
}
|
|
977
|
+
observations.push({
|
|
978
|
+
path: target.path,
|
|
979
|
+
...(await observeFilesystemTarget(root, { ...target, expected: input.expected })),
|
|
980
|
+
})
|
|
981
|
+
}
|
|
982
|
+
const usable = observations.every((item) => item.usable)
|
|
983
|
+
const observed = observations.map((item) => item.observed)
|
|
984
|
+
const verdict: VerificationVerdict = !usable
|
|
985
|
+
? "inconclusive"
|
|
986
|
+
: observed.every((state) => state === input.expected)
|
|
987
|
+
? input.expected
|
|
988
|
+
: observed.every((state) => state !== input.expected)
|
|
989
|
+
? input.expected === "present"
|
|
990
|
+
? "absent"
|
|
991
|
+
: "present"
|
|
992
|
+
: "inconclusive"
|
|
993
|
+
const reference = JSON.stringify({
|
|
994
|
+
method: "filesystem-read-back",
|
|
995
|
+
expected: input.expected,
|
|
996
|
+
observations: observations.map((item) => ({
|
|
997
|
+
path: item.path,
|
|
998
|
+
observed: item.observed,
|
|
999
|
+
...(item.reason ? { reason: item.reason } : {}),
|
|
1000
|
+
})),
|
|
1001
|
+
})
|
|
1002
|
+
const result = await recordExternalVerification({
|
|
1003
|
+
sessionId,
|
|
1004
|
+
...(input.threadId ? { threadId: input.threadId } : {}),
|
|
1005
|
+
tool,
|
|
1006
|
+
invocationId,
|
|
1007
|
+
method: "filesystem-read-back",
|
|
1008
|
+
verdict,
|
|
1009
|
+
evidenceReference: reference,
|
|
1010
|
+
cwd: root,
|
|
1011
|
+
...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
|
|
1012
|
+
...(typeof input.observedAt === "number" ? { observedAt: input.observedAt } : {}),
|
|
1013
|
+
})
|
|
1014
|
+
return { record: result.record, durable: result.durable, verdict }
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** Read-only commit observation using hardened git plumbing. */
|
|
1018
|
+
export async function observeGitCommit(
|
|
1019
|
+
cwd: string,
|
|
1020
|
+
sha: unknown,
|
|
1021
|
+
): Promise<"present" | "absent" | "inconclusive"> {
|
|
1022
|
+
if (typeof sha !== "string" || !SHA_RE.test(sha)) {
|
|
1023
|
+
throw new Error("verification: refusing git observation without commit SHA")
|
|
1024
|
+
}
|
|
1025
|
+
const root = requireWorkspaceRoot(cwd)
|
|
1026
|
+
let repo = false
|
|
1027
|
+
try {
|
|
1028
|
+
repo = await isGitRepo(root)
|
|
1029
|
+
} catch {
|
|
1030
|
+
return "inconclusive"
|
|
1031
|
+
}
|
|
1032
|
+
if (!repo) return "inconclusive"
|
|
1033
|
+
try {
|
|
1034
|
+
const result = spawnSync(
|
|
1035
|
+
resolveTrustedExecutable("git"),
|
|
1036
|
+
[...GIT_SAFE_BASE, "cat-file", "-e", `${sha}^{commit}`],
|
|
1037
|
+
{
|
|
1038
|
+
cwd: root,
|
|
1039
|
+
encoding: "utf8",
|
|
1040
|
+
timeout: GIT_OBSERVE_TIMEOUT_MS,
|
|
1041
|
+
},
|
|
1042
|
+
)
|
|
1043
|
+
if (result.status === 0) return "present"
|
|
1044
|
+
if (typeof result.status === "number") return "absent"
|
|
1045
|
+
return "inconclusive"
|
|
1046
|
+
} catch {
|
|
1047
|
+
return "inconclusive"
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/** Write a git-state VerificationRecord for an already-observed commit. */
|
|
1052
|
+
export async function verifyGitCommit(input: {
|
|
1053
|
+
sessionId: string
|
|
1054
|
+
threadId?: string
|
|
1055
|
+
tool: string
|
|
1056
|
+
invocationId: string
|
|
1057
|
+
cwd: string
|
|
1058
|
+
sha: string
|
|
1059
|
+
childSessionId?: string
|
|
1060
|
+
observedAt?: number
|
|
1061
|
+
}): Promise<{ record: JournalRecord; durable: boolean; verdict: VerificationVerdict }> {
|
|
1062
|
+
const observation = await observeGitCommit(input.cwd, input.sha)
|
|
1063
|
+
const verdict: VerificationVerdict =
|
|
1064
|
+
observation === "present" ? "present" : observation === "absent" ? "absent" : "inconclusive"
|
|
1065
|
+
const result = await recordExternalVerification({
|
|
1066
|
+
sessionId: input.sessionId,
|
|
1067
|
+
...(input.threadId ? { threadId: input.threadId } : {}),
|
|
1068
|
+
tool: input.tool,
|
|
1069
|
+
invocationId: input.invocationId,
|
|
1070
|
+
method: "git-state",
|
|
1071
|
+
verdict,
|
|
1072
|
+
evidenceReference: `git-state:commit:${input.sha}:${observation}`,
|
|
1073
|
+
cwd: input.cwd,
|
|
1074
|
+
...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
|
|
1075
|
+
...(typeof input.observedAt === "number" ? { observedAt: input.observedAt } : {}),
|
|
1076
|
+
})
|
|
1077
|
+
return { record: result.record, durable: result.durable, verdict }
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/** Map an actually executed verifier outcome (never model prose) to a verdict. */
|
|
1081
|
+
export function mapVerifierOutcome(result: VerifyResult): VerificationVerdict {
|
|
1082
|
+
return result.ok ? "present" : "inconclusive"
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** Record an executed existing-verifier outcome for one invocation. */
|
|
1086
|
+
export async function recordVerifierOutcome(input: {
|
|
1087
|
+
sessionId: string
|
|
1088
|
+
threadId?: string
|
|
1089
|
+
tool: string
|
|
1090
|
+
invocationId: string
|
|
1091
|
+
cwd: string
|
|
1092
|
+
result: VerifyResult
|
|
1093
|
+
childSessionId?: string
|
|
1094
|
+
observedAt?: number
|
|
1095
|
+
}): Promise<{ record: JournalRecord; durable: boolean; verdict: VerificationVerdict }> {
|
|
1096
|
+
const command = scrubSecrets(String(input.result.command ?? "")).slice(0, MAX_ID)
|
|
1097
|
+
if (!command) throw new Error("verification: refusing verifier record without command")
|
|
1098
|
+
const verdict = mapVerifierOutcome(input.result)
|
|
1099
|
+
const result = await recordExternalVerification({
|
|
1100
|
+
sessionId: input.sessionId,
|
|
1101
|
+
...(input.threadId ? { threadId: input.threadId } : {}),
|
|
1102
|
+
tool: input.tool,
|
|
1103
|
+
invocationId: input.invocationId,
|
|
1104
|
+
method: "existing-verifier",
|
|
1105
|
+
verdict,
|
|
1106
|
+
evidenceReference: `existing-verifier:${command}:${input.result.ok ? "passed" : "failed"}`,
|
|
1107
|
+
cwd: input.cwd,
|
|
1108
|
+
...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
|
|
1109
|
+
...(typeof input.observedAt === "number" ? { observedAt: input.observedAt } : {}),
|
|
1110
|
+
})
|
|
1111
|
+
return { record: result.record, durable: result.durable, verdict }
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
export interface ExternalVerificationRequest {
|
|
1115
|
+
sessionId: string
|
|
1116
|
+
threadId?: string
|
|
1117
|
+
tool: string
|
|
1118
|
+
invocationId: string
|
|
1119
|
+
method: VerificationMethod
|
|
1120
|
+
verdict: VerificationVerdict
|
|
1121
|
+
evidenceReference: string
|
|
1122
|
+
observedAt?: number
|
|
1123
|
+
cwd: string
|
|
1124
|
+
childOf?: string
|
|
1125
|
+
childSessionId?: string
|
|
1126
|
+
providerToolCallId?: string
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/**
|
|
1130
|
+
* Record an explicit external observation. Only approved methods are accepted;
|
|
1131
|
+
* untrusted prose and unrelated lifecycle, observation, authorization, or
|
|
1132
|
+
* watermark authorities are rejected before any write. The referenced
|
|
1133
|
+
* invocation must already have durable intent.
|
|
1134
|
+
*/
|
|
1135
|
+
export async function recordExternalVerification(
|
|
1136
|
+
input: ExternalVerificationRequest,
|
|
1137
|
+
): Promise<{ record: JournalRecord; durable: boolean }> {
|
|
1138
|
+
const sessionId = asNonEmpty(input.sessionId, "sessionId")
|
|
1139
|
+
const tool = asNonEmpty(input.tool, "tool")
|
|
1140
|
+
const invocationId = asNonEmpty(input.invocationId, "invocationId")
|
|
1141
|
+
if (!isVerificationMethod(input.method)) {
|
|
1142
|
+
throw new Error(`verification: unsupported method ${String(input.method)}`)
|
|
1143
|
+
}
|
|
1144
|
+
if (
|
|
1145
|
+
input.verdict !== "present" &&
|
|
1146
|
+
input.verdict !== "absent" &&
|
|
1147
|
+
input.verdict !== "inconclusive"
|
|
1148
|
+
) {
|
|
1149
|
+
throw new Error(`verification: unsupported verdict ${String(input.verdict)}`)
|
|
1150
|
+
}
|
|
1151
|
+
const root = requireWorkspaceRoot(input.cwd)
|
|
1152
|
+
const loaded = await loadJournal(sessionId, root)
|
|
1153
|
+
if (loaded.status === "unreadable") {
|
|
1154
|
+
throw new EvidenceIncompleteError(
|
|
1155
|
+
"verification: refusing observation while intent is unreadable",
|
|
1156
|
+
)
|
|
1157
|
+
}
|
|
1158
|
+
const intent = loaded.records.some(
|
|
1159
|
+
(record) =>
|
|
1160
|
+
(!record.kind || record.kind === "mutation") && record.invocationId === invocationId,
|
|
1161
|
+
)
|
|
1162
|
+
if (!intent) {
|
|
1163
|
+
throw new EvidenceIncompleteError("verification: refusing observation without durable intent")
|
|
1164
|
+
}
|
|
1165
|
+
return appendVerificationRecord({
|
|
1166
|
+
session: sessionId,
|
|
1167
|
+
...(input.threadId ? { threadId: input.threadId } : {}),
|
|
1168
|
+
tool,
|
|
1169
|
+
invocationId,
|
|
1170
|
+
method: input.method,
|
|
1171
|
+
verdict: input.verdict,
|
|
1172
|
+
evidenceReference: input.evidenceReference,
|
|
1173
|
+
...(typeof input.observedAt === "number" ? { observedAt: input.observedAt } : {}),
|
|
1174
|
+
cwd: root,
|
|
1175
|
+
...(input.childOf ? { childOf: input.childOf } : {}),
|
|
1176
|
+
...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
|
|
1177
|
+
...(input.providerToolCallId ? { providerToolCallId: input.providerToolCallId } : {}),
|
|
1178
|
+
})
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
export interface ChildLineage {
|
|
1182
|
+
parentSessionId: string
|
|
1183
|
+
childSessionId: string
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
export interface ChildEffectRequest {
|
|
1187
|
+
parentSessionId: string
|
|
1188
|
+
childSessionId: string
|
|
1189
|
+
childInvocationId: string
|
|
1190
|
+
cwd: string
|
|
1191
|
+
lineage: ChildLineage[]
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
export interface ChildEffectCorrelation {
|
|
1195
|
+
parentDelegation: ChildDelegationStatus
|
|
1196
|
+
childJournal: ChildJournalStatus
|
|
1197
|
+
childVerification: ChildVerificationStatus
|
|
1198
|
+
conclusion: VerificationVerdict | "unknown"
|
|
1199
|
+
evidence: {
|
|
1200
|
+
parentIntentId?: string
|
|
1201
|
+
parentTerminalId?: string
|
|
1202
|
+
childIntentId?: string
|
|
1203
|
+
childTerminalId?: string
|
|
1204
|
+
childVerificationId?: string
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
function latestBySeq<T extends { seq: number }>(records: T[]): T | undefined {
|
|
1209
|
+
let latest: T | undefined
|
|
1210
|
+
for (const record of records) {
|
|
1211
|
+
if (!latest || record.seq >= latest.seq) latest = record
|
|
1212
|
+
}
|
|
1213
|
+
return latest
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Correlate parent delegation with child-journal evidence. Delegation text is
|
|
1218
|
+
* not consulted. Only an explicit child VerificationRecord can move the
|
|
1219
|
+
* conclusion away from unknown.
|
|
1220
|
+
*/
|
|
1221
|
+
export async function correlateChildEffect(
|
|
1222
|
+
input: ChildEffectRequest,
|
|
1223
|
+
): Promise<ChildEffectCorrelation> {
|
|
1224
|
+
const parentSessionId = asNonEmpty(input.parentSessionId, "parentSessionId")
|
|
1225
|
+
const childSessionId = asNonEmpty(input.childSessionId, "childSessionId")
|
|
1226
|
+
const childInvocationId = asNonEmpty(input.childInvocationId, "childInvocationId")
|
|
1227
|
+
const root = requireWorkspaceRoot(input.cwd)
|
|
1228
|
+
const linked = (input.lineage ?? []).some(
|
|
1229
|
+
(entry) =>
|
|
1230
|
+
entry?.parentSessionId === parentSessionId && entry?.childSessionId === childSessionId,
|
|
1231
|
+
)
|
|
1232
|
+
if (!linked) {
|
|
1233
|
+
return {
|
|
1234
|
+
parentDelegation: "absent",
|
|
1235
|
+
childJournal: "absent",
|
|
1236
|
+
childVerification: "absent-record",
|
|
1237
|
+
conclusion: "unknown",
|
|
1238
|
+
evidence: {},
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const parent = await loadJournal(parentSessionId, root)
|
|
1242
|
+
const parentIntents = parent.records.filter(
|
|
1243
|
+
(record) =>
|
|
1244
|
+
(!record.kind || record.kind === "mutation") &&
|
|
1245
|
+
record.tool === "delegate_task" &&
|
|
1246
|
+
record.childSessionId === childSessionId,
|
|
1247
|
+
)
|
|
1248
|
+
const parentTerminal = latestBySeq(
|
|
1249
|
+
parentIntents.filter((record) => record.state === "committed" || record.state === "failed"),
|
|
1250
|
+
)
|
|
1251
|
+
const parentDelegation: ChildDelegationStatus = parentTerminal
|
|
1252
|
+
? parentTerminal.state === "committed"
|
|
1253
|
+
? "committed"
|
|
1254
|
+
: "failed"
|
|
1255
|
+
: parentIntents.length > 0
|
|
1256
|
+
? "pending"
|
|
1257
|
+
: "absent"
|
|
1258
|
+
if (parentDelegation !== "committed") {
|
|
1259
|
+
return {
|
|
1260
|
+
parentDelegation,
|
|
1261
|
+
childJournal: "absent",
|
|
1262
|
+
childVerification: "absent-record",
|
|
1263
|
+
conclusion: "unknown",
|
|
1264
|
+
evidence: {
|
|
1265
|
+
...(parentIntents[0] ? { parentIntentId: parentIntents[0].id } : {}),
|
|
1266
|
+
...(parentTerminal ? { parentTerminalId: parentTerminal.id } : {}),
|
|
1267
|
+
},
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const child = await loadJournal(childSessionId, root)
|
|
1271
|
+
const childIntents = child.records.filter(
|
|
1272
|
+
(record) =>
|
|
1273
|
+
(!record.kind || record.kind === "mutation") &&
|
|
1274
|
+
record.invocationId === childInvocationId &&
|
|
1275
|
+
record.session === childSessionId,
|
|
1276
|
+
)
|
|
1277
|
+
if (childIntents.length === 0) {
|
|
1278
|
+
return {
|
|
1279
|
+
parentDelegation,
|
|
1280
|
+
childJournal: "absent",
|
|
1281
|
+
childVerification: "absent-record",
|
|
1282
|
+
conclusion: "unknown",
|
|
1283
|
+
evidence: {
|
|
1284
|
+
...(parentTerminal ? { parentTerminalId: parentTerminal.id } : {}),
|
|
1285
|
+
},
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
const childTerminal = latestBySeq(
|
|
1289
|
+
childIntents.filter((record) => record.state === "committed" || record.state === "failed"),
|
|
1290
|
+
)
|
|
1291
|
+
const childJournal: ChildJournalStatus = childTerminal
|
|
1292
|
+
? childTerminal.state === "committed"
|
|
1293
|
+
? "committed"
|
|
1294
|
+
: "failed"
|
|
1295
|
+
: "pending"
|
|
1296
|
+
const verification = latestBySeq(
|
|
1297
|
+
child.records.filter(
|
|
1298
|
+
(record) => record.kind === "verification" && record.invocationId === childInvocationId,
|
|
1299
|
+
),
|
|
1300
|
+
)
|
|
1301
|
+
const childVerification: ChildVerificationStatus = verification
|
|
1302
|
+
? (verification.verdict ?? "inconclusive")
|
|
1303
|
+
: "absent-record"
|
|
1304
|
+
const conclusion =
|
|
1305
|
+
childVerification === "present" || childVerification === "absent"
|
|
1306
|
+
? childVerification
|
|
1307
|
+
: "unknown"
|
|
1308
|
+
return {
|
|
1309
|
+
parentDelegation,
|
|
1310
|
+
childJournal,
|
|
1311
|
+
childVerification,
|
|
1312
|
+
conclusion,
|
|
1313
|
+
evidence: {
|
|
1314
|
+
...(parentTerminal ? { parentTerminalId: parentTerminal.id } : {}),
|
|
1315
|
+
...(childIntents[0] ? { childIntentId: childIntents[0].id } : {}),
|
|
1316
|
+
...(childTerminal ? { childTerminalId: childTerminal.id } : {}),
|
|
1317
|
+
...(verification ? { childVerificationId: verification.id } : {}),
|
|
1318
|
+
},
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// ── [Fase 3 / LOOP-INV-12, LOOP-G21] Tier 1 Workspace Integrity Check ──────
|
|
1323
|
+
//
|
|
1324
|
+
// Pemeriksaan deterministik & instan (tanpa spawn proses eksternal) sebelum
|
|
1325
|
+
// task diizinkan mengunci status terminal `COMPLETED`:
|
|
1326
|
+
// 1. File yang tercatat dimutasi (write_file/edit/apply_patch/move_file)
|
|
1327
|
+
// tidak boleh hilang diam-diam di disk.
|
|
1328
|
+
// 2. File teks yang dimutasi tidak boleh menyisakan penanda konflik Git
|
|
1329
|
+
// yang belum diselesaikan (`<<<<<<< `, `=======`, `>>>>>>> ` di awal baris).
|
|
1330
|
+
|
|
1331
|
+
export interface WorkspaceIntegrityIssue {
|
|
1332
|
+
readonly path: string
|
|
1333
|
+
readonly reason: "missing-written-file" | "unresolved-conflict-marker"
|
|
1334
|
+
readonly line?: number
|
|
1335
|
+
readonly detail: string
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
export interface WorkspaceIntegrityReport {
|
|
1339
|
+
readonly ok: boolean
|
|
1340
|
+
readonly checkedFiles: readonly string[]
|
|
1341
|
+
readonly issues: readonly WorkspaceIntegrityIssue[]
|
|
1342
|
+
readonly summary: string
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
const INTEGRITY_MAX_BYTES = 8 * 1024 * 1024
|
|
1346
|
+
const CONFLICT_START_RE = /^<{7}(?: |$)/
|
|
1347
|
+
const CONFLICT_END_RE = /^>{7}(?: |$)/
|
|
1348
|
+
|
|
1349
|
+
function findConflictMarkerLine(text: string): number | null {
|
|
1350
|
+
const lines = text.split("\n")
|
|
1351
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1352
|
+
const raw = lines[i]!
|
|
1353
|
+
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw
|
|
1354
|
+
if (CONFLICT_START_RE.test(line) || CONFLICT_END_RE.test(line)) {
|
|
1355
|
+
return i + 1
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
// `=======` sendirian lazim sebagai setext heading Markdown, jadi hanya
|
|
1359
|
+
// dianggap conflict marker bila disertai `<<<<<<<` / `>>>>>>>` (yang sudah
|
|
1360
|
+
// tertangkap di atas). Menjaga nol false-positive pada dokumentasi `.md`.
|
|
1361
|
+
return null
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
export async function checkWorkspaceIntegrity(
|
|
1365
|
+
modifiedFiles: readonly string[],
|
|
1366
|
+
workspaceRoot: string,
|
|
1367
|
+
): Promise<WorkspaceIntegrityReport> {
|
|
1368
|
+
const root = resolve(workspaceRoot)
|
|
1369
|
+
const checkedFiles: string[] = []
|
|
1370
|
+
const issues: WorkspaceIntegrityIssue[] = []
|
|
1371
|
+
const seen = new Set<string>()
|
|
1372
|
+
|
|
1373
|
+
for (const rawPath of modifiedFiles) {
|
|
1374
|
+
if (typeof rawPath !== "string" || !rawPath.trim()) continue
|
|
1375
|
+
const abs = resolve(root, rawPath)
|
|
1376
|
+
const rel = relative(root, abs).replace(/\\/g, "/")
|
|
1377
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) continue
|
|
1378
|
+
if (seen.has(rel)) continue
|
|
1379
|
+
seen.add(rel)
|
|
1380
|
+
checkedFiles.push(rel)
|
|
1381
|
+
|
|
1382
|
+
let st: Awaited<ReturnType<typeof safeStat>> | null = null
|
|
1383
|
+
try {
|
|
1384
|
+
st = await safeStat(abs, root)
|
|
1385
|
+
} catch (err) {
|
|
1386
|
+
if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
1387
|
+
issues.push({
|
|
1388
|
+
path: rel,
|
|
1389
|
+
reason: "missing-written-file",
|
|
1390
|
+
detail: `expected written file '${rel}' is missing on disk`,
|
|
1391
|
+
})
|
|
1392
|
+
}
|
|
1393
|
+
continue
|
|
1394
|
+
}
|
|
1395
|
+
if (!st.isFile() || st.size > INTEGRITY_MAX_BYTES) continue
|
|
1396
|
+
|
|
1397
|
+
let contentText: string
|
|
1398
|
+
try {
|
|
1399
|
+
contentText = await safeReadFile(abs, root)
|
|
1400
|
+
} catch (err) {
|
|
1401
|
+
if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
1402
|
+
issues.push({
|
|
1403
|
+
path: rel,
|
|
1404
|
+
reason: "missing-written-file",
|
|
1405
|
+
detail: `expected written file '${rel}' disappeared during check`,
|
|
1406
|
+
})
|
|
1407
|
+
}
|
|
1408
|
+
continue
|
|
1409
|
+
}
|
|
1410
|
+
// Lewati file biner (ada karakter NUL pada 8 KiB pertama).
|
|
1411
|
+
const probeLen = Math.min(contentText.length, 8192)
|
|
1412
|
+
let binary = false
|
|
1413
|
+
for (let i = 0; i < probeLen; i++) {
|
|
1414
|
+
if (contentText.charCodeAt(i) === 0) {
|
|
1415
|
+
binary = true
|
|
1416
|
+
break
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
if (binary) continue
|
|
1420
|
+
|
|
1421
|
+
const markerLine = findConflictMarkerLine(contentText)
|
|
1422
|
+
if (markerLine !== null) {
|
|
1423
|
+
issues.push({
|
|
1424
|
+
path: rel,
|
|
1425
|
+
reason: "unresolved-conflict-marker",
|
|
1426
|
+
line: markerLine,
|
|
1427
|
+
detail: `unresolved Git conflict marker in '${rel}' at line ${markerLine}`,
|
|
1428
|
+
})
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
if (issues.length === 0) {
|
|
1433
|
+
return {
|
|
1434
|
+
ok: true,
|
|
1435
|
+
checkedFiles,
|
|
1436
|
+
issues: [],
|
|
1437
|
+
summary: "workspace integrity ok",
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
const first = issues[0]!
|
|
1441
|
+
const suffix = issues.length > 1 ? ` (+${issues.length - 1} more)` : ""
|
|
1442
|
+
return {
|
|
1443
|
+
ok: false,
|
|
1444
|
+
checkedFiles,
|
|
1445
|
+
issues,
|
|
1446
|
+
summary: `workspace integrity failed: ${first.detail}${suffix}`,
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// ── [Fase 6A / ACE-02] Anti-Reward-Hacking Tamper Guard ──────────────────────
|
|
1451
|
+
//
|
|
1452
|
+
// Verifikasi yang jujur mensyaratkan evaluator TIDAK ikut berubah selama agen
|
|
1453
|
+
// bekerja. Dua jalur curang yang paling murah:
|
|
1454
|
+
// 1. menyentuh skrip gate/evaluator (`bench/eval-gate.ts`,
|
|
1455
|
+
// `scripts/telemetry-gate.ts`) atau mengganti script test/verify di
|
|
1456
|
+
// `package.json`, dan
|
|
1457
|
+
// 2. menyuntik `.skip(` / `.todo(` baru ke file `test/**/*.test.ts` yang
|
|
1458
|
+
// sedang dimodifikasi agar test yang gagal berhenti dieksekusi.
|
|
1459
|
+
//
|
|
1460
|
+
// Deteksi ini SANGAT konservatif pada arah yang aman (fail-closed): tanpa
|
|
1461
|
+
// baseline yang bisa dibaca, file gate dianggap tersentuh. Baseline diambil
|
|
1462
|
+
// dari parameter eksplisit (test hermetik) atau `git show HEAD:<path>`.
|
|
1463
|
+
|
|
1464
|
+
export interface EvaluationTamperingReport {
|
|
1465
|
+
readonly tampered: boolean
|
|
1466
|
+
readonly reason: string
|
|
1467
|
+
readonly offendingFiles: readonly string[]
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
export interface EvaluationTamperingOptions {
|
|
1471
|
+
/** Operator/agen eksplisit diizinkan mengubah test (mis. task "perbaiki test"). */
|
|
1472
|
+
readonly allowTestModification?: boolean
|
|
1473
|
+
/** Baseline isi file sebelum sesi; bila absen, `git show HEAD:` dipakai. */
|
|
1474
|
+
readonly baselineContentByFile?: ReadonlyMap<string, string>
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
const EVALUATOR_GATE_FILES = new Set(["bench/eval-gate.ts", "scripts/telemetry-gate.ts"])
|
|
1478
|
+
const SKIP_TODO_RE = /\.(?:skip|skipIf|only|todo|fails)\s*\(/g
|
|
1479
|
+
|
|
1480
|
+
function countSkipTodo(text: string): number {
|
|
1481
|
+
return (text.match(SKIP_TODO_RE) ?? []).length
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
function verificationScriptsFingerprint(text: string): string | null {
|
|
1485
|
+
try {
|
|
1486
|
+
const parsed = JSON.parse(text) as { scripts?: Record<string, unknown> }
|
|
1487
|
+
const scripts = parsed.scripts ?? {}
|
|
1488
|
+
return Object.keys(scripts)
|
|
1489
|
+
.filter((k) => /^(?:test|verify|lint|check|gate|eval)/i.test(k))
|
|
1490
|
+
.sort()
|
|
1491
|
+
.map((k) => `${k}=${String(scripts[k])}`)
|
|
1492
|
+
.join("\n")
|
|
1493
|
+
} catch {
|
|
1494
|
+
return null
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
function gitBaselineContent(root: string, rel: string): string | null {
|
|
1499
|
+
try {
|
|
1500
|
+
const result = spawnSync(
|
|
1501
|
+
resolveTrustedExecutable("git"),
|
|
1502
|
+
[...GIT_SAFE_BASE, "show", `HEAD:${rel}`],
|
|
1503
|
+
{
|
|
1504
|
+
cwd: root,
|
|
1505
|
+
encoding: "utf8",
|
|
1506
|
+
timeout: GIT_OBSERVE_TIMEOUT_MS,
|
|
1507
|
+
maxBuffer: INTEGRITY_MAX_BYTES,
|
|
1508
|
+
},
|
|
1509
|
+
)
|
|
1510
|
+
return result.status === 0 && typeof result.stdout === "string" ? result.stdout : null
|
|
1511
|
+
} catch {
|
|
1512
|
+
return null
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* Deteksi manipulasi evaluator pada file yang dimutasi sesi ini.
|
|
1518
|
+
* Deterministik: hanya membaca file/baseline; tidak menulis apa pun.
|
|
1519
|
+
*/
|
|
1520
|
+
export async function detectEvaluationTampering(
|
|
1521
|
+
modifiedFiles: readonly string[],
|
|
1522
|
+
workspaceRoot: string,
|
|
1523
|
+
opts: EvaluationTamperingOptions = {},
|
|
1524
|
+
): Promise<EvaluationTamperingReport> {
|
|
1525
|
+
if (opts.allowTestModification === true) {
|
|
1526
|
+
return { tampered: false, reason: "test modification explicitly allowed", offendingFiles: [] }
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
const root = resolve(workspaceRoot)
|
|
1530
|
+
const offending: string[] = []
|
|
1531
|
+
const seen = new Set<string>()
|
|
1532
|
+
|
|
1533
|
+
for (const rawPath of modifiedFiles) {
|
|
1534
|
+
if (typeof rawPath !== "string" || !rawPath.trim()) continue
|
|
1535
|
+
const abs = resolve(root, rawPath)
|
|
1536
|
+
const rel = relative(root, abs).replace(/\\/g, "/")
|
|
1537
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel) || seen.has(rel)) continue
|
|
1538
|
+
seen.add(rel)
|
|
1539
|
+
|
|
1540
|
+
// 1. Skrip gate/evaluator kritis tidak boleh berubah sama sekali.
|
|
1541
|
+
if (EVALUATOR_GATE_FILES.has(rel)) {
|
|
1542
|
+
offending.push(rel)
|
|
1543
|
+
continue
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
// 2. `package.json`: hanya bagian script test/verify/lint/gate yang relevan.
|
|
1547
|
+
if (rel === "package.json") {
|
|
1548
|
+
let current: string
|
|
1549
|
+
try {
|
|
1550
|
+
current = await safeReadFile(abs, root)
|
|
1551
|
+
} catch {
|
|
1552
|
+
continue // file terhapus: bukan manipulasi script.
|
|
1553
|
+
}
|
|
1554
|
+
const baselineText = opts.baselineContentByFile?.get(rel) ?? gitBaselineContent(root, rel)
|
|
1555
|
+
if (baselineText == null) {
|
|
1556
|
+
// Tanpa baseline bentuk script tak bisa dibuktikan → fail-closed.
|
|
1557
|
+
offending.push(rel)
|
|
1558
|
+
continue
|
|
1559
|
+
}
|
|
1560
|
+
const before = verificationScriptsFingerprint(baselineText)
|
|
1561
|
+
const after = verificationScriptsFingerprint(current)
|
|
1562
|
+
if (before === null || after === null || before !== after) offending.push(rel)
|
|
1563
|
+
continue
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// 3. File test: hanya `.skip(`/`.todo(` BARU yang dihitung manipulasi.
|
|
1567
|
+
if (rel.startsWith("test/") && rel.endsWith(".test.ts")) {
|
|
1568
|
+
let current: string
|
|
1569
|
+
try {
|
|
1570
|
+
current = await safeReadFile(abs, root)
|
|
1571
|
+
} catch {
|
|
1572
|
+
continue
|
|
1573
|
+
}
|
|
1574
|
+
const baselineText = opts.baselineContentByFile?.get(rel) ?? gitBaselineContent(root, rel)
|
|
1575
|
+
// Tanpa baseline di git (file baru): semua skip/todo dianggap baru.
|
|
1576
|
+
const beforeCount = baselineText == null ? 0 : countSkipTodo(baselineText)
|
|
1577
|
+
if (countSkipTodo(current) > beforeCount) offending.push(rel)
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
if (offending.length === 0) {
|
|
1582
|
+
return { tampered: false, reason: "evaluation surface unchanged", offendingFiles: [] }
|
|
1583
|
+
}
|
|
1584
|
+
return {
|
|
1585
|
+
tampered: true,
|
|
1586
|
+
reason: `evaluation tampering: modified evaluator/test surfaces [${offending.join(", ")}]`,
|
|
1587
|
+
offendingFiles: offending,
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
/**
|
|
1592
|
+
* Kumpulkan daftar file yang terakhir dimutasi secara committed dalam jurnal
|
|
1593
|
+
* sesi (mengikuti write/edit/apply_patch, move_file, dan menghapus file yang
|
|
1594
|
+
* memang dihapus lewat delete_file). Record sintetis `pending` tanpa terminal
|
|
1595
|
+
* committed diabaikan agar tidak menimbulkan klaim palsu.
|
|
1596
|
+
*/
|
|
1597
|
+
export function collectModifiedFilesFromJournal(records: readonly JournalRecord[]): string[] {
|
|
1598
|
+
const byId = new Map<string, JournalRecord[]>()
|
|
1599
|
+
for (const r of records) {
|
|
1600
|
+
if (r.kind && r.kind !== "mutation") continue
|
|
1601
|
+
const list = byId.get(r.id) ?? []
|
|
1602
|
+
list.push(r)
|
|
1603
|
+
byId.set(r.id, list)
|
|
1604
|
+
}
|
|
1605
|
+
const ordered = [...byId.values()].sort((a, b) => a[0]!.seq - b[0]!.seq)
|
|
1606
|
+
const active = new Set<string>()
|
|
1607
|
+
for (const group of ordered) {
|
|
1608
|
+
const intent = group[0]!
|
|
1609
|
+
const committed = group.some((r) => r.state === "committed")
|
|
1610
|
+
if (!committed) continue
|
|
1611
|
+
const paths = intent.paths ?? []
|
|
1612
|
+
if (paths.length === 0) continue
|
|
1613
|
+
if (intent.tool === "write_file" || intent.tool === "edit" || intent.tool === "apply_patch") {
|
|
1614
|
+
for (const p of paths) active.add(p)
|
|
1615
|
+
} else if (intent.tool === "delete_file") {
|
|
1616
|
+
for (const p of paths) active.delete(p)
|
|
1617
|
+
} else if (intent.tool === "move_file") {
|
|
1618
|
+
if (paths[0]) active.delete(paths[0])
|
|
1619
|
+
if (paths[1]) active.add(paths[1])
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
return [...active]
|
|
1623
|
+
}
|