dsh-boost 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +97 -33
- package/README.md +85 -32
- package/dist/gate/decide.js +33 -2
- package/dist/gate/decide.js.map +1 -1
- package/dist/hooks/llm-stream.js +129 -54
- package/dist/hooks/llm-stream.js.map +1 -1
- package/dist/hooks/post-execute.js +104 -21
- package/dist/hooks/post-execute.js.map +1 -1
- package/dist/hooks/session-state.js +18 -8
- package/dist/hooks/session-state.js.map +1 -1
- package/dist/index.js +371 -67
- package/dist/index.js.map +1 -1
- package/dist/scope/doc.js.map +1 -1
- package/dist/scope/store.js +24 -9
- package/dist/scope/store.js.map +1 -1
- package/package.json +8 -4
- package/dist/admission/fixed-cost.d.ts +0 -23
- package/dist/admission/ledger.d.ts +0 -113
- package/dist/admission/retrieval.d.ts +0 -65
- package/dist/admission/usage.d.ts +0 -75
- package/dist/config.d.ts +0 -43
- package/dist/gate/binding.d.ts +0 -113
- package/dist/gate/decide.d.ts +0 -82
- package/dist/gate/guard.d.ts +0 -69
- package/dist/gate/invalidate.d.ts +0 -112
- package/dist/gate/plan.d.ts +0 -86
- package/dist/hooks/clock.d.ts +0 -68
- package/dist/hooks/execute.d.ts +0 -79
- package/dist/hooks/llm-stream.d.ts +0 -283
- package/dist/hooks/pending.d.ts +0 -89
- package/dist/hooks/post-execute.d.ts +0 -257
- package/dist/hooks/session-state.d.ts +0 -158
- package/dist/hooks/synthesize.d.ts +0 -74
- package/dist/host/loader.d.ts +0 -23
- package/dist/host/platform.d.ts +0 -18
- package/dist/host/root.d.ts +0 -25
- package/dist/projection/apply.d.ts +0 -174
- package/dist/projection/canonicalise.d.ts +0 -43
- package/dist/projection/counters.d.ts +0 -65
- package/dist/projection/truncate.d.ts +0 -47
- package/dist/prompt/protocol.d.ts +0 -45
- package/dist/receipts/store.d.ts +0 -198
- package/dist/scope/doc.d.ts +0 -117
- package/dist/scope/resolve.d.ts +0 -91
- package/dist/scope/store.d.ts +0 -135
- package/dist/selector/jev.d.ts +0 -93
- package/dist/tools/boost.d.ts +0 -380
- package/dist/tools/family.d.ts +0 -26
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-execute.js","sourceRoot":"","sources":["../../src/hooks/post-execute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2EG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAI1D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAC1C,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAGnE,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAEjD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AACpF,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AAEpE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAG5D,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAG1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAEvF,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAG7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,EACL,eAAe,EACf,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,UAAU,GACX,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAExC,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,WAAW,E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AED,oCAAoC;AACpC,SAAS,eAAe,CAAC,GAAkB,EAAE,IAAc,EAAE,KAA0B;IACrF,GAAG,CAAC,EAAE,CAAC,eAAe,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAC/E,CAAC;AAED,kFAAkF;AAClF,SAAS,uBAAuB,CAAC,GAAkB,EAAE,KAA6B;IAChF,GAAG,CAAC,YAAY,CAAC,OAAO,CAAC;QACvB,IAAI,EAAE,aAAa;QACnB,KAAK,EAAE,cAAc;QACrB,WAAW,EAAE,KAAK;QAClB,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC;KAChD,CAAC,CAAA;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,aAAa,CAAC,GAAkB,EAAE,IAAc;IAC9D,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,IAAI,IAAI,mBAAmB,EAAE,CAAA;IAC5D,+EAA+E;IAC/E,6EAA6E;IAC7E,0EAA0E;IAC1E,4DAA4D;IAC5D,IAAI,CAAC,YAAY,GAAG,KAAK,CAAA;IACzB,0EAA0E;IAC1E,2EAA2E;IAC3E,+DAA+D;IAC/D,IAAI,CAAC,MAAM,KAAK,GAAG,CAAC,MAAM,CAAA;IAC1B,uBAAuB,CAAC,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACxC,mBAAmB,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;IACrC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC5B,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;AACnC,CAAC","sourcesContent":["/**\n * Host hook assembly: the four mount points the plugin owns, and the\n * post-execute decision path that turns the gate into a working product.\n *\n * Registration stays split one function per mount so each body can be replaced\n * without rewriting the mount:\n *\n * - `tools/post-execute` first gates on the same cached scope judgement the\n * protocol section reads, then canonicalises the result and runs a\n * conservative invalidation check. It files the arriving receipt under\n * `'root'`, works the substitution decision (`decide` → admission → pending\n * queue / shadow receipt / fallback), then the double-projection guard, and\n * finally projects the receipt when the scope document asks for it. Order is\n * fixed: `next() → scope gate → canonicalise → invalidate → decide →\n * (shadow receipt | admit and enqueue | fallback) → double-projection guard →\n * projection → return the decision` (plan §Task 23b). A call with no\n * `exec.agent` is not the plugin's to inspect: the downstream decision is\n * returned untouched and a `skip:no-scope` receipt keeps the pass visible\n * (design §5.5). A call carrying `exec.parent` is a PTC inner dispatch and\n * returns before any of this: it is not the step's root receipt.\n * - `llm/stream` is the model-request waterfall. Its body lives in\n * `./llm-stream.ts` (Task 23c-1) and is re-exported below: it lets the\n * plugin's own selector request through untouched, then answers a pending\n * decision with a synthesized turn or delegates to `next()` after the\n * turn/anchor checks. The mount is registered here because `registerHooks`\n * is the single assembly surface.\n * - `tools/execute` looks the session's pending substitution up with `peek`\n * (never `take`: the entry must survive to this hook), compares the arriving\n * `callId` itself. A **differing** `callId` is not tampering: the host assigns\n * call ids and our synthesized turn sets the one we chose, so a call carrying\n * a different id is an ordinary call that has nothing to do with the\n * substitution — it passes through untouched. Only when the ids are equal does\n * `rejectIfTampered` run, and only then is the entry cleared (on accept or\n * reject), because the entry has then served its purpose.\n * - the `systemPrompt` section reads the per-agent judgement cache\n * synchronously. Its `text` must be a function, never a static string: a\n * static string would inject the protocol into every session unconditionally\n * and defeat the scope document (design §5.5).\n *\n * ## What Task 23b added\n *\n * The receipt map (`ReceiptSessionState`) keys `'root'` to the receipt that\n * just arrived and each executed candidate's id to its own receipt, so guards\n * and `$public` templates always read the arrival-time canonical text and a\n * later step can project a value from an earlier step. The executable args\n * always come from the *decision* (`decision.args` / `decision.candidates[i]\n * .args`), never from `plan.steps[i].args`, which still holds `$public`\n * templates. A plan is one-shot per receipt: the first post-execute that reads\n * it removes it, so neither a guard failure nor a commit can leave the block\n * alive to fire against a later receipt (the model writes a new block for its\n * next call). It also means `decide` cannot re-commit the same step.\n *\n * The `shadow` flag from the scope document drives both `decide` (which skips\n * the whitelist) and the record-only branch: a shadow commit writes a\n * `{kind:'shadow'}` receipt and neither enqueues nor takes budget. It does\n * **not** suppress projection: `shadow` and `projection` are independent\n * switches (design §5.2-5), and projection-shadow mode writes only its\n * accounting receipt. Admission runs in the mandated order — existence,\n * `worthSubstituting`, then `budget.take()` — so a fallback never spends budget\n * for a call it did not substitute.\n *\n * Everything here is contained: the host turns a throwing `post-execute`\n * listener into an error result and the tool's real output is lost, so every\n * foreign call (stores, queue, clock, usage, estimator) is wrapped. The\n * `tools/execute` mount is contained too, failing open on an internal error:\n * the design's fail-closed definition is \"pass through, do not substitute\",\n * never \"intercept the call\" (design §5.5).\n *\n * The provider's `c.scope` is the agent itself at runtime: the host builds the\n * assembly context as `{ agent, scope: agent, signal }`\n * (`@deepseek-ai/dsh-agent/lib/index.js:410`), even though the declared type is\n * the opaque `ScopeKey`. Keying the cache on anything else — or falling back to\n * a no-argument judgement — would leak one session's visibility into another.\n *\n * @module dsh-boost/hooks/post-execute\n */\nimport { worthSubstituting } from '../admission/ledger.js'\nimport type { StepBudget } from '../admission/ledger.js'\nimport type { RetrievalLedger } from '../admission/retrieval.js'\nimport type { UsageLedger } from '../admission/usage.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { decide } from '../gate/decide.js'\nimport { alreadySpilled, looksPruned } from '../gate/invalidate.js'\nimport type { AnchorStore, ReceiptAnchors } from '../gate/invalidate.js'\nimport type { Candidate, Guard, Plan } from '../gate/plan.js'\nimport { isPosixOnly } from '../host/platform.js'\nimport type { ProjectionCounters } from '../projection/counters.js'\nimport { PROTOCOL_NAME, PROTOCOL_ORDER, PROTOCOL_TEXT } from '../prompt/protocol.js'\nimport { projectApply, projectShadow } from '../projection/apply.js'\nimport type { FormatFooter, ProjectionMode, SpillBackend, SpillHandle } from '../projection/apply.js'\nimport { canonicalise } from '../projection/canonicalise.js'\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport type { ReceiptStore } from '../receipts/store.js'\nimport { DEFAULT_SCOPE, isVisible } from '../scope/doc.js'\nimport type { ScopeDoc } from '../scope/doc.js'\nimport type { ScopeStore } from '../scope/store.js'\nimport { SELECTOR_SYSTEM_PROMPT, choose, selectorPromptText } from '../selector/jev.js'\nimport type { LlmLike } from '../selector/jev.js'\nimport { familyOf } from '../tools/family.js'\nimport type { AbortSignalLike, AgentLike, BoostConfig, PluginContext } from '../types.js'\nimport type { TurnClock } from './clock.js'\nimport { rejectIfTampered } from './execute.js'\nimport {\n receiptsStopped,\n sessionBudget,\n sessionClock,\n sessionUsage,\n settleDiscarded,\n streamHook,\n} from './llm-stream.js'\nimport type { SessionRuntime } from './llm-stream.js'\nimport { callIdFor } from './pending.js'\nimport type { PendingEntry, PendingQueue } from './pending.js'\nimport {\n ReceiptSessionState,\n appendReceipt,\n callPreview,\n clearAnchors,\n clearPlan,\n clearPending,\n clockTurnOf,\n peekPending,\n previewOf,\n} from './session-state.js'\nimport type { ReceiptInput } from './session-state.js'\n\n/**\n * The `llm/stream` body lives in its own module (Task 23c-1). It is re-exported\n * here because `registerHooks` is the assembly surface the rest of the plugin\n * and the integration tests import; the mount below uses the same function.\n */\nexport { streamHook }\n\n/**\n * The substitution whitelist: exactly the read-only trio (design §5.2-5).\n *\n * One constant drives both `decide` (non-shadow) and the `whitelisted` field\n * written to the shadow/substitute receipts, so the policy the gate enforced\n * and the policy the audit trail reports cannot drift. `bash`, `web_fetch` and\n * every write tool stay out: they have no deterministic read-only judgement.\n */\nexport const SUBSTITUTION_WHITELIST: ReadonlySet<string> = new Set(['read', 'grep', 'glob'])\n\n/**\n * Hard cap on the receipt text shown to the selector.\n *\n * A full 40 KB receipt would dominate the selector call before the candidate\n * summaries are added. This cap keeps the receipt near 300 tokens even when the\n * tool family's projection window is larger, while still showing the\n * projection's head/tail shape. The actual input+output charge is computed\n * from the text that is sent, never from this cap alone.\n */\nconst SELECTOR_RECEIPT_MAX_CHARS = 1_200\n\n/** The route an `ask-selector` request inherits from the boundary request. */\nexport interface SelectorRoute {\n provider: string\n model: string\n reasoningEffort?: string\n}\n\n/** The dependencies the mounts read; Task 23c constructs the whole set once. */\nexport interface HookDeps {\n config: BoostConfig\n scope: ScopeStore\n receipts: ReceiptStore\n /**\n * Per-session receipt anchors (design §5.2-7).\n *\n * Written by the decision path on a real commit and read here to detect an\n * external rewrite; a hit clears them. Required by the contract: without a\n * store the invalidation check is silently dead.\n */\n anchors: AnchorStore\n /**\n * Session id to workspace id.\n *\n * Required: substitution is refused for a session that does not resolve to a\n * workspace, or whose live scope document does not list that workspace. The\n * judgement cache alone can be stale, and the replacement path must never\n * run without a current visibility answer (design §5.5). Returning\n * `undefined` is fail-closed, never an error.\n */\n resolveSession: (sessionId: string) => string | undefined\n /** At most one pending substitution per session; absent means the path is inert. */\n queue?: PendingQueue\n /**\n * Per-turn substitution budget; absent means no cap is applied. Used only\n * when `sessions` is absent, so a shared instance is never preferred over\n * the per-session runtime.\n */\n budget?: StepBudget\n /** Usage pairing; the shared fallback when `sessions` is absent (T21/T23c). */\n usage?: UsageLedger\n /**\n * The host turn/step clock; `step()` is the only source of a call id's step.\n * The shared fallback when `sessions` is absent.\n */\n clock?: TurnClock\n /**\n * Per-session clock, budget and usage (Task 23c).\n *\n * A shared `clock` lets another session's turn/step stamp this session's\n * `callId`; a shared `StepBudget` starves a session; a shared `UsageLedger`\n * pairs one session's substitution with another session's request. When\n * supplied, this runtime is authoritative and the three single instances\n * above are only the fallback for a plugin wired without it. 23c-2 constructs\n * one `SessionRuntime`, drives `onModelRequest` from the host's\n * `agent/request` payload, and passes it here.\n */\n sessions?: SessionRuntime\n /**\n * The host LLM service, used only for the `ask-selector` call.\n *\n * Optional so a minimal assembly (or a unit test of the decision path)\n * degrades to a record-only abstention rather than crashing. The selector\n * request carries `purpose: 'boost-selector'`, which the frozen stream hook\n * lets through untouched (Task 23c-2).\n */\n llm?: LlmLike\n /**\n * The effective provider/model of the session's latest model request.\n *\n * The selector request must inherit the boundary request's route; this hook\n * has no `GenerateOptions` of its own, so 23c-2 captures it from the\n * `agent/request` waterfall and exposes it here. Missing means the selector\n * cannot run and `ask-selector` records an abstention.\n */\n selectorRoute?: (sessionId: string) => SelectorRoute | undefined\n /** Parsed plans per session, written by 23c's stream hook. */\n plans?: Map<string, Plan>\n /**\n * The per-session receipt/dispatch store. Optional so 23c can own the\n * instance and call `clear(sessionId)` on a session-end signal; when omitted,\n * `registerHooks` creates one. Lifetime: the store keeps one host turn's\n * receipts and in-flight dispatches per session, folds them on the first call\n * of a new turn, and otherwise retains the last turn until `clear` (or process\n * exit). The class documents the reasoning.\n */\n sessionState?: ReceiptSessionState\n /** The host spill backend; absent skips apply-mode projection. */\n spill?: SpillBackend\n /**\n * Session → spill locators of the receipts this plugin projected.\n *\n * Its only producer is a real spill write (design §5.3): the applied outcome\n * carries the locator, and a later `read`/`grep` naming it becomes a\n * `projection-retrieval` receipt whose cost is subtracted from the projection\n * net. Optional so a minimal assembly degrades to uncounted retrievals rather\n * than crashing; `apply` constructs one and `clearSession` drops a session's\n * set on disposal.\n */\n retrievals?: RetrievalLedger\n /**\n * Projection skip counters (Task 25 review).\n *\n * `projectDecision` increments the unknown-family counter when a tool name has\n * no configured family, so status can distinguish \"no window, by design\"\n * from \"the mapper missed a decorated name\".\n */\n projectionCounters?: ProjectionCounters\n /**\n * Token estimator; absent means no meter.\n *\n * Projection still clips, but records `estimate:'unknown'` and no token\n * numbers; substitution is refused before it can spend money (design §9).\n */\n estimateText?: (t: string) => number\n /**\n * Which estimator produced a projection receipt's numbers.\n *\n * `host` means the synchronous host token meter priced it. `unknown` is the\n * only meterless value: a projection without a meter still clips, but its\n * receipt carries `estimate:'unknown'` and no numbers at all. There is\n * deliberately no characters-over-four arm — a fixed-density guess is not a\n * measurement, and admitting the type would let a future producer stamp a\n * fabricated figure as if the host had measured it.\n */\n estimateKind?: 'host' | 'unknown'\n /**\n * The host spill-notice predicate, injected instead of imported.\n *\n * Kept because the host spill policy is not declared as a dependency at all and a\n * test needs to hand over a throwing predicate without the host package.\n * Production omits it and the dynamically imported host function is used.\n */\n hasSpillNotice?: (text: string) => boolean\n /**\n * The host spill footer renderer, injected instead of imported.\n *\n * The same seam and the same reason as {@link hasSpillNotice}: the notice\n * module is reached by `import()` only, and a test must be able to exercise\n * the \"module absent\" path (which disables apply-mode projection) without\n * uninstalling the host package. Returning `undefined` means the module has\n * no renderer; production omits this and the dynamically imported host\n * function is used.\n */\n resolveFooter?: () => FormatFooter | undefined | Promise<FormatFooter | undefined>\n /**\n * The session's runtime replay horizon (design §5.3), when the assembly can\n * supply it.\n *\n * The horizon is `min(config horizon, mean of the session's last\n * `historyTurns` turns)`. Its instance (`RuntimeStepHorizon`) is built in\n * `src/index.ts` and read there by `status`; the decision path can only see\n * it through this seam. A projection receipt pins whatever this returns, so\n * a historical saving is never re-valued by a later cross-session minimum.\n * Absent (the current production wiring) means the resolved config's\n * `horizonSteps` is the horizon in effect.\n */\n horizonFor?: (sessionId: string) => number\n /**\n * Drop the per-session dispatch mirror on disposal.\n *\n * `clearSession` lives in the stream hook and the mirror lives here, so the\n * teardown reaches it through this seam rather than exporting the map. Wired\n * by `apply`; absent in tests, which is why it is optional and guarded.\n */\n clearAcceptedDispatch?: (sessionId: string) => void\n /**\n * The host logger, for the few conditions that have no other surface.\n *\n * `registerHooks` fills it from `ctx.logger` when absent, so production never\n * passes it explicitly. A missing footer renderer is the one current caller:\n * it logs once, and `status` reports the same condition as a stable code.\n */\n logger?: { warn(message: string): void }\n}\n\n/** The execution facts a `tools/post-execute` listener reads here. */\ntype PostExecuteExec = {\n name?: string\n callId?: string\n agent?: AgentLike | undefined\n /**\n * The host's cancellation signal. `tools/post-execute` is async, and the\n * host contract requires async listeners to observe `exec.signal`; this\n * listener reads `aborted` before it does any projection work.\n */\n signal?: AbortSignalLike | undefined\n /** Parsed tool arguments; the retrieval matcher reads them (Task 25). */\n arguments?: unknown\n /**\n * PTC transport token. Present on an SDK sub-dispatch (`tools/execute` and\n * `tools/post-execute` run for inner calls too), where the result belongs to\n * the enclosing `run_code` step and is not the step's root receipt.\n */\n parent?: unknown\n}\n\n/** The normalized result fields canonicalisation reads. */\ntype PostExecuteResult = {\n content?: ReadonlyArray<{ type: string; text?: string }> | undefined\n isError?: boolean | undefined\n}\n\n/**\n * A post-execute decision.\n *\n * Only `kind` is interpreted here; every other field belongs to the host\n * contract (`accept` with content/value, or `block`).\n */\ntype PostExecuteDecision = {\n kind: 'accept' | 'block'\n [key: string]: unknown\n}\n\n/** The dispatch fields the tamper check reads (the host passes a `ToolExecution`). */\ntype DispatchExec = {\n name: string\n arguments: unknown\n /** Host-issued call id; compared here because `rejectIfTampered` never sees it. */\n callId?: string\n agent?: AgentLike | undefined\n}\n\n/** Everything one decision pass needs, computed once by the listener. */\ntype DecisionContext = {\n sessionId: string\n exec: PostExecuteExec\n receipt: CanonicalReceipt\n doc: ScopeDoc\n result: PostExecuteResult | undefined\n state: ReceiptSessionState\n turn: number\n /** The tool call itself names one of this session's spill locators. */\n retrievalCall?: boolean\n}\n\n/** Skip reasons that mean the projection machinery degraded, not \"nothing to cut\". */\nconst PROJECTION_DEGRADATIONS: ReadonlySet<string> = new Set([\n 'no-spill',\n 'no-owner',\n 'projection-skipped:no-footer',\n 'spill-failed',\n 'footer-failed',\n])\n\n/** The judgement-cache key carried by the assembly context's `scope`. */\nfunction agentKeyOf(scope: unknown): string | undefined {\n const id = (scope as AgentLike | undefined)?.session?.header?.id\n return typeof id === 'string' ? id : undefined\n}\n\n/** The session a hook call belongs to, or `undefined` when the host supplied none. */\nfunction sessionIdOf(exec: PostExecuteExec | DispatchExec | undefined): string | undefined {\n const id = (exec as PostExecuteExec | undefined)?.agent?.session?.header?.id\n return typeof id === 'string' ? id : undefined\n}\n\n/**\n * Whether the host cancelled the call that produced this result.\n *\n * `tools/post-execute` is async, and the host contract (`dsh-tools`'\n * `events.d.ts`) requires async listeners to observe `exec.signal`. A\n * cancelled call's result never reaches the model, so projecting it would pay\n * a spill write and persist an artifact nobody can read. The signal crosses\n * the host boundary, so a malformed one means \"not cancelled\" rather than a\n * reason to throw out of the hook.\n */\nfunction cancelled(exec: PostExecuteExec | undefined): boolean {\n try {\n return exec?.signal?.aborted === true\n } catch {\n return false\n }\n}\n\n/**\n * The protocol section's synchronous provider.\n *\n * It may only read the cached judgement: the host assembles prompts\n * synchronously, so there is nothing to await. A missing store, a store without\n * `judgement`, a context without `scope`, and a scope without a session id all\n * mean \"inject nothing\" (fail-closed, design §5.5).\n */\nfunction protocolText(scope: ScopeStore | undefined, context: { scope?: unknown }): string {\n if (scope == null || typeof scope.judgement !== 'function') return ''\n const key = agentKeyOf(context?.scope)\n if (key === undefined) return ''\n return scope.judgement(key) ? PROTOCOL_TEXT : ''\n}\n\n// ---------------------------------------------------------------------------\n// Defensive readers: every foreign call is wrapped\n// ---------------------------------------------------------------------------\n\n/**\n * The host step index, or `undefined` when no clock can supply one.\n *\n * `undefined` is fail-closed: the decision path refuses to invent a step\n * (a plugin-side counter would collide two substitutions in one turn — T23a).\n */\nfunction clockStepOf(deps: HookDeps, sessionId: string): number | undefined {\n try {\n const step = sessionClock(deps, sessionId)?.step()\n return typeof step === 'number' && Number.isFinite(step) ? step : undefined\n } catch {\n return undefined\n }\n}\n\n/** The session's anchors without ever failing the call. */\nfunction pendingAnchorsOf(deps: HookDeps, sessionId: string): ReceiptAnchors | undefined {\n try {\n return deps.anchors?.get(sessionId)\n } catch {\n return undefined\n }\n}\n\n/**\n * The only invalidation branch that is live at this call site: the prune marker.\n *\n * `invalidate` also compares the anchor text, but a `tools/post-execute` receipt\n * is a *different* call's body, so that comparison can never establish the\n * anchored receipt's identity here; it would fire `compaction-reset` after every\n * commit, drop the anchors obligation 10 exists to keep for 23c, and skip one\n * decision (review F1). The anchor branch belongs on the model-request path\n * (`llm/stream`, 23c), where the compared text is the anchored receipt's current\n * body in the outgoing messages.\n */\nfunction markerResetOf(\n pending: ReceiptAnchors,\n receiptText: string,\n): 'pruned-reset' | undefined {\n try {\n if (pending == null) return undefined\n return looksPruned(receiptText) ? 'pruned-reset' : undefined\n } catch {\n return undefined\n }\n}\n\n/** Write one ledger record, keyed to the session and host turn. */\nfunction ledgerEntry(\n ctx: DecisionContext,\n kind: 'shadow' | 'projection' | 'skip',\n code: string,\n extra: Record<string, unknown> = {},\n): ReceiptInput {\n return {\n version: 1,\n ts: new Date().toISOString(),\n sessionId: ctx.sessionId,\n turn: ctx.turn,\n kind,\n code,\n ...(typeof ctx.exec.name === 'string' ? { tool: ctx.exec.name } : {}),\n // The operator's evidence line: the canonical receipt head and the executed\n // args. Without args every same-tool/same-turn receipt hashed identically\n // (stepId is always 'root').\n preview: previewOf(ctx.receipt.text),\n ...(ctx.exec.arguments !== undefined ? { args: ctx.exec.arguments } : {}),\n ...extra,\n }\n}\n\n/**\n * Caps on the plan evidence a substitution receipt carries.\n *\n * G2 (design line 71) requires the receipt to answer \"why was the model not\n * asked\" with 计划、守卫、绑定、回执、节省量; without the plan and the guards an\n * auditor sees what ran but not why it was legitimate. The plan is\n * model-written text though, and a receipt is one line: 256 code points of\n * goal (the same order as `preview`), at most 8 guards, and at most 300 code\n * points per guard. The bound is a *code-point* cap, not a byte cap: one\n * pathological plan can contribute up to ~9.6 KB from the guards alone\n * (8 × 300 code points × 4 UTF-8 bytes for 4-byte characters) plus up to\n * ~1 KB from the 256-code-point goal. That is bounded and auditable, but a\n * receipt line can exceed 10 KB — status and readers must not assume 2.7 KB.\n * Truncation is always visible: the goal ends in `…`, an oversized guard\n * becomes `{truncated_json: \"…\"}`, and `guards_total` is present whenever\n * guards were left out.\n */\nconst MAX_RECEIPT_PLAN_CODE_POINTS = 256\nconst MAX_RECEIPT_GUARDS = 8\nconst MAX_RECEIPT_GUARD_CODE_POINTS = 300\n\n/** What a substitute, substitute-settled or shadow receipt adds about its plan. */\nexport interface SubstitutionEvidence {\n /** The plan's goal, capped to {@link MAX_RECEIPT_PLAN_CODE_POINTS}. */\n plan: string\n /** The committed candidate's guards, up to {@link MAX_RECEIPT_GUARDS}. */\n guards: unknown[]\n /** The plan's guard count, present only when `guards` was capped. */\n guards_total?: number\n}\n\n/**\n * A queued entry carrying the evidence the synth-time receipt needs.\n *\n * `PendingEntry` is the one object that travels from the commit (post-execute)\n * to synthesis (llm-stream), so the evidence rides on it; the settle afterwards\n * reads it back from the ledger pairing. The extra field is additive and never\n * dispatched: `synthesizeTurn` reads `name`/`args` only.\n */\nexport type AuditedPendingEntry = PendingEntry & { evidence?: SubstitutionEvidence }\n\n/** Cap a string by code point so a surrogate pair is never split. */\nfunction capText(value: string, cap: number): string {\n const points = Array.from(value)\n if (points.length <= cap) return value\n return `${points.slice(0, Math.max(0, cap - 1)).join('')}…`\n}\n\n/**\n * The plan/goal and guard evidence for one committed candidate.\n *\n * Guards are carried as written while they fit. Only a guard whose own JSON\n * exceeds {@link MAX_RECEIPT_GUARD_CODE_POINTS} (a multi-KB `text_contains`,\n * say) is replaced by a `truncated_json` marker, so the array stays bounded\n * without silently dropping the guard's form.\n */\nexport function substitutionEvidence(\n goal: unknown,\n guards: readonly Guard[],\n): SubstitutionEvidence {\n const carried = guards.slice(0, MAX_RECEIPT_GUARDS).map((guard) => {\n const json = JSON.stringify(guard) ?? ''\n return Array.from(json).length <= MAX_RECEIPT_GUARD_CODE_POINTS\n ? guard\n : { truncated_json: capText(json, MAX_RECEIPT_GUARD_CODE_POINTS) }\n })\n return {\n plan: capText(typeof goal === 'string' ? goal : '', MAX_RECEIPT_PLAN_CODE_POINTS),\n guards: carried,\n ...(guards.length > MAX_RECEIPT_GUARDS ? { guards_total: guards.length } : {}),\n }\n}\n\n/**\n * Append one `skip:no-scope` receipt.\n *\n * The no-agent case has no session id and no turn; the empty session id and\n * turn zero are honest placeholders, and the `code` is the field status counts.\n */\nasync function appendSkipNoScope(\n receipts: ReceiptStore | undefined,\n exec: PostExecuteExec | undefined,\n sessionId = '',\n turn = 0,\n): Promise<void> {\n if (receipts == null || typeof receipts.append !== 'function') return\n try {\n await receipts.append({\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn,\n kind: 'skip',\n code: 'skip:no-scope',\n tool: exec?.name,\n })\n } catch {\n // A receipt is evidence, not a precondition: never break the call for it.\n }\n}\n\n/** Append one invalidation receipt; a receipt failure never breaks the call. */\nasync function appendResetReceipt(\n receipts: ReceiptStore | undefined,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n stepId: string,\n code: 'pruned-reset' | 'compaction-reset',\n): Promise<void> {\n if (receipts == null || typeof receipts.append !== 'function') return\n try {\n await receipts.append({\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn,\n stepId,\n kind: 'reset',\n code,\n tool: exec?.name,\n })\n } catch {\n // A receipt is evidence, not a precondition: never break the call for it.\n }\n}\n\n/**\n * Abandon the pending decision after an external rewrite.\n *\n * Only the plugin's own anchor record is touched — the session log's current\n * body is never read (design §5.2-7). Clearing happens before the receipt write\n * so a stalled store cannot leave the stale anchors in place; both steps are\n * contained so the tool result survives.\n *\n * The decision-time usage mark is settled **without** a settlement receipt\n * first, exactly like `applyAbandon`: the substitution was never synthesized,\n * so there is no saving to report. Leaving the mark would let the next real\n * request pair itself with it and write a `substitute-settled` line for a\n * substitution that never ran (row 1).\n */\nasync function resetInvalidatedPending(\n deps: HookDeps,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n pending: ReceiptAnchors,\n code: 'pruned-reset' | 'compaction-reset',\n): Promise<void> {\n // Design §5.2-7: a reset returns to the slow path *and* empties pending, so no\n // queued substitution can fire from anchors that no longer name live text. The\n // plan is dropped too: it was written for the invalidated receipt, and leaving\n // it would let it fire against a later one. A dispatch accepted for the\n // invalidated decision must not settle a later mark that reuses its id.\n clearAcceptedDispatch(deps, sessionId)\n settleDiscarded(deps, sessionId)\n clearAnchors(deps, sessionId)\n clearPending(deps, sessionId)\n clearPlan(deps, sessionId)\n await appendResetReceipt(deps.receipts, exec, sessionId, turn, pending.stepId, code)\n}\n\n/**\n * The host's spill-notice predicate, resolved at most once per process.\n *\n * The spill policy is never declared as a dependency (design §5.4), so its notice module is\n * imported dynamically: a static import would make the plugin fail to load on\n * a host without it. A missing package means no receipt can carry its footer,\n * so the guard simply does not fire. The deps seam wins, which is what keeps\n * the guard testable without the host.\n */\nlet noticePredicate: Promise<((text: string) => boolean) | undefined> | undefined\n\nfunction resolveNoticePredicate(\n deps: HookDeps,\n): Promise<((text: string) => boolean) | undefined> {\n if (typeof deps.hasSpillNotice === 'function') return Promise.resolve(deps.hasSpillNotice)\n noticePredicate ??= import('@deepseek-ai/dsh-spill-policy/notice')\n .then((module) => (typeof module.hasSpillNotice === 'function' ? module.hasSpillNotice : undefined))\n .catch(() => undefined)\n return noticePredicate\n}\n\n/**\n * The host's spill footer renderer, resolved lazily.\n *\n * `projectApply` cannot statically import the spill policy for the same reason\n * the notice predicate cannot. A missing package makes apply-mode projection\n * degrade to `projection-skipped:no-footer` in `projectApply` itself — and,\n * because that turns the plugin's headline feature off, the first resolution\n * that yields nothing is logged once (never per receipt, which would drown the\n * log of a busy session). `status` maps the same receipt code to\n * `ERR_HOST_NO_SPILL_NOTICE`, so the degradation also reaches the operator who\n * never reads the log.\n */\nlet footerFormatter: Promise<FormatFooter | undefined> | undefined\n/** One warning per process; a missing host module is not a per-call event. */\nlet footerMissingLogged = false\n\n/** Log the missing-footer degradation once; a foreign logger must not throw. */\nfunction noteMissingFooter(deps: HookDeps): void {\n if (footerMissingLogged) return\n footerMissingLogged = true\n try {\n deps.logger?.warn?.(\n 'dsh-boost: ERR_HOST_NO_SPILL_NOTICE: @deepseek-ai/dsh-spill-policy/notice resolved no formatSpillNotice; ' +\n 'apply-mode projection is disabled (projection-skipped:no-footer) until the host spill policy is available',\n )\n } catch {\n // A logger failure must not become a tool failure.\n }\n}\n\nfunction resolveFooterFormatter(deps: HookDeps): Promise<FormatFooter | undefined> {\n // The seam wins over the memoised import, exactly like `hasSpillNotice`: a\n // test states \"the module resolved nothing\" without uninstalling the host\n // package. It is deliberately not memoised — it belongs to one deps object.\n if (typeof deps.resolveFooter === 'function') {\n return Promise.resolve()\n .then(() => deps.resolveFooter?.())\n .then((formatter) => {\n if (formatter === undefined) noteMissingFooter(deps)\n return formatter\n })\n .catch(() => {\n noteMissingFooter(deps)\n return undefined\n })\n }\n footerFormatter ??= import('@deepseek-ai/dsh-spill-policy/notice')\n .then((module) => {\n if (typeof module.formatSpillNotice !== 'function') return undefined\n return (omitted: { kind: 'exact'; count: number }, ref: SpillHandle) =>\n // T6's `SpillBackend` widens the host's branded `SpillLocator` to\n // `string`; the value is the same at runtime.\n module.formatSpillNotice(\n omitted,\n ref as unknown as Parameters<typeof module.formatSpillNotice>[1],\n )\n })\n .catch(() => undefined)\n .then((formatter) => {\n if (formatter === undefined) noteMissingFooter(deps)\n return formatter\n })\n return footerFormatter\n}\n\n/**\n * The canonical text of the decision that will enter history, when it carries\n * a content array.\n *\n * The host spill policy registers with `{ prepend: true }`: it calls `next()`\n * and applies its footer to *that* decision, so the footer lives in\n * `decision.content` and never in the `result.content` this listener received.\n * `undefined` means \"the decision carries no content\"; the caller then falls\n * back to the receiver as it arrived.\n */\nfunction decisionTextOf(decision: PostExecuteDecision): string | undefined {\n const content = decision.content\n if (!Array.isArray(content)) return undefined\n return canonicalise(content as ReadonlyArray<{ type: string; text?: string }>, false).text\n}\n\n/**\n * Whether projection must be skipped because the host already spilled this\n * receipt (design §5.4).\n *\n * A predicate that throws counts as \"already spilled\": when the notice cannot\n * be ruled out, a second projection could hide the original twice, so the safe\n * direction is to leave the receipt alone.\n */\nasync function isAlreadySpilled(deps: HookDeps, receiptText: string): Promise<boolean> {\n try {\n const hasNotice = await resolveNoticePredicate(deps)\n return hasNotice !== undefined && alreadySpilled(receiptText, hasNotice)\n } catch {\n return true\n }\n}\n\n/** Whether the plugin is active for this session (fail-closed on any doubt). */\nfunction isActiveSession(deps: HookDeps, sessionId: string): boolean {\n const scope = deps.scope\n if (scope == null || typeof scope.judgement !== 'function') return false\n try {\n return scope.judgement(sessionId)\n } catch {\n return false\n }\n}\n\n/**\n * The live scope document, or the strict default when it cannot be read.\n *\n * Read once per decision pass rather than cached: `boost` writes the document\n * while the plugin runs, and the projection/shadow switches must follow it. A\n * missing or throwing reader degrades to `DEFAULT_SCOPE`, whose `shadow: true`\n * makes the substitution path record-only — the safe direction.\n */\nasync function scopeDocOf(deps: HookDeps): Promise<ScopeDoc> {\n try {\n const read = deps.scope?.read\n if (typeof read !== 'function') return DEFAULT_SCOPE\n const result = await read.call(deps.scope)\n const raw = (result as { doc?: unknown } | undefined)?.doc\n if (raw === null || typeof raw !== 'object') return DEFAULT_SCOPE\n return raw as ScopeDoc\n } catch {\n return DEFAULT_SCOPE\n }\n}\n\n// ---------------------------------------------------------------------------\n// Retrieval accounting\n// ---------------------------------------------------------------------------\n\n/** The calls that can retrieve a spilled artifact (design §5.3). */\nconst RETRIEVAL_TOOLS: ReadonlySet<string> = new Set(['read', 'grep'])\n\n/** A detected retrieval, held until the final visible content is known. */\ntype PendingRetrieval = { locator: string }\n\n/**\n * Detect a retrieval without writing anything yet.\n *\n * Detection has to happen before the visibility gate (a projected receipt\n * consumed context whether or not the workspace is still visible), but the\n * cost must wait until projection has decided what the model will actually\n * see (review I3). The split keeps both properties.\n */\nfunction pendingRetrievalOf(\n deps: HookDeps,\n exec: PostExecuteExec,\n sessionId: string,\n): PendingRetrieval | undefined {\n try {\n const name = exec?.name\n if (typeof name !== 'string' || !RETRIEVAL_TOOLS.has(name)) return undefined\n const ledger = deps.retrievals\n if (ledger == null || typeof ledger.locate !== 'function') return undefined\n const locator = ledger.locate(sessionId, exec.arguments)\n return locator === undefined ? undefined : { locator }\n } catch {\n return undefined\n }\n}\n\n/**\n * The one-time cost of one retrieval, or `undefined` when it cannot be priced.\n *\n * This is the **per-receipt** figure: the call block (name + arguments) plus\n * the content the model saw. The replay multiplier is applied once, to both\n * sides of the net formula, in `status` — multiplying only the cost by the\n * horizon made a cheap partial re-read look like a loss (review C1).\n *\n * `content` is the decision's final visible text, so a retrieval that is itself\n * projected is charged for the window, not the raw result (review I3). A\n * missing/non-finite estimate is omitted rather than fabricated.\n */\nfunction retrievalCostOf(\n deps: HookDeps,\n exec: PostExecuteExec,\n content: string,\n): { callTokens: number; contentTokens: number; totalTokens: number } | undefined {\n const estimate = estimatorOf(deps)\n if (estimate === undefined) return undefined\n\n const contentTokens = safeEstimate(estimate, content)\n if (contentTokens === undefined) return undefined\n\n let params = ''\n try {\n params = JSON.stringify(exec.arguments) ?? ''\n } catch {\n params = ''\n }\n const callTokens = safeEstimate(estimate, `${exec.name ?? 'tool'} ${params}`)\n if (callTokens === undefined) return undefined\n\n const totalTokens = callTokens + contentTokens\n return Number.isFinite(totalTokens) ? { callTokens, contentTokens, totalTokens } : undefined\n}\n\n/**\n * Count a `read`/`grep` that names one of this session's spill locators.\n *\n * `appendReceipt` is the store's only write path, and `kind:'projection'` with\n * `retrieved:true` is exactly what `boost status` aggregates as\n * `projection_retrievals` and `projection_retrieval_tokens`. No\n * `saved_projection_tokens` is written: this line documents a cost, not\n * another gross saving.\n *\n * `visibleText` is the content that enters history after projection, which is\n * what the model must pay to replay.\n */\nasync function recordProjectionRetrieval(\n deps: HookDeps,\n exec: PostExecuteExec,\n sessionId: string,\n pending: PendingRetrieval,\n visibleText: string,\n): Promise<void> {\n try {\n const name = exec?.name\n if (typeof name !== 'string') return\n const cost = retrievalCostOf(deps, exec, visibleText)\n const entry: ReceiptInput = {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: clockTurnOf(deps, sessionId) ?? 0,\n kind: 'projection',\n code: 'projection-retrieval',\n tool: name,\n retrieved: true,\n locator: pending.locator,\n // The visible content replays over this horizon in `status`'s net, so it\n // must be the horizon in effect when the retrieval happened, not one read\n // from the whole ledger later.\n horizon_steps: projectionHorizonOf(deps, sessionId),\n preview: previewOf(visibleText),\n ...(exec.arguments !== undefined ? { args: exec.arguments } : {}),\n }\n if (cost === undefined) {\n entry.estimate = 'unknown'\n } else {\n entry.retrieval_call_tokens = cost.callTokens\n entry.retrieval_content_tokens = cost.contentTokens\n entry.retrieval_tokens = cost.totalTokens\n entry.estimate = deps.estimateKind ?? 'unknown'\n }\n await appendReceipt(deps, entry)\n } catch {\n // A retrieval is evidence, never a precondition of the tool result.\n }\n}\n\n// ---------------------------------------------------------------------------\n// Admission and the decision branch\n// ---------------------------------------------------------------------------\n\n/**\n * The conservative saving of skipping one model step: the last real request's\n * replayed context (`input + cacheRead`).\n *\n * The step that is skipped would have replayed at least this much: the context\n * only grows as receipts enter it. A missing ledger or sample is 0, never an\n * interpolation, so admission falls back to the model when it cannot measure\n * (design §5.3: measured, not estimated).\n */\nfunction savedTokensOf(deps: HookDeps, sessionId: string): number {\n try {\n const last = sessionUsage(deps, sessionId)?.last()\n if (last === undefined) return 0\n const { input, cacheRead } = last\n if (!Number.isFinite(input) || !Number.isFinite(cacheRead) || input < 0 || cacheRead < 0) return 0\n const total = input + cacheRead\n return Number.isFinite(total) ? total : 0\n } catch {\n return 0\n }\n}\n\n/**\n * Whether this commit clears the admission threshold.\n *\n * A plan with exactly one candidate is the design's deterministic-single\n * exemption: there is no selector call to pay for, so the threshold does not\n * apply. Any other plan pays no selector either once only one candidate\n * survives, but it still has to show a net win over the threshold; the\n * conservative direction here is to keep the gate on.\n */\nfunction admittedFor(\n deps: HookDeps,\n sessionId: string,\n plan: Plan,\n overheadTokens: number,\n): boolean {\n try {\n const threshold = deps.config?.admission?.thresholdTokens\n const thresholdTokens =\n typeof threshold === 'number' && Number.isFinite(threshold)\n ? threshold\n : DEFAULT_CONFIG.admission.thresholdTokens\n return worthSubstituting({\n savedTokens: savedTokensOf(deps, sessionId),\n overheadTokens,\n thresholdTokens,\n deterministicSingle: plan.steps.length === 1,\n })\n } catch {\n return false\n }\n}\n\n/**\n * Whether the session's turn budget is already empty, without consuming it.\n *\n * A selector call is real spend, so this check runs before the selector is\n * priced or called; the consuming `takeBudget` stays at the commit point.\n * A missing or foreign budget means \"not exhausted\", matching `takeBudget`'s\n * no-cap contract. Shadow mode never calls this: it spends no step.\n */\nfunction budgetExhausted(deps: HookDeps, sessionId: string): boolean {\n try {\n const budget = sessionBudget(deps, sessionId)\n if (budget == null || typeof budget.exhausted !== 'function') return false\n return budget.exhausted() === true\n } catch {\n return false\n }\n}\n\n/** Claim one budget step; no budget wired means no cap is applied. */\nfunction takeBudget(deps: HookDeps, sessionId: string): boolean {\n try {\n const budget = sessionBudget(deps, sessionId)\n if (budget == null || typeof budget.take !== 'function') return true\n return budget.take()\n } catch {\n return false\n }\n}\n\n/** Record the substitution for the usage pairing; the stream hook settles it. */\nfunction markSubstituted(deps: HookDeps, sessionId: string, candidateId: string): void {\n try {\n sessionUsage(deps, sessionId)?.markSubstituted(candidateId)\n } catch {\n // A ledger miss costs a measurement, never this call.\n }\n}\n\n/** The session's pending usage-mark candidate, or `undefined` for a foreign ledger. */\nfunction pendingCandidateOf(deps: HookDeps, sessionId: string): string | undefined {\n try {\n return sessionUsage(deps, sessionId)?.pendingCandidateId()\n } catch {\n return undefined\n }\n}\n\n/**\n * The last substitution dispatch `tools/execute` accepted for a session.\n *\n * `ReceiptSessionState` records the same callId -> candidate mapping, but the\n * candidate's own `tools/post-execute` consumes it when it files the receipt.\n * A turn rollover needs the fact *after* that consumption: a late parallel\n * tool result can roll the turn before the next real request, and the usage\n * mark must then be reported instead of discarded as if nothing ran. The\n * accepted dispatch is mirrored here together with the evidence that would\n * otherwise be parked for the next settlement.\n *\n * One record per session: a later accepted dispatch replaces it, a session\n * whose usage mark is already gone drops it, and a rollover consumes it. The\n * `HookDeps` key keeps two assemblies in one process from reading each other's\n * sessions. The record is small and per-session; it is never persisted.\n */\nconst ACCEPTED_DISPATCH = new WeakMap<\n HookDeps,\n Map<string, { turn: number; candidateId: string; evidence?: SubstitutionEvidence }>\n>()\n\n/** Mirror an accepted dispatch for a possible rollover settlement. */\nfunction noteAcceptedDispatch(\n deps: HookDeps,\n sessionId: string,\n turn: number,\n candidateId: string,\n evidence: SubstitutionEvidence | undefined,\n): void {\n let bySession = ACCEPTED_DISPATCH.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n ACCEPTED_DISPATCH.set(deps, bySession)\n }\n bySession.set(sessionId, {\n turn,\n candidateId,\n ...(evidence === undefined ? {} : { evidence }),\n })\n}\n\n/**\n * Consume the accepted dispatch that matches `candidateId`, if any.\n *\n * The turn check is a staleness guard: the record that a pending mark belongs\n * to was written in the turn now rolling over. A record written in the new\n * turn cannot belong to it.\n */\nfunction takeAcceptedDispatch(\n deps: HookDeps,\n sessionId: string,\n candidateId: string,\n turn: number,\n): { evidence?: SubstitutionEvidence } | undefined {\n const bySession = ACCEPTED_DISPATCH.get(deps)\n const record = bySession?.get(sessionId)\n bySession?.delete(sessionId)\n if (record === undefined || record.candidateId !== candidateId || record.turn === turn) {\n return undefined\n }\n return record.evidence === undefined ? {} : { evidence: record.evidence }\n}\n\n/** Drop the mirrored dispatch; no pending mark is waiting to settle it. */\nexport function clearAcceptedDispatch(deps: HookDeps, sessionId: string): void {\n ACCEPTED_DISPATCH.get(deps)?.delete(sessionId)\n}\n\n/**\n * Settle the usage mark at a turn rollover, reporting a substitution that ran.\n *\n * The ordinary path settles at the first real request after synthesis. A late\n * parallel tool result can roll the turn before that request; the mark must not\n * survive into the new turn, where it would pair with a request that is not the\n * substitution's next one. If `tools/execute` never accepted the synthesized\n * dispatch, the substitution did not run and the mark is a discard. If it did,\n * the model round really was skipped: the settlement line is written with\n * whatever sample the ledger holds (`'unknown'` when no after-mark request has\n * run yet) and with the evidence captured at dispatch, so the substitution is\n * reported instead of disappearing.\n */\nasync function settleRollover(deps: HookDeps, sessionId: string, turn: number): Promise<void> {\n const candidateId = pendingCandidateOf(deps, sessionId)\n if (candidateId === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n\n const dispatched = takeAcceptedDispatch(deps, sessionId, candidateId, turn)\n if (dispatched === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n\n let settled: ReturnType<UsageLedger['settle']>\n try {\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n settled = ledger.settle()\n } catch {\n settleDiscarded(deps, sessionId)\n return\n }\n\n // The parked evidence lives in `llm-stream`'s private map and would outlive\n // the mark. `settleDiscarded` is the module's idempotent cleanup: the ledger\n // was settled above, so this call only forgets that evidence. It runs before\n // the receipt write so the `await` cannot let a new mark be created and then\n // be consumed by this cleanup.\n settleDiscarded(deps, sessionId)\n\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn,\n stepId: 'root',\n kind: 'substitute-settled',\n code: 'substitute-settled',\n candidateId,\n ...(dispatched.evidence ?? {}),\n saved_input_tokens: settled.saved_input_tokens,\n cache_hit_delta: settled.cache_hit_delta,\n output_tokens: settled.output_tokens,\n })\n}\n\n/**\n * The receipt ids a candidate's `$public` templates refer to, plus `'root'`.\n *\n * These are the anchors the invalidation check compares against: the chosen\n * candidate's arguments were computed from those receipts, so if any of them\n * is rewritten externally the decision is stale. The walk is iterative and\n * depth-capped because it runs over model-written args; `parsePlan` already\n * caps them at 64 levels, but the hook must not depend on that.\n */\nfunction referencedReceiptIds(args: unknown): Set<string> {\n const ids = new Set<string>(['root'])\n const stack: Array<{ value: unknown; depth: number }> = [{ value: args, depth: 1 }]\n while (stack.length > 0) {\n const frame = stack.pop()\n if (frame === undefined) break\n if (frame.depth > 64) continue\n if (Array.isArray(frame.value)) {\n for (const child of frame.value) {\n if (typeof child === 'object' && child !== null) {\n stack.push({ value: child, depth: frame.depth + 1 })\n }\n }\n continue\n }\n if (typeof frame.value !== 'object' || frame.value === null) continue\n const { $public: template, ...rest } = frame.value as Record<string, unknown>\n if (\n typeof template === 'object' &&\n template !== null &&\n typeof (template as { after?: unknown }).after === 'string'\n ) {\n ids.add((template as { after: string }).after)\n }\n for (const child of Object.values(rest)) {\n if (typeof child === 'object' && child !== null) {\n stack.push({ value: child, depth: frame.depth + 1 })\n }\n }\n }\n return ids\n}\n\n/**\n * Store the session's anchors for the committed candidate.\n *\n * `stepId` is `'root'` because the guards and templates were evaluated against\n * the receipt that just arrived; the map carries that receipt's canonical text\n * plus the text of every receipt the candidate's `$public` templates reference\n * (design §5.2-7). Missing references are omitted rather than invented.\n */\nfunction setAnchors(deps: HookDeps, ctx: DecisionContext, candidateArgs: unknown): void {\n try {\n const anchorsStore = deps.anchors\n if (anchorsStore == null || typeof anchorsStore.set !== 'function') return\n const receipts = ctx.state.receiptsFor(ctx.sessionId, ctx.turn)\n const anchors: Record<string, string> = {}\n for (const id of referencedReceiptIds(candidateArgs)) {\n const receipt = receipts.get(id)\n if (receipt !== undefined) anchors[id] = receipt.text\n }\n anchorsStore.set(ctx.sessionId, { stepId: 'root', anchors })\n } catch {\n // Anchors are a guard input, not the guard: losing them costs a reset.\n }\n}\n\n/**\n * Whether the session may be substituted for right now.\n *\n * Both gates must agree: the cached judgement said yes (the listener would\n * have returned otherwise), and the live document still lists the session's\n * workspace. The second check cannot be skipped: the cache is refreshed by a\n * different task, and a stale \"visible\" must never authorize a replacement.\n */\nfunction substitutableSession(deps: HookDeps, sessionId: string, doc: ScopeDoc): boolean {\n try {\n const workspaceId = deps.resolveSession?.(sessionId)\n if (typeof workspaceId !== 'string') return false\n return isVisible(doc, workspaceId)\n } catch {\n return false\n }\n}\n\n/**\n * A selector-facing summary of one already-bound candidate.\n *\n * The selector only needs to tell candidates apart; the args are included so\n * two calls to the same tool with different paths are distinguishable. The\n * bound tree is safe to show (it is what will run) and bounded so one huge\n * argument cannot dominate the selector prompt.\n */\nfunction selectorSummary(candidate: Candidate): string {\n let args = ''\n try {\n args = JSON.stringify(candidate.args) ?? ''\n } catch {\n // A model-written plan is already JSON, but the summary is evidence-shaped\n // and must not make the selector call throw.\n }\n const text = `${candidate.tool} ${args}`.trim()\n const points = Array.from(text)\n return points.length > 200 ? `${points.slice(0, 200).join('')}…` : text\n}\n\n/** Bound the receipt the selector pays for, using the projection's head/tail shape. */\nfunction selectorReceiptOf(deps: HookDeps, ctx: DecisionContext): string {\n const text = ctx.receipt.text\n const points = Array.from(text)\n if (points.length <= SELECTOR_RECEIPT_MAX_CHARS) return text\n\n const toolName = ctx.exec.name\n const family = toolName === undefined ? undefined : familyOf(toolName)\n const params = family !== undefined ? deps.config.projection[family] : undefined\n const configured = params !== undefined ? params.headChars + params.tailChars : 0\n const total = Math.min(\n SELECTOR_RECEIPT_MAX_CHARS,\n configured > 0 ? configured : SELECTOR_RECEIPT_MAX_CHARS,\n )\n const ratio = configured > 0 && params !== undefined ? params.headChars / configured : 0.8\n const headChars = Math.min(total, Math.max(0, Math.round(total * ratio)))\n const tailChars = total - headChars\n const head = points.slice(0, headChars).join('')\n const tail = tailChars > 0 ? points.slice(-tailChars).join('') : ''\n const omitted = points.length - headChars - tailChars\n return `${head}\\n…[selector window: omitted ${omitted} chars]…\\n${tail}`\n}\n\n/** The configured selector output budget, with the design default as a fallback. */\nfunction selectorMaxTokens(deps: HookDeps): number {\n const raw = deps.config?.selector?.maxTokens\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {\n return DEFAULT_CONFIG.selector.maxTokens\n }\n return Math.floor(raw)\n}\n\n/** The route the selector call would inherit, or `undefined` when it cannot run. */\nfunction selectorRouteOf(deps: HookDeps, sessionId: string): SelectorRoute | undefined {\n try {\n const route = deps.selectorRoute?.(sessionId)\n if (\n route === undefined ||\n typeof route.provider !== 'string' ||\n typeof route.model !== 'string'\n ) {\n return undefined\n }\n return route\n } catch {\n return undefined\n }\n}\n\n/** Whether the selector is missing its LLM or its effective route. */\nfunction selectorSeamUnavailable(deps: HookDeps, ctx: DecisionContext): boolean {\n const llm = deps.llm\n return llm == null || typeof llm.stream !== 'function' || selectorRouteOf(deps, ctx.sessionId) === undefined\n}\n\n/**\n * The selector's fast upper bound: its output cap plus the estimated input.\n *\n * `maxTokens` bounds only the output; everything the request sends is input:\n * the system prompt, the user template, the candidate list and the receipt.\n * Charging only the receipt and the candidates under-counts the call by the\n * prompt (about 60–70 tokens) and makes admission optimistic exactly where it\n * decides whether to call. The priced string is built with the selector's own\n * exported template, so the estimate cannot drift from the request (row 36).\n * `undefined` means the caller cannot price the call; it must not guess.\n */\nfunction selectorChargeOf(\n deps: HookDeps,\n candidates: readonly Candidate[],\n receiptText: string,\n): number | undefined {\n const estimate = deps.estimateText\n if (typeof estimate !== 'function') return undefined\n const prompt = selectorPromptText({\n candidates: candidates.map((candidate) => ({\n id: candidate.id,\n summary: selectorSummary(candidate),\n })),\n receiptText,\n })\n const input = safeEstimate(estimate, `${SELECTOR_SYSTEM_PROMPT}\\n${prompt}`)\n if (input === undefined || input < 0) return undefined\n return selectorMaxTokens(deps) + input\n}\n\n/**\n * Ask the selector to pick one of `decision.candidates` and return that same\n * decision candidate, whose `args` are already bound.\n *\n * Never throws and never guesses. A missing LLM seam, a missing route, an\n * abstention or a thrown call all leave the plan untouched and write one\n * `skip` receipt explaining why; the next post-execute may try again. The\n * `SELECTOR_PURPOSE` marker is set by `choose` itself, so the frozen stream\n * hook can recognize and pass the aux request through.\n */\nasync function chooseCandidate(\n deps: HookDeps,\n ctx: DecisionContext,\n candidates: readonly Candidate[],\n receiptText: string,\n): Promise<Candidate | undefined> {\n const llm = deps.llm\n if (llm == null || typeof llm.stream !== 'function') {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return undefined\n }\n\n let route: SelectorRoute | undefined\n try {\n route = deps.selectorRoute?.(ctx.sessionId)\n } catch {\n route = undefined\n }\n if (\n route === undefined ||\n typeof route.provider !== 'string' ||\n typeof route.model !== 'string'\n ) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return undefined\n }\n\n try {\n const result = await choose({\n llm,\n provider: route.provider,\n model: route.model,\n ...(typeof route.reasoningEffort === 'string'\n ? { reasoningEffort: route.reasoningEffort }\n : {}),\n candidates: candidates.map((candidate) => ({\n id: candidate.id,\n summary: selectorSummary(candidate),\n })),\n receiptText,\n maxTokens: deps.config.selector.maxTokens,\n })\n if ('choice' in result) {\n // `candidates` are the decision's copies: their args are the bound tree.\n return candidates.find((candidate) => candidate.id === result.choice)\n }\n // §5.2-3 distinguishes a timeout/no-label abstention from a failed call:\n // `choose` maps its own dispatch failure to `abstain: 'error'`, and that is\n // the `selector-error` branch, not a second abstention reason.\n const code = result.abstain === 'error' ? 'selector-error' : 'selector-abstain'\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', code, { stepId: 'root', reason: result.abstain }),\n )\n return undefined\n } catch {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'selector-error', { stepId: 'root', reason: 'error' }),\n )\n return undefined\n }\n}\n\n/**\n * The substitution decision and its side effects.\n *\n * The fixed order is the plan's: existence of a plan and a receipt first, then\n * `worthSubstituting`, then `budget.take()`. Nothing below spends budget on a\n * decision that will not be dispatched.\n *\n * `ask-selector` is fulfilled here since Task 23c-2: the decision carries only\n * already-bound candidates, so the selector's choice is committed from\n * `decision.candidates[].args` — never from `plan.steps[i].args`, which still\n * holds `$public` templates. The selector call is the plugin's own aux request\n * (`purpose: 'boost-selector'`), so the frozen stream hook passes it through.\n * A missing route or a missing LLM is a record-only abstention, never a guess.\n * `fallback` records the decision code and leaves the pending entry alone: this\n * invocation has enqueued nothing, so any entry it finds belongs to another\n * call, and clearing it would cancel a live substitution in a multi-call step.\n * A plan is **one-shot per receipt**: the first post-execute that reads it\n * removes it from the session map, whatever the outcome (commit, guard\n * failure, selector abstention, no candidate). The protocol says a block\n * describes the next call and may be omitted when unsure; retaining it would\n * let a plan the model has withdrawn fire against a much later receipt. The\n * remaining candidates are not reused either; the model writes a fresh block\n * for the next call (and may still reference an earlier receipt by id).\n *\n * A shadow commit parks nothing, but projection is independent of the shadow\n * flag (design §5.2-5) and still runs in `applyDecision`.\n */\nasync function decideSubstitution(\n deps: HookDeps,\n ctx: DecisionContext,\n): Promise<void> {\n // Fail-closed gate (design §5.2-3): a store that cannot record evidence\n // cannot justify spending a selector call or a budget step. No receipt is\n // attempted here either; the store is already failing, and status exposes\n // `receipts.stopped()` to the operator.\n //\n // The plan is still consumed here. This receipt cannot use it, and a plan is\n // one-shot per receipt: keeping it for a later receipt is exactly the stale\n // plan the one-shot rule exists to prevent. A store that recovers mid-turn\n // would otherwise let the next receipt fire a decision the model wrote for\n // this one.\n if (receiptsStopped(deps)) {\n clearPlan(deps, ctx.sessionId)\n return\n }\n\n const plan = safePlan(deps, ctx.sessionId)\n if (plan === undefined) return\n // One-shot: capture the plan for this pass, then drop it before any branch can\n // return, so no later receipt can reuse it.\n clearPlan(deps, ctx.sessionId)\n\n // Design §9: no token meter means no substitution. The meter is what prices\n // `worthSubstituting` and the selector's input, so running without it would\n // spend real money on a fabricated estimate. Refuse before `decide`, before\n // the selector and before admission; shadow mode is record-only and may\n // still run. Projection is not gated (it needs no token numbers to clip).\n const estimator = estimatorOf(deps)\n if (\n !ctx.doc.shadow &&\n (estimator === undefined || safeEstimate(estimator, 'dsh-boost meter probe') === undefined)\n ) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'ERR_HOST_NO_TOKENMETER', {\n stepId: 'root',\n reason: 'no-token-meter',\n }),\n )\n return\n }\n\n let decision: ReturnType<typeof decide>\n try {\n decision = decide({\n plan,\n stepId: 'root',\n receipts: ctx.state.receiptsFor(ctx.sessionId, ctx.turn),\n whitelist: SUBSTITUTION_WHITELIST,\n shadow: ctx.doc.shadow,\n })\n } catch {\n return\n }\n\n // Substitution synthesises a dispatch and expects POSIX process semantics;\n // on Windows it is refused **before** the selector, admission and budget, so\n // the path cannot spend anything to decline. Shadow mode is record-only and\n // stays available: it changes nothing the model sees. The stable operator\n // signal is `boost status`'s `ERR_HOST_PLATFORM_UNSUPPORTED`; this receipt\n // keeps the refusal auditable per call rather than silently doing less.\n if (!isPosixOnly() && !ctx.doc.shadow) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', {\n stepId: 'root',\n reason: 'platform-unsupported',\n }),\n )\n return\n }\n\n let candidate: Candidate | undefined\n let boundArgs: Record<string, unknown> | undefined\n let candidateId: string | undefined\n\n // A selector call pays its output cap plus the input actually sent. A single\n // surviving candidate pays no selector at all. This must run before `choose`:\n // a selector call that cannot be paid for is never sent.\n let selectorOverhead = 0\n let selectorReceiptText = ''\n if (decision.kind === 'ask-selector') {\n // Row 2: the budget is checked before the selector is paid for. Without\n // this, an exhausted step would still send a real model request and then\n // record `steps-exhausted` after the money was spent. Shadow mode is\n // record-only and takes no step, so it keeps measuring.\n if (!ctx.doc.shadow && budgetExhausted(deps, ctx.sessionId)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }))\n return\n }\n // Availability is checked before pricing: a missing LLM/route is the\n // `selector-unavailable` degradation, not an admission decision.\n if (selectorSeamUnavailable(deps, ctx)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return\n }\n selectorReceiptText = selectorReceiptOf(deps, ctx)\n const charge = selectorChargeOf(deps, decision.candidates, selectorReceiptText)\n if (charge === undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root', reason: 'no-estimator' }),\n )\n return\n }\n selectorOverhead = charge\n if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }))\n return\n }\n // The decision's candidates already carry the bound trees; committing from\n // the plan here would dispatch a `$public` template.\n const chosen = await chooseCandidate(deps, ctx, decision.candidates, selectorReceiptText)\n if (chosen === undefined) return\n candidate = chosen\n boundArgs = chosen.args\n candidateId = chosen.id\n } else if (decision.kind === 'fallback') {\n // This invocation enqueued nothing, so any pending entry belongs to another\n // call in the step; cancelling it would leave the budget spent and usage\n // marked for a substitution that never runs (review F2).\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', decision.code, { stepId: 'root' }))\n return\n } else {\n candidate = plan.steps.find((step) => step.id === decision.candidateId)\n boundArgs = decision.args\n candidateId = decision.candidateId\n }\n\n if (candidate === undefined || boundArgs === undefined || candidateId === undefined) {\n // decide only commits its own plan's ids; this is containment, not a path.\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'no-candidate', { stepId: 'root' }))\n return\n }\n\n // The live visibility check runs for the shadow path too: the record-only\n // measurement must describe the same population the real admission would\n // consider, not a broader one (review F2). The cached judgement passed above,\n // but the document may have changed while the session ran.\n if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'skip:no-scope', { stepId: 'root' }))\n return\n }\n\n if (ctx.doc.shadow) {\n // Record-only: the same `shadow` flag was passed to `decide` above, so the\n // recorded potential matches the policy that produced it. No queue entry\n // and no budget. Projection is a separate switch and still runs afterwards\n // (design §5.2-5); this branch only stops the substitution side.\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'shadow', 'ok', {\n decision: 'commit',\n candidateId,\n // The executed tool is the model's call; the candidate's tool is what\n // the gate decided. The shadow report's per-family hit rate must use\n // the latter (the shadow receipt's `tool` is the former).\n candidateTool: candidate.tool,\n admitted: admittedFor(deps, ctx.sessionId, plan, selectorOverhead),\n whitelisted: SUBSTITUTION_WHITELIST.has(candidate.tool),\n stepId: 'root',\n args: boundArgs,\n // G2: the plan and the guards are why this candidate was legitimate.\n ...substitutionEvidence(plan.goal, candidate.guards),\n }),\n )\n return\n }\n\n const step = clockStepOf(deps, ctx.sessionId)\n if (step === undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-step' }),\n )\n return\n }\n if (deps.queue == null || typeof deps.queue.set !== 'function') {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-queue' }),\n )\n return\n }\n\n if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }))\n return\n }\n\n if (!takeBudget(deps, ctx.sessionId)) {\n // No entry is ours to clear here: this invocation enqueued nothing, so a\n // live entry belongs to another call in the step (review F2).\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }))\n return\n }\n\n const callId = callIdFor(ctx.sessionId, ctx.turn, step, candidateId)\n const entry: AuditedPendingEntry = {\n callId,\n candidateId,\n // The candidate's tool name identifies the call; the executable args are\n // the *decision's* bound tree, never the plan's `$public` template.\n name: candidate.tool,\n args: boundArgs,\n turn: ctx.turn,\n step,\n // The plan is one-shot (cleared above), so the evidence must travel with\n // the entry: the synth-time receipt is written after this turn's plan is\n // gone, and the settled receipt only knows the candidate id.\n evidence: substitutionEvidence(plan.goal, candidate.guards),\n }\n try {\n deps.queue.set(ctx.sessionId, entry)\n } catch {\n await appendReceipt(\n deps,\n // The step was already taken and this receipt is the only evidence that\n // it bought no substitution; a throwing queue must not also hide the cost.\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', {\n stepId: 'root',\n reason: 'queue-failed',\n budget: 'spent',\n }),\n )\n return\n }\n\n markSubstituted(deps, ctx.sessionId, candidateId)\n // Anchors name the templates the executed call was bound from: the decision's\n // args are already expanded, so only the plan copy still carries the\n // `$public` references. That tree is inspected here, never dispatched.\n setAnchors(deps, ctx, plan.steps.find((step) => step.id === candidateId)?.args ?? boundArgs)\n return\n}\n\n/** The session's plan, or `undefined` when none is known (or the map is foreign). */\nfunction safePlan(deps: HookDeps, sessionId: string): Plan | undefined {\n try {\n const plans = deps.plans\n if (plans == null || typeof plans.get !== 'function') return undefined\n const plan = plans.get(sessionId)\n if (plan === undefined || plan === null) return undefined\n // A spent plan has nothing left to decide; skipping the call also avoids a\n // `guard-trivial` receipt on every later tool call of the turn.\n if (!Array.isArray(plan.steps) || plan.steps.length === 0) return undefined\n return plan\n } catch {\n return undefined\n }\n}\n\n// ---------------------------------------------------------------------------\n// Projection\n// ---------------------------------------------------------------------------\n\n/** The text projection may replace, or `undefined` when it must stay intact. */\nfunction projectionTargetOf(\n decision: PostExecuteDecision,\n receipt: CanonicalReceipt,\n result: PostExecuteResult | undefined,\n): string | undefined {\n // A `value` replacement cannot be combined with `content`: the host throws a\n // TypeError for both, which would replace the tool result with an error.\n if (Object.hasOwn(decision, 'value')) return undefined\n if (decision.kind !== 'accept') return undefined\n\n if (Object.hasOwn(decision, 'content')) {\n const content = decision.content\n if (!Array.isArray(content)) return undefined\n // Replacing a multi-block result with one text block is only lossless when\n // every block is text; an image or file block must stay where it is.\n if (!content.every((block) => textBlock(block))) return undefined\n return canonicalise(content as ReadonlyArray<{ type: string; text?: string }>, false).text\n }\n\n const content = result?.content\n if (content !== undefined && !(Array.isArray(content) && content.every((block) => textBlock(block)))) {\n return undefined\n }\n return receipt.text\n}\n\n/** Whether a block is a text block this hook can fold into one string. */\nfunction textBlock(block: unknown): boolean {\n return typeof block === 'object' && block !== null && (block as { type?: unknown }).type === 'text'\n}\n\n/** The estimator, or `undefined` when none is wired (projection then stays off). */\nfunction estimatorOf(deps: HookDeps): ((t: string) => number) | undefined {\n const estimate = deps.estimateText\n return typeof estimate === 'function' ? estimate : undefined\n}\n\n/** One estimate, sanitised: a non-finite or throwing result means \"cannot price\". */\nfunction safeEstimate(estimate: (t: string) => number, text: string): number | undefined {\n try {\n const value = estimate(text)\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The replay horizon in effect for one projection decision, pinned on its receipt.\n *\n * `status` applies `(1 + horizon)` to every projection's saving. Reading one\n * current horizon at status time re-valued receipts from other sessions and\n * other moments whenever the cross-session minimum moved, so a historical net\n * saving jumped when an unrelated session started or ended. The receipt now\n * carries the horizon its decision was made under; `status` only falls back to\n * the current horizon for receipts that predate the field, and says how many\n * those were.\n *\n * The runtime horizon is design §5.3's `min(config, mean of the session's last\n * historyTurns turns)`. Its instance lives in `src/index.ts` (`apply` builds\n * one `RuntimeStepHorizon`), so the decision path can only read it through\n * {@link HookDeps.horizonFor}; until that one line is wired, the resolved\n * config's `horizonSteps` is the value in effect. A throwing or malformed\n * answer falls back the same way, never to a fabricated number.\n */\nfunction projectionHorizonOf(deps: HookDeps, sessionId: string): number {\n try {\n const live = deps.horizonFor?.(sessionId)\n if (typeof live === 'number' && Number.isFinite(live) && live >= 0) return Math.floor(live)\n } catch {\n // A foreign horizon is evidence, never a reason to lose the receipt.\n }\n const raw = deps.config?.horizonSteps\n return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0\n ? Math.floor(raw)\n : DEFAULT_CONFIG.horizonSteps\n}\n\n/** `projection-skipped:<reason>`; `projectApply` already prefixes one reason. */\nfunction projectionSkipCode(reason: string): string {\n return reason.startsWith('projection-skipped:') ? reason : `projection-skipped:${reason}`\n}\n\n/**\n * Project the receipt that will enter history.\n *\n * Shadow mode only prices the receipt: it writes a `{kind:'shadow'}` record and\n * returns the decision untouched, so nothing the model sees changes. Apply mode\n * persists the canonical original through the host spill backend and replaces\n * the content only after `projectApply`'s own guards pass; a skip leaves the\n * decision intact. The regression guard (`assembled.length < original.length`)\n * lives inside `projectApply`; here only pricing and evidence are added.\n *\n * The live visibility recheck runs before either mode. The listener gate reads\n * the cached judgement from prompt assembly time; a workspace disabled since\n * then must not have its receipt clipped or accounted, in shadow or apply mode.\n */\nasync function projectDecision(\n deps: HookDeps,\n receipt: CanonicalReceipt,\n decision: PostExecuteDecision,\n ctx: DecisionContext,\n): Promise<PostExecuteDecision> {\n const mode: ProjectionMode = ctx.doc.projection\n if (mode === 'off') return decision\n\n // Projection gets the same live recheck substitution performs. The cached\n // judgement passed the listener gate, but the prompt was assembled before\n // the tool ran: `boost` may have disabled the workspace in between, and a\n // projection changes what the model sees. The cache alone must not authorize\n // that (design §5.5).\n if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) return decision\n\n const toolName = ctx.exec.name\n const family = toolName === undefined ? undefined : familyOf(toolName)\n if (family === undefined) {\n // `edit`, `web_fetch`, `todo_write`, `boost` and friends are by-design\n // passes, not mapper gaps. Only a decorated (`mcp__*`) name means the\n // mapper may have missed a real family, so only that is counted.\n if (typeof toolName === 'string' && toolName.startsWith('mcp__')) {\n try {\n deps.projectionCounters?.unknownFamily(toolName)\n } catch {\n // A counter is evidence, never a precondition.\n }\n }\n return decision\n }\n const target = projectionTargetOf(decision, receipt, ctx.result)\n if (target === undefined) return decision\n\n // Clipping does not need a token meter; only its accounting does (design\n // §9). With no estimator the replacement still happens, but the receipts\n // carry `estimate:'unknown'` and no fabricated numbers.\n const estimate = estimatorOf(deps)\n\n try {\n if (mode === 'shadow') {\n const outcome = await projectShadow({\n text: target,\n isError: receipt.isError,\n family,\n cfg: deps.config,\n // Same sanitiser as the apply path: a throwing or non-finite host\n // estimate must never become `null` in the shadow account. Without a\n // meter the NaN makes `projectShadow` record an unpriced event.\n estimate: (text) =>\n estimate === undefined ? Number.NaN : (safeEstimate(estimate, text) ?? Number.NaN),\n })\n if (outcome.kind === 'shadow') {\n const priced =\n outcome.before !== undefined &&\n outcome.after !== undefined &&\n outcome.saved !== undefined\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'shadow', 'projection-shadow', {\n decision: 'projection',\n unit: 'raw',\n // The shadow ledger's one-time figure is replayable with the same\n // horizon as the applied one; pinning it keeps the two comparable.\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n ...(priced\n ? {\n before: outcome.before,\n after: outcome.after,\n saved_projection_tokens: outcome.saved,\n }\n : {}),\n estimate: priced ? (deps.estimateKind ?? 'unknown') : 'unknown',\n }),\n )\n }\n return decision\n }\n\n const { content, outcome } = await projectApply({\n text: target,\n isError: receipt.isError,\n family,\n cfg: deps.config,\n sessionId: ctx.sessionId,\n toolName: ctx.exec.name ?? 'tool',\n callId: typeof ctx.exec.callId === 'string' ? ctx.exec.callId : undefined,\n label: family,\n spill: deps.spill,\n formatFooter: await resolveFooterFormatter(deps),\n })\n\n if (outcome.kind === 'applied') {\n // Remember the artifact's only address: this is what makes a later read\n // of it a counted retrieval instead of a free one (design §5.3).\n if (outcome.locator !== undefined) deps.retrievals?.record(ctx.sessionId, outcome.locator)\n\n // The applied event is always recorded; only the token figures depend on\n // the meter. `estimate` is always present and names the producer\n // (`deps.estimateKind`, defaulting to `'unknown'`), never a guess.\n // One-time `before`/`after`/`saved_projection_tokens` are the\n // authoritative names (§5.3); `status` applies the replay factor once to\n // the aggregate, never per receipt. `horizon_steps` is the horizon this\n // decision was made under, so a later status cannot re-value it.\n const before = estimate === undefined ? undefined : safeEstimate(estimate, target)\n const after = estimate === undefined ? undefined : safeEstimate(estimate, content)\n if (before !== undefined && after !== undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'projection', 'projected', {\n unit: 'raw',\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n before,\n after,\n saved_projection_tokens: before - after,\n estimate: deps.estimateKind ?? 'unknown',\n }),\n )\n } else {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'projection', 'projected', {\n unit: 'raw',\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n estimate: 'unknown',\n }),\n )\n }\n return { ...decision, content: [{ type: 'text', text: content }] }\n }\n\n if (\n outcome.kind === 'skipped' &&\n outcome.reason !== undefined &&\n PROJECTION_DEGRADATIONS.has(outcome.reason)\n ) {\n // `projection-skipped:no-spill` is the receipt behind\n // `boost status`'s `ERR_HOST_NO_SPILL`; the other degradation codes\n // exist for the same audit trail. Ordinary \"not worth it\" skips are\n // deterministic policy, not a per-call decision (design §5.3), so they\n // write nothing.\n // A skip projected nothing, so it is a `skip` receipt, not a\n // `projection` one. `kind:'projection'` is not a promise of numeric\n // fields: the meterless apply branch above always writes\n // `estimate:'unknown'` but omits `before`/`after`/\n // `saved_projection_tokens` entirely (design §9), and consumers must\n // treat those as unpriced rather than assume the numbers exist.\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', projectionSkipCode(outcome.reason)),\n )\n }\n return decision\n } catch {\n // `projectApply`/`projectShadow` already contain their own host calls; this\n // is the last belt for a bug in either of them.\n return decision\n }\n}\n\n/**\n * The decision + projection stage.\n *\n * Both seams live in one place so the listener's order is visible in one\n * function: decide, then the double-projection guard, then project. A shadow\n * substitution does not stop the projection: the two switches are independent\n * (design §5.2-5), and in projection-shadow mode the projection writes only\n * its accounting line.\n */\nasync function applyDecision(\n deps: HookDeps,\n decision: PostExecuteDecision,\n ctx: DecisionContext,\n): Promise<PostExecuteDecision> {\n // Projection below runs for a shadow commit too: the decision side never\n // suppresses the projection ledger.\n await decideSubstitution(deps, ctx)\n\n // Second-projection guard. Two host shapers are outer to this listener:\n //\n // - The spill policy registers with `{ prepend: true }`: it calls `next()`\n // and adds its footer to *that* decision after this listener returns. So\n // this check sees only a footer an inner listener already wrote, never the\n // host's own; it must not be read as full double-spill detection.\n // - For `glob`/`grep`, `@deepseek-ai/dsh-tool-fs-search` is outer too\n // (`dsh-base` loads it first) and would replace an over-cap result with its\n // own spill-backed preview. The plugin pre-empts it **deliberately**:\n // `acceptedDirectCallValue` does nothing as soon as the decision carries\n // `content` (`dsh-tool-fs-search/lib/index.js:490-493`), so the projection\n // accept below wins and the host preview never runs. That is the intended\n // trade for these two families: the plugin's window triggers at 700\n // characters, far below the host's 100-path / 250-match caps, and its own\n // footer keeps the spill locator, so the host preview has nothing to add\n // to a receipt this listener already clipped. A family the plugin does not\n // project leaves the host shaper untouched.\n //\n // Both the receiver as it arrived and the decision that will enter history\n // are checked (design §5.4).\n if (await isAlreadySpilled(deps, ctx.receipt.text)) return decision\n const downstreamText = decisionTextOf(decision) ?? ctx.receipt.text\n if (downstreamText !== ctx.receipt.text && await isAlreadySpilled(deps, downstreamText)) {\n return decision\n }\n return projectDecision(deps, ctx.receipt, decision, ctx)\n}\n\n// ---------------------------------------------------------------------------\n// The two listeners\n// ---------------------------------------------------------------------------\n\n/**\n * The `tools/post-execute` body.\n *\n * `next()` runs first, exactly like the host's own spill policy: a listener\n * either returns a decision or calls `next()` and returns its result, and\n * bypassing it would silently drop the listeners mounted after this one. The\n * fixed order that follows is `scope gate → canonicalise → invalidate →\n * substitution decision → double-projection guard → projection → return the\n * decision` (design §5.2-7/§5.4-5).\n *\n * Everything after `next()` is contained: the host turns a throwing\n * `post-execute` listener into an error result and the real tool output is\n * lost. A failure in our own wiring must therefore return the decision as it\n * arrived, never a thrown error.\n */\nasync function postExecute(\n deps: HookDeps,\n state: ReceiptSessionState,\n exec: PostExecuteExec | undefined,\n result: PostExecuteResult | undefined,\n next: () => Promise<PostExecuteDecision>,\n): Promise<PostExecuteDecision> {\n const decision = await next()\n\n // The host cancels a call by aborting `exec.signal`; an async listener must\n // observe it before doing work whose result the model will never receive.\n // `next()` still runs — the waterfall must not drop the listeners mounted\n // after this one, and the host only replaces a successful accepted outcome\n // after they settle — but nothing after it does.\n if (cancelled(exec)) return decision\n\n // A PTC inner call traverses this waterfall with `parent` set. Its result\n // belongs to the enclosing `run_code` step, not to a step of its own: it must\n // not become `root`, drive a decision, consume the outer plan or overwrite the\n // outer anchors. Leaving it untouched is what keeps a plan from being decided\n // from an inner receipt.\n if (exec !== undefined && exec.parent !== undefined) return decision\n\n if (exec?.agent === undefined) {\n await appendSkipNoScope(deps.receipts, exec)\n return decision\n }\n\n // Exposure gate: an out-of-scope session pays nothing. This is the same\n // cached judgement the protocol section reads; a miss is false (fail-closed,\n // design §5.5).\n const sessionId = sessionIdOf(exec)\n if (sessionId === undefined) {\n // The agent exists but carries no usable session id, so neither the scope\n // gate nor the retrieval ledger can attribute this call. Fail closed and\n // keep the pass visible; the no-agent branch above does the same.\n await appendSkipNoScope(deps.receipts, exec)\n return decision\n }\n\n // The mirrored dispatch is only meaningful while its usage mark is pending.\n // Once the mark is gone (settled by the next real request, or discarded), the\n // record is stale and a later turn's mark could reuse the candidate id.\n if (pendingCandidateOf(deps, sessionId) === undefined) clearAcceptedDispatch(deps, sessionId)\n\n // A substituted call denied by `tools/pre-execute` (approval or sandbox)\n // returns a post-result without invoking `tools/execute`, while post-execute\n // still runs. Matching the call id here clears the pending entry even though\n // no dispatch mapping exists, so the substitution is not re-synthesized on\n // every later step of the turn.\n clearMatchingPending(deps, sessionId, exec)\n\n // Detect the retrieval before the visibility gate (a projected receipt\n // already consumed context regardless of today's scope), but write its cost\n // only after projection, when the final visible content is known (review I3).\n const retrieval = pendingRetrievalOf(deps, exec, sessionId)\n\n if (!isActiveSession(deps, sessionId)) {\n if (retrieval !== undefined) {\n const arrival = canonicalise(result?.content ?? [], result?.isError === true)\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, arrival.text)\n }\n await appendSkipNoScope(deps.receipts, exec, sessionId, clockTurnOf(deps, sessionId) ?? 0)\n return decision\n }\n\n try {\n // Canonicalise the original receiver, not a downstream replacement: guards\n // and the selector read the receipt as it arrived.\n const receipt = canonicalise(result?.content ?? [], result?.isError === true)\n const turn = clockTurnOf(deps, sessionId) ?? 0\n\n // The receipt map is the gate's memory for this turn. `begin` folds the\n // previous turn away (anchors live in the store, receipts and in-flight\n // dispatches here), then the arriving receipt becomes `root` and, if it is\n // the call we substituted, also becomes the candidate's receipt.\n const { rolledOver } = state.begin(sessionId, turn)\n if (rolledOver) {\n // A pending entry and its decision-time usage mark from the previous turn\n // can never match a call in this one, so both are dead weight; the reset\n // path does the same mid-turn (F2). The mark is settled **without** a\n // settlement receipt when no substitution ran, exactly like\n // `resetInvalidatedPending` and `applyAbandon`. This branch is reachable\n // with a live mark because a parallel tool result can land after the host\n // advanced the turn but before this turn's first `llm/stream`, so the old\n // \"the stream always runs first\" argument does not hold (D1). When the\n // synthesized dispatch *was* accepted, the skipped model round is real:\n // `settleRollover` reports it with the sample the ledger has (row 28).\n await settleRollover(deps, sessionId, turn)\n clearAnchors(deps, sessionId)\n clearPending(deps, sessionId)\n // The plan map is normally reconciled by `SessionRuntime.notePlanTurn` on\n // the first real request of a turn. If that request has not run yet, a\n // plan still in the map belongs to the previous turn and would fire\n // against this new-turn receipt; drop it. When the request did run,\n // `notePlanTurn` reports false and the plan present was parsed by that\n // request's response: keep it, because clearing would discard a valid\n // new-turn plan.\n let planForThisTurn = false\n try {\n planForThisTurn = deps.sessions?.notePlanTurn(sessionId, turn) === false\n } catch {\n planForThisTurn = false\n }\n if (!planForThisTurn) clearPlan(deps, sessionId)\n }\n state.recordRoot(sessionId, turn, receipt)\n fileDispatchedReceipt(state, exec, sessionId, turn, receipt)\n\n // Conservative local invalidation check. The tool-result path cannot see\n // the host pruner (it rewrites session surface nodes, not this waterfall)\n // or compaction, so only the **marker** branch is meaningful here: it\n // catches a receipt whose tool output itself carries the pruner literal.\n // The anchor comparison needs the anchored receipt's current text and\n // belongs to the model-request path (23c); running it here would compare a\n // different call's text and fire a false compaction-reset after every\n // commit (review F1). A hit only abandons the decision, which is safe.\n const pending = pendingAnchorsOf(deps, sessionId)\n // `!= null` rather than `!== undefined`: a foreign store can hand back a\n // null, and dereferencing it would throw out of the hook.\n if (pending != null) {\n const reset = markerResetOf(pending, receipt.text)\n if (reset !== undefined) {\n await resetInvalidatedPending(deps, exec, sessionId, turn, pending, reset)\n if (retrieval !== undefined) {\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, receipt.text)\n }\n return decision\n }\n }\n\n const ctx: DecisionContext = {\n sessionId,\n exec,\n receipt,\n doc: await scopeDocOf(deps),\n result,\n state,\n turn,\n retrievalCall: retrieval !== undefined,\n }\n const outgoing = await applyDecision(deps, decision, ctx)\n if (retrieval !== undefined) {\n // The retrieval receipt's content figure must price what enters history\n // after projection, not the raw result it arrived with.\n const visible = decisionTextOf(outgoing) ?? receipt.text\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, visible)\n }\n return outgoing\n } catch {\n // Never lose the tool's real output to a wiring bug in this listener.\n return decision\n }\n}\n\n/**\n * Drop a pending entry whose call id matches the arriving result.\n *\n * The execute hook clears the entry when it inspects an accepted or rejected\n * dispatch, but a call denied by `tools/pre-execute` never reaches that hook;\n * post-execute is then the only observer that knows the substituted call is\n * over. A different call id is an ordinary call and leaves the entry alone.\n */\nfunction clearMatchingPending(\n deps: HookDeps,\n sessionId: string,\n exec: PostExecuteExec,\n): void {\n const pending = peekPending(deps, sessionId)\n if (pending === undefined) return\n if (typeof exec.callId !== 'string' || exec.callId !== pending.callId) return\n clearPending(deps, sessionId)\n}\n\n/** File an executed candidate's receipt under its plan id, consuming the dispatch record. */\nfunction fileDispatchedReceipt(\n state: ReceiptSessionState,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n receipt: CanonicalReceipt,\n): void {\n const callId = exec?.callId\n if (typeof callId !== 'string') return\n const candidateId = state.takeDispatch(sessionId, turn, callId)\n if (candidateId === undefined) return\n state.recordCandidate(sessionId, turn, candidateId, receipt)\n}\n\n/** The host's `ToolExecutionResult` failure branch for a refused dispatch. */\nfunction dispatchFailure(message: string): unknown {\n return {\n isError: true,\n error: {\n message,\n info: { name: 'DispatchRejectedError', code: 'dispatch-rejected' },\n },\n content: [{ type: 'text', text: `Error: ${message}` }],\n }\n}\n\n/** Record one refused dispatch; a receipt write never changes the verdict. */\nasync function appendDispatchRejected(\n deps: HookDeps,\n exec: DispatchExec,\n entry: PendingEntry,\n sessionId: string,\n): Promise<void> {\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: clockTurnOf(deps, sessionId) ?? 0,\n stepId: 'root',\n kind: 'skip',\n code: 'dispatch-rejected',\n tool: exec.name,\n callId: typeof exec.callId === 'string' ? exec.callId : undefined,\n candidateId: entry.candidateId,\n // The refused call's own args, not the pending decision's: the operator\n // needs to see exactly what the host was asked to run.\n args: exec.arguments,\n preview: callPreview(exec.name, exec.arguments),\n })\n}\n\n/**\n * The inspect half of `tools/execute`: no `next()` is called here, so a throw\n * can never cause the dispatch to run twice.\n *\n * Every operation is contained (the lookup, the clearing, the receipt write),\n * so the only throw this function can produce is a bug of its own; the caller\n * then fails open.\n */\nasync function inspectDispatch(\n deps: HookDeps,\n exec: DispatchExec,\n): Promise<\n | { kind: 'next' }\n | { kind: 'reject'; message: string }\n | {\n kind: 'accept'\n sessionId: string\n callId: string\n candidateId: string\n /** The plan/guard evidence the entry carried; mirrored for a rollover settle. */\n evidence: SubstitutionEvidence | undefined\n }\n> {\n const sessionId = sessionIdOf(exec)\n if (sessionId === undefined) return { kind: 'next' }\n\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'next' }\n\n const reject = async (message: string) => {\n clearPending(deps, sessionId)\n await appendDispatchRejected(deps, exec, entry, sessionId)\n return { kind: 'reject' as const, message }\n }\n\n // A different call id is an ordinary call, not tampering: the host assigns\n // call ids, so only a call that carries the id we chose is the dispatch under\n // inspection. Rejecting the rest would lose a legitimate tool's output (F2).\n if (typeof exec.callId !== 'string' || exec.callId !== entry.callId) {\n return { kind: 'next' }\n }\n // `rejectIfTampered` compares name and parsed arguments only; the call id was\n // compared above.\n if (rejectIfTampered(exec, entry).reject) {\n return reject(\n 'dsh-boost refused a substituted call: the dispatched arguments do not match the pending decision',\n )\n }\n\n // Accept path: the entry has done its job, so drop it before dispatching.\n clearPending(deps, sessionId)\n return {\n kind: 'accept',\n sessionId,\n callId: entry.callId,\n candidateId: entry.candidateId,\n evidence: (entry as AuditedPendingEntry).evidence,\n }\n}\n\n/**\n * The `tools/execute` hook body: refuse a tampered substitution.\n *\n * With no pending entry the plugin is not substituting this call, so `next()`\n * runs untouched. The entry describes the dispatch we synthesised: a call that\n * carries the **same** call id is inspected, compared with the decision, and\n * the entry is cleared on both the accept and the reject path so it cannot\n * outlive its dispatch. A call with a **different** call id is an ordinary call\n * — the host assigns ids — and passes through without touching the entry\n * (review F2: rejecting it would lose a legitimate tool's output). On the\n * accept path the call id is remembered so the following `post-execute` can\n * file the receipt under its candidate id.\n *\n * The mount fails open on an internal error (the design's fail-closed means\n * \"pass through, do not substitute\", never \"intercept\"): a broken queue must\n * not block every tool call in the process.\n */\nasync function executeHook(\n deps: HookDeps,\n state: ReceiptSessionState,\n exec: DispatchExec,\n next: () => Promise<unknown>,\n): Promise<unknown> {\n let outcome: Awaited<ReturnType<typeof inspectDispatch>>\n try {\n outcome = await inspectDispatch(deps, exec)\n } catch {\n return next()\n }\n\n if (outcome.kind === 'reject') return dispatchFailure(outcome.message)\n if (outcome.kind === 'accept') {\n const turn = clockTurnOf(deps, outcome.sessionId) ?? 0\n try {\n state.recordDispatch(outcome.sessionId, turn, outcome.callId, outcome.candidateId)\n } catch {\n // Losing the mapping costs the candidate receipt, not this call.\n }\n // The same fact, kept outside `ReceiptSessionState` because the candidate's\n // post-execute consumes that mapping before a rollover can look at it.\n noteAcceptedDispatch(\n deps,\n outcome.sessionId,\n turn,\n outcome.candidateId,\n outcome.evidence,\n )\n }\n return next()\n}\n\n// ---------------------------------------------------------------------------\n// Registration\n// ---------------------------------------------------------------------------\n\n/** Mount the projection waterfall. */\nfunction registerPostExecute(\n ctx: PluginContext,\n deps: HookDeps,\n state: ReceiptSessionState,\n): void {\n ctx.on('tools/post-execute', (exec, result, next) => postExecute(deps, state, exec, result, next))\n}\n\n/** Mount the model-request waterfall; the hook function is built once per registration. */\nfunction registerLlmStream(ctx: PluginContext, deps: HookDeps): void {\n const hook = streamHook(deps)\n ctx.on('llm/stream', (options, next) => hook(options, next))\n}\n\n/** Mount the dispatch waterfall. */\nfunction registerExecute(ctx: PluginContext, deps: HookDeps, state: ReceiptSessionState): void {\n ctx.on('tools/execute', (exec, next) => executeHook(deps, state, exec, next))\n}\n\n/** Mount the protocol section, whose provider stays synchronous and per-agent. */\nfunction registerProtocolSection(ctx: PluginContext, scope: ScopeStore | undefined): void {\n ctx.systemPrompt.section({\n name: PROTOCOL_NAME,\n order: PROTOCOL_ORDER,\n interpolate: false,\n text: (context) => protocolText(scope, context),\n })\n}\n\n/**\n * Register the plugin's four host integration points.\n *\n * The prompt section is registered first on purpose: it is the only mount that\n * rejects a duplicate name, so a second `apply` aborts here before any event\n * hook is mounted twice (the host turns a duplicate section into an error, and\n * `apply` treats that as \"already mounted\"). Registering it last would leave\n * three live duplicate listeners behind.\n *\n * One `ReceiptSessionState` belongs to the whole registration: the execute\n * mount writes the in-flight call mapping and the post-execute mount consumes\n * it, so the two waterfalls must share it.\n *\n * `scope`, `receipts`, `anchors` and `resolveSession` are required by\n * `HookDeps`, but they are still checked at the point of use: a host wiring the\n * plugin without one of the optional pieces still gets the four mount points,\n * and every degraded path is fail-closed instead of throwing during\n * registration.\n */\nexport function registerHooks(ctx: PluginContext, deps: HookDeps): void {\n const state = deps.sessionState ?? new ReceiptSessionState()\n // Publish the instance we created. `clearSession` and Task 23c-2's session-end\n // wiring reach the state through `deps.sessionState`; a caller that omits it\n // (the plan's 23c-2 assembly list does) would otherwise leave the created\n // receipt/dispatch maps unreachable and leaked per session.\n deps.sessionState = state\n // The logger is a host service the caller already has; publishing it here\n // keeps the degradation warnings reachable without widening every caller's\n // deps literal. A deps object that already names one keeps it.\n deps.logger ??= ctx.logger\n registerProtocolSection(ctx, deps.scope)\n registerPostExecute(ctx, deps, state)\n registerLlmStream(ctx, deps)\n registerExecute(ctx, deps, state)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"post-execute.js","sourceRoot":"","sources":["../../src/hooks/post-execute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2EG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAI1D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,MAAM,EAAE,MAA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KAAK,CAAC,CAAA;IACxC,mBAAmB,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;IACrC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC5B,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;AACnC,CAAC","sourcesContent":["/**\n * Host hook assembly: the four mount points the plugin owns, and the\n * post-execute decision path that turns the gate into a working product.\n *\n * Registration stays split one function per mount so each body can be replaced\n * without rewriting the mount:\n *\n * - `tools/post-execute` first gates on the same cached scope judgement the\n * protocol section reads, then canonicalises the result and runs a\n * conservative invalidation check. It files the arriving receipt under\n * `'root'`, works the substitution decision (`decide` → admission → pending\n * queue / shadow receipt / fallback), then the double-projection guard, and\n * finally projects the receipt when the scope document asks for it. Order is\n * fixed: `next() → scope gate → canonicalise → invalidate → decide →\n * (shadow receipt | admit and enqueue | fallback) → double-projection guard →\n * projection → return the decision` (plan §Task 23b). A call with no\n * `exec.agent` is not the plugin's to inspect: the downstream decision is\n * returned untouched and a `skip:no-scope` receipt keeps the pass visible\n * (design §5.5). A call carrying `exec.parent` is a PTC inner dispatch and\n * returns before any of this: it is not the step's root receipt.\n * - `llm/stream` is the model-request waterfall. Its body lives in\n * `./llm-stream.ts` (Task 23c-1) and is re-exported below: it lets the\n * plugin's own selector request through untouched, then answers a pending\n * decision with a synthesized turn or delegates to `next()` after the\n * turn/anchor checks. The mount is registered here because `registerHooks`\n * is the single assembly surface.\n * - `tools/execute` looks the session's pending substitution up with `peek`\n * (never `take`: the entry must survive to this hook), compares the arriving\n * `callId` itself. A **differing** `callId` is not tampering: the host assigns\n * call ids and our synthesized turn sets the one we chose, so a call carrying\n * a different id is an ordinary call that has nothing to do with the\n * substitution — it passes through untouched. Only when the ids are equal does\n * `rejectIfTampered` run, and only then is the entry cleared (on accept or\n * reject), because the entry has then served its purpose.\n * - the `systemPrompt` section reads the per-agent judgement cache\n * synchronously. Its `text` must be a function, never a static string: a\n * static string would inject the protocol into every session unconditionally\n * and defeat the scope document (design §5.5).\n *\n * ## What Task 23b added\n *\n * The receipt map (`ReceiptSessionState`) keys `'root'` to the receipt that\n * just arrived and each executed candidate's id to its own receipt, so guards\n * and `$public` templates always read the arrival-time canonical text and a\n * later step can project a value from an earlier step. The executable args\n * always come from the *decision* (`decision.args` / `decision.candidates[i]\n * .args`), never from `plan.steps[i].args`, which still holds `$public`\n * templates. A plan is one-shot per receipt: the first post-execute that reads\n * it removes it, so neither a guard failure nor a commit can leave the block\n * alive to fire against a later receipt (the model writes a new block for its\n * next call). It also means `decide` cannot re-commit the same step.\n *\n * The `shadow` flag from the scope document drives both `decide` (which skips\n * the whitelist) and the record-only branch: a shadow commit writes a\n * `{kind:'shadow'}` receipt and neither enqueues nor takes budget. It does\n * **not** suppress projection: `shadow` and `projection` are independent\n * switches (design §5.2-5), and projection-shadow mode writes only its\n * accounting receipt. Admission runs in the mandated order — existence,\n * `worthSubstituting`, then `budget.take()` — so a fallback never spends budget\n * for a call it did not substitute.\n *\n * Everything here is contained: the host turns a throwing `post-execute`\n * listener into an error result and the tool's real output is lost, so every\n * foreign call (stores, queue, clock, usage, estimator) is wrapped. The\n * `tools/execute` mount is contained too, failing open on an internal error:\n * the design's fail-closed definition is \"pass through, do not substitute\",\n * never \"intercept the call\" (design §5.5).\n *\n * The provider's `c.scope` is the agent itself at runtime: the host builds the\n * assembly context as `{ agent, scope: agent, signal }`\n * (`@deepseek-ai/dsh-agent/lib/index.js:410`), even though the declared type is\n * the opaque `ScopeKey`. Keying the cache on anything else — or falling back to\n * a no-argument judgement — would leak one session's visibility into another.\n *\n * @module dsh-boost/hooks/post-execute\n */\nimport { worthSubstituting } from '../admission/ledger.js'\nimport type { StepBudget } from '../admission/ledger.js'\nimport type { RetrievalLedger } from '../admission/retrieval.js'\nimport type { UsageLedger } from '../admission/usage.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { decide } from '../gate/decide.js'\nimport { alreadySpilled, looksPruned } from '../gate/invalidate.js'\nimport type { AnchorStore, ReceiptAnchors } from '../gate/invalidate.js'\nimport type { Candidate, Guard, Plan } from '../gate/plan.js'\nimport { isPosixOnly } from '../host/platform.js'\nimport type { ProjectionCounters } from '../projection/counters.js'\nimport { PROTOCOL_NAME, PROTOCOL_ORDER, PROTOCOL_TEXT } from '../prompt/protocol.js'\nimport { projectApply, projectShadow } from '../projection/apply.js'\nimport type { FormatFooter, ProjectionMode, SpillBackend, SpillHandle } from '../projection/apply.js'\nimport { canonicalise } from '../projection/canonicalise.js'\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport type { ReceiptStore } from '../receipts/store.js'\nimport { DEFAULT_SCOPE, isVisible } from '../scope/doc.js'\nimport type { ScopeDoc } from '../scope/doc.js'\nimport type { ScopeStore } from '../scope/store.js'\nimport { SELECTOR_SYSTEM_PROMPT, choose, selectorPromptText } from '../selector/jev.js'\nimport type { LlmLike } from '../selector/jev.js'\nimport { familyOf } from '../tools/family.js'\nimport type {\n AbortSignalLike,\n AgentLike,\n BoostConfig,\n PluginContext,\n ResolvedToolSet,\n} from '../types.js'\nimport type { TurnClock } from './clock.js'\nimport { rejectIfTampered } from './execute.js'\nimport {\n budgetWired,\n receiptsStopped,\n sessionBudget,\n sessionClock,\n sessionUsage,\n settleDiscarded,\n streamHook,\n} from './llm-stream.js'\nimport type { SessionRuntime } from './llm-stream.js'\nimport { callIdFor } from './pending.js'\nimport type { PendingEntry, PendingQueue } from './pending.js'\nimport {\n ReceiptSessionState,\n appendReceipt,\n callPreview,\n clearAnchors,\n clearPlan,\n clearPending,\n clockTurnOf,\n peekPending,\n previewOf,\n} from './session-state.js'\nimport type { ReceiptInput } from './session-state.js'\n\n/**\n * The `llm/stream` body lives in its own module (Task 23c-1). It is re-exported\n * here because `registerHooks` is the assembly surface the rest of the plugin\n * and the integration tests import; the mount below uses the same function.\n */\nexport { streamHook }\n\n/**\n * The substitution whitelist: exactly the read-only trio (design §5.2-5).\n *\n * One constant drives both `decide` (non-shadow) and the `whitelisted` field\n * written to the shadow/substitute receipts, so the policy the gate enforced\n * and the policy the audit trail reports cannot drift. `bash`, `web_fetch` and\n * every write tool stay out: they have no deterministic read-only judgement.\n */\nexport const SUBSTITUTION_WHITELIST: ReadonlySet<string> = new Set(['read', 'grep', 'glob'])\n\n/**\n * Hard cap on the receipt text shown to the selector.\n *\n * A full 40 KB receipt would dominate the selector call before the candidate\n * summaries are added. This cap keeps the receipt near 300 tokens even when the\n * tool family's projection window is larger, while still showing the\n * projection's head/tail shape. The actual input+output charge is computed\n * from the text that is sent, never from this cap alone.\n */\nconst SELECTOR_RECEIPT_MAX_CHARS = 1_200\n\n/** The route an `ask-selector` request inherits from the boundary request. */\nexport interface SelectorRoute {\n provider: string\n model: string\n reasoningEffort?: string\n}\n\n/** The dependencies the mounts read; Task 23c constructs the whole set once. */\nexport interface HookDeps {\n config: BoostConfig\n scope: ScopeStore\n receipts: ReceiptStore\n /**\n * Per-session receipt anchors (design §5.2-7).\n *\n * Written by the decision path on a real commit and read here to detect an\n * external rewrite; a hit clears them. Required by the contract: without a\n * store the invalidation check is silently dead.\n */\n anchors: AnchorStore\n /**\n * Session id to workspace id.\n *\n * Required: substitution is refused for a session that does not resolve to a\n * workspace, or whose live scope document does not list that workspace. The\n * judgement cache alone can be stale, and the replacement path must never\n * run without a current visibility answer (design §5.5). Returning\n * `undefined` is fail-closed, never an error.\n */\n resolveSession: (sessionId: string) => string | undefined\n /** At most one pending substitution per session; absent means the path is inert. */\n queue?: PendingQueue\n /**\n * Per-turn substitution budget; absent **and with no `sessions` runtime**\n * means no cap is applied. Used only when `sessions` is absent, so a shared\n * instance is never preferred over the per-session runtime. A shared instance\n * that another session already borrowed is not \"no budget\": `sessionBudget`\n * answers `undefined` for the refused loan and the decision path treats it as\n * exhausted (row 21).\n */\n budget?: StepBudget\n /** Usage pairing; the shared fallback when `sessions` is absent (T21/T23c). */\n usage?: UsageLedger\n /**\n * The host turn/step clock; `step()` is the only source of a call id's step.\n * The shared fallback when `sessions` is absent.\n */\n clock?: TurnClock\n /**\n * Per-session clock, budget and usage (Task 23c).\n *\n * A shared `clock` lets another session's turn/step stamp this session's\n * `callId`; a shared `StepBudget` starves a session; a shared `UsageLedger`\n * pairs one session's substitution with another session's request. When\n * supplied, this runtime is authoritative and the three single instances\n * above are only the fallback for a plugin wired without it. 23c-2 constructs\n * one `SessionRuntime`, drives `onModelRequest` from the host's\n * `agent/request` payload, and passes it here.\n */\n sessions?: SessionRuntime\n /**\n * The host LLM service, used only for the `ask-selector` call.\n *\n * Optional so a minimal assembly (or a unit test of the decision path)\n * degrades to a record-only abstention rather than crashing. The selector\n * request carries `purpose: 'boost-selector'`, which the frozen stream hook\n * lets through untouched (Task 23c-2).\n */\n llm?: LlmLike\n /**\n * The effective provider/model of the session's latest model request.\n *\n * The selector request must inherit the boundary request's route; this hook\n * has no `GenerateOptions` of its own, so 23c-2 captures it from the\n * `agent/request` waterfall and exposes it here. Missing means the selector\n * cannot run and `ask-selector` records an abstention.\n */\n selectorRoute?: (sessionId: string) => SelectorRoute | undefined\n /** Parsed plans per session, written by 23c's stream hook. */\n plans?: Map<string, Plan>\n /**\n * The per-session receipt/dispatch store. Optional so 23c can own the\n * instance and call `clear(sessionId)` on a session-end signal; when omitted,\n * `registerHooks` creates one. Lifetime: the store keeps one host turn's\n * receipts and in-flight dispatches per session, folds them on the first call\n * of a new turn, and otherwise retains the last turn until `clear` (or process\n * exit). The class documents the reasoning.\n */\n sessionState?: ReceiptSessionState\n /** The host spill backend; absent skips apply-mode projection. */\n spill?: SpillBackend\n /**\n * Session → spill locators of the receipts this plugin projected.\n *\n * Its only producer is a real spill write (design §5.3): the applied outcome\n * carries the locator, and a later `read`/`grep` naming it becomes a\n * `projection-retrieval` receipt whose cost is subtracted from the projection\n * net. Optional so a minimal assembly degrades to uncounted retrievals rather\n * than crashing; `apply` constructs one and `clearSession` drops a session's\n * set on disposal.\n */\n retrievals?: RetrievalLedger\n /**\n * Projection skip counters (Task 25 review).\n *\n * `projectDecision` increments the unknown-family counter when a tool name has\n * no configured family, so status can distinguish \"no window, by design\"\n * from \"the mapper missed a decorated name\".\n */\n projectionCounters?: ProjectionCounters\n /**\n * Token estimator; absent means no meter.\n *\n * Projection still clips, but records `estimate:'unknown'` and no token\n * numbers; substitution is refused before it can spend money (design §9).\n */\n estimateText?: (t: string) => number\n /**\n * Which estimator produced a projection receipt's numbers.\n *\n * `host` means the synchronous host token meter priced it. `unknown` is the\n * only meterless value: a projection without a meter still clips, but its\n * receipt carries `estimate:'unknown'` and no numbers at all. There is\n * deliberately no characters-over-four arm — a fixed-density guess is not a\n * measurement, and admitting the type would let a future producer stamp a\n * fabricated figure as if the host had measured it.\n */\n estimateKind?: 'host' | 'unknown'\n /**\n * The host spill-notice predicate, injected instead of imported.\n *\n * Kept because the host spill policy is not declared as a dependency at all and a\n * test needs to hand over a throwing predicate without the host package.\n * Production omits it and the dynamically imported host function is used.\n */\n hasSpillNotice?: (text: string) => boolean\n /**\n * The host spill footer renderer, injected instead of imported.\n *\n * The same seam and the same reason as {@link hasSpillNotice}: the notice\n * module is reached by `import()` only, and a test must be able to exercise\n * the \"module absent\" path (which disables apply-mode projection) without\n * uninstalling the host package. Returning `undefined` means the module has\n * no renderer; production omits this and the dynamically imported host\n * function is used.\n */\n resolveFooter?: () => FormatFooter | undefined | Promise<FormatFooter | undefined>\n /**\n * The session's runtime replay horizon (design §5.3), when the assembly can\n * supply it.\n *\n * The horizon is `min(config horizon, mean of the session's last\n * `historyTurns` turns)`. Its instance (`RuntimeStepHorizon`) is built in\n * `src/index.ts` and read there by `status`; the decision path can only see\n * it through this seam. A projection receipt pins whatever this returns, so\n * a historical saving is never re-valued by a later cross-session minimum.\n * Absent (the current production wiring) means the resolved config's\n * `horizonSteps` is the horizon in effect.\n */\n horizonFor?: (sessionId: string) => number\n /**\n * Drop the per-session dispatch mirror on disposal.\n *\n * `clearSession` lives in the stream hook and the mirror lives here, so the\n * teardown reaches it through this seam rather than exporting the map. Wired\n * by `apply`; absent in tests, which is why it is optional and guarded.\n */\n clearAcceptedDispatch?: (sessionId: string) => void\n /**\n * Mirror a synthesized turn for a possible rollover settlement (row 27).\n *\n * `llm/stream` owns the synthesis but the mirror lives here next to the\n * execute-side record, so the fact crosses on a seam rather than by exporting\n * the map. It is written at synthesis time, not at dispatch acceptance: a\n * call denied by `tools/pre-execute` never reaches `tools/execute`, and the\n * skipped model round must still be reported when a late result rolls the\n * turn over. `registerHooks` wires it; absent means the mirror stays\n * execute-only (under-report, never a false saving).\n */\n noteSynthesis?: (\n sessionId: string,\n turn: number,\n candidateId: string,\n evidence: SubstitutionEvidence | undefined,\n ) => void\n /**\n * The host logger, for the few conditions that have no other surface.\n *\n * `registerHooks` fills it from `ctx.logger` when absent, so production never\n * passes it explicitly. A missing footer renderer is the one current caller:\n * it logs once, and `status` reports the same condition as a stable code.\n */\n logger?: { warn(message: string): void }\n}\n\n/** The execution facts a `tools/post-execute` listener reads here. */\ntype PostExecuteExec = {\n name?: string\n callId?: string\n agent?: AgentLike | undefined\n /**\n * The host's cancellation signal. `tools/post-execute` is async, and the\n * host contract requires async listeners to observe `exec.signal`; this\n * listener reads `aborted` before it does any projection work.\n */\n signal?: AbortSignalLike | undefined\n /** Parsed tool arguments; the retrieval matcher reads them (Task 25). */\n arguments?: unknown\n /**\n * The step's resolved tool admission (`dsh-tools`' `ResolvedToolSet`).\n *\n * A real model step always has one: the host's pipeline builds the execution\n * as `...toolSet === void 0 ? {} : { toolSet }`. It is optional here because\n * embedded/legacy call sites can omit it, and the decision path records\n * `substitute-skipped:no-toolset` rather than refusing (row 7).\n */\n toolSet?: ResolvedToolSet\n /**\n * PTC transport token. Present on an SDK sub-dispatch (`tools/execute` and\n * `tools/post-execute` run for inner calls too), where the result belongs to\n * the enclosing `run_code` step and is not the step's root receipt.\n */\n parent?: unknown\n}\n\n/** The normalized result fields canonicalisation reads. */\ntype PostExecuteResult = {\n content?: ReadonlyArray<{ type: string; text?: string }> | undefined\n isError?: boolean | undefined\n}\n\n/**\n * A post-execute decision.\n *\n * Only `kind` is interpreted here; every other field belongs to the host\n * contract (`accept` with content/value, or `block`).\n */\ntype PostExecuteDecision = {\n kind: 'accept' | 'block'\n [key: string]: unknown\n}\n\n/** The dispatch fields the tamper check reads (the host passes a `ToolExecution`). */\ntype DispatchExec = {\n name: string\n arguments: unknown\n /** Host-issued call id; compared here because `rejectIfTampered` never sees it. */\n callId?: string\n agent?: AgentLike | undefined\n /**\n * PTC transport token. An inner call belongs to the enclosing `run_code`\n * step: its host-assigned call id is not the root decision's, so the\n * tamper check must not read a collision as our dispatch (row 30).\n */\n parent?: unknown\n}\n\n/** Everything one decision pass needs, computed once by the listener. */\ntype DecisionContext = {\n sessionId: string\n exec: PostExecuteExec\n receipt: CanonicalReceipt\n doc: ScopeDoc\n result: PostExecuteResult | undefined\n state: ReceiptSessionState\n turn: number\n /** The tool call itself names one of this session's spill locators. */\n retrievalCall?: boolean\n}\n\n/** Skip reasons that mean the projection machinery degraded, not \"nothing to cut\". */\nconst PROJECTION_DEGRADATIONS: ReadonlySet<string> = new Set([\n 'no-spill',\n 'no-owner',\n 'projection-skipped:no-footer',\n 'spill-failed',\n 'footer-failed',\n])\n\n/** The judgement-cache key carried by the assembly context's `scope`. */\nfunction agentKeyOf(scope: unknown): string | undefined {\n const id = (scope as AgentLike | undefined)?.session?.header?.id\n return typeof id === 'string' ? id : undefined\n}\n\n/** The session a hook call belongs to, or `undefined` when the host supplied none. */\nfunction sessionIdOf(exec: PostExecuteExec | DispatchExec | undefined): string | undefined {\n const id = (exec as PostExecuteExec | undefined)?.agent?.session?.header?.id\n return typeof id === 'string' ? id : undefined\n}\n\n/**\n * Whether the host cancelled the call that produced this result.\n *\n * `tools/post-execute` is async, and the host contract (`dsh-tools`'\n * `events.d.ts`) requires async listeners to observe `exec.signal`. A\n * cancelled call's result never reaches the model, so projecting it would pay\n * a spill write and persist an artifact nobody can read. The signal crosses\n * the host boundary, so a malformed one means \"not cancelled\" rather than a\n * reason to throw out of the hook.\n */\nfunction cancelled(exec: PostExecuteExec | undefined): boolean {\n try {\n return exec?.signal?.aborted === true\n } catch {\n return false\n }\n}\n\n/**\n * The protocol section's synchronous provider.\n *\n * It may only read the cached judgement: the host assembles prompts\n * synchronously, so there is nothing to await. A missing store, a store without\n * `judgement`, a context without `scope`, and a scope without a session id all\n * mean \"inject nothing\" (fail-closed, design §5.5).\n */\nfunction protocolText(scope: ScopeStore | undefined, context: { scope?: unknown }): string {\n if (scope == null || typeof scope.judgement !== 'function') return ''\n const key = agentKeyOf(context?.scope)\n if (key === undefined) return ''\n return scope.judgement(key) ? PROTOCOL_TEXT : ''\n}\n\n// ---------------------------------------------------------------------------\n// Defensive readers: every foreign call is wrapped\n// ---------------------------------------------------------------------------\n\n/**\n * The host step index, or `undefined` when no clock can supply one.\n *\n * `undefined` is fail-closed: the decision path refuses to invent a step\n * (a plugin-side counter would collide two substitutions in one turn — T23a).\n */\nfunction clockStepOf(deps: HookDeps, sessionId: string): number | undefined {\n try {\n const step = sessionClock(deps, sessionId)?.step()\n return typeof step === 'number' && Number.isFinite(step) ? step : undefined\n } catch {\n return undefined\n }\n}\n\n/** The session's anchors without ever failing the call. */\nfunction pendingAnchorsOf(deps: HookDeps, sessionId: string): ReceiptAnchors | undefined {\n try {\n return deps.anchors?.get(sessionId)\n } catch {\n return undefined\n }\n}\n\n/**\n * The only invalidation branch that is live at this call site: the prune marker.\n *\n * `invalidate` also compares the anchor text, but a `tools/post-execute` receipt\n * is a *different* call's body, so that comparison can never establish the\n * anchored receipt's identity here; it would fire `compaction-reset` after every\n * commit, drop the anchors obligation 10 exists to keep for 23c, and skip one\n * decision (review F1). The anchor branch belongs on the model-request path\n * (`llm/stream`, 23c), where the compared text is the anchored receipt's current\n * body in the outgoing messages.\n */\nfunction markerResetOf(\n pending: ReceiptAnchors,\n receiptText: string,\n): 'pruned-reset' | undefined {\n try {\n if (pending == null) return undefined\n return looksPruned(receiptText) ? 'pruned-reset' : undefined\n } catch {\n return undefined\n }\n}\n\n/** Write one ledger record, keyed to the session and host turn. */\nfunction ledgerEntry(\n ctx: DecisionContext,\n kind: 'shadow' | 'projection' | 'skip',\n code: string,\n extra: Record<string, unknown> = {},\n): ReceiptInput {\n return {\n version: 1,\n ts: new Date().toISOString(),\n sessionId: ctx.sessionId,\n turn: ctx.turn,\n kind,\n code,\n ...(typeof ctx.exec.name === 'string' ? { tool: ctx.exec.name } : {}),\n // The operator's evidence line: the canonical receipt head and the executed\n // args. Without args every same-tool/same-turn receipt hashed identically\n // (stepId is always 'root').\n preview: previewOf(ctx.receipt.text),\n ...(ctx.exec.arguments !== undefined ? { args: ctx.exec.arguments } : {}),\n ...extra,\n }\n}\n\n/**\n * Caps on the plan evidence a substitution receipt carries.\n *\n * G2 (design line 71) requires the receipt to answer \"why was the model not\n * asked\" with 计划、守卫、绑定、回执、节省量; without the plan and the guards an\n * auditor sees what ran but not why it was legitimate. The plan is\n * model-written text though, and a receipt is one line: 256 code points of\n * goal (the same order as `preview`), at most 8 guards, and at most 300 code\n * points per guard. The bound is a *code-point* cap, not a byte cap: one\n * pathological plan can contribute up to ~9.6 KB from the guards alone\n * (8 × 300 code points × 4 UTF-8 bytes for 4-byte characters) plus up to\n * ~1 KB from the 256-code-point goal. That is bounded and auditable, but a\n * receipt line can exceed 10 KB — status and readers must not assume 2.7 KB.\n * Truncation is always visible: the goal ends in `…`, an oversized guard\n * becomes `{truncated_json: \"…\"}`, and `guards_total` is present whenever\n * guards were left out.\n */\nconst MAX_RECEIPT_PLAN_CODE_POINTS = 256\nconst MAX_RECEIPT_GUARDS = 8\nconst MAX_RECEIPT_GUARD_CODE_POINTS = 300\n\n/** What a substitute, substitute-settled or shadow receipt adds about its plan. */\nexport interface SubstitutionEvidence {\n /** The plan's goal, capped to {@link MAX_RECEIPT_PLAN_CODE_POINTS}. */\n plan: string\n /** The committed candidate's guards, up to {@link MAX_RECEIPT_GUARDS}. */\n guards: unknown[]\n /** The plan's guard count, present only when `guards` was capped. */\n guards_total?: number\n}\n\n/**\n * A queued entry carrying the evidence the synth-time receipt needs.\n *\n * `PendingEntry` is the one object that travels from the commit (post-execute)\n * to synthesis (llm-stream), so the evidence rides on it; the settle afterwards\n * reads it back from the ledger pairing. The extra field is additive and never\n * dispatched: `synthesizeTurn` reads `name`/`args` only.\n */\nexport type AuditedPendingEntry = PendingEntry & { evidence?: SubstitutionEvidence }\n\n/** Cap a string by code point so a surrogate pair is never split. */\nfunction capText(value: string, cap: number): string {\n const points = Array.from(value)\n if (points.length <= cap) return value\n return `${points.slice(0, Math.max(0, cap - 1)).join('')}…`\n}\n\n/**\n * The plan/goal and guard evidence for one committed candidate.\n *\n * Guards are carried as written while they fit. Only a guard whose own JSON\n * exceeds {@link MAX_RECEIPT_GUARD_CODE_POINTS} (a multi-KB `text_contains`,\n * say) is replaced by a `truncated_json` marker, so the array stays bounded\n * without silently dropping the guard's form.\n */\nexport function substitutionEvidence(\n goal: unknown,\n guards: readonly Guard[],\n): SubstitutionEvidence {\n const carried = guards.slice(0, MAX_RECEIPT_GUARDS).map((guard) => {\n const json = JSON.stringify(guard) ?? ''\n return Array.from(json).length <= MAX_RECEIPT_GUARD_CODE_POINTS\n ? guard\n : { truncated_json: capText(json, MAX_RECEIPT_GUARD_CODE_POINTS) }\n })\n return {\n plan: capText(typeof goal === 'string' ? goal : '', MAX_RECEIPT_PLAN_CODE_POINTS),\n guards: carried,\n ...(guards.length > MAX_RECEIPT_GUARDS ? { guards_total: guards.length } : {}),\n }\n}\n\n/**\n * Append one `skip:no-scope` receipt.\n *\n * The no-agent case has no session id and no turn; the empty session id and\n * turn zero are honest placeholders, and the `code` is the field status counts.\n */\nasync function appendSkipNoScope(\n receipts: ReceiptStore | undefined,\n exec: PostExecuteExec | undefined,\n sessionId = '',\n turn = 0,\n): Promise<void> {\n if (receipts == null || typeof receipts.append !== 'function') return\n try {\n await receipts.append({\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn,\n kind: 'skip',\n code: 'skip:no-scope',\n tool: exec?.name,\n })\n } catch {\n // A receipt is evidence, not a precondition: never break the call for it.\n }\n}\n\n/** Append one invalidation receipt; a receipt failure never breaks the call. */\nasync function appendResetReceipt(\n receipts: ReceiptStore | undefined,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n stepId: string,\n code: 'pruned-reset' | 'compaction-reset',\n): Promise<void> {\n if (receipts == null || typeof receipts.append !== 'function') return\n try {\n await receipts.append({\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn,\n stepId,\n kind: 'reset',\n code,\n tool: exec?.name,\n })\n } catch {\n // A receipt is evidence, not a precondition: never break the call for it.\n }\n}\n\n/**\n * Abandon the pending decision after an external rewrite.\n *\n * Only the plugin's own anchor record is touched — the session log's current\n * body is never read (design §5.2-7). Clearing happens before the receipt write\n * so a stalled store cannot leave the stale anchors in place; both steps are\n * contained so the tool result survives.\n *\n * The decision-time usage mark is settled **without** a settlement receipt\n * first, exactly like `applyAbandon`: the substitution was never synthesized,\n * so there is no saving to report. Leaving the mark would let the next real\n * request pair itself with it and write a `substitute-settled` line for a\n * substitution that never ran (row 1).\n */\nasync function resetInvalidatedPending(\n deps: HookDeps,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n pending: ReceiptAnchors,\n code: 'pruned-reset' | 'compaction-reset',\n): Promise<void> {\n // Design §5.2-7: a reset returns to the slow path *and* empties pending, so no\n // queued substitution can fire from anchors that no longer name live text. The\n // plan is dropped too: it was written for the invalidated receipt, and leaving\n // it would let it fire against a later one. A dispatch accepted for the\n // invalidated decision must not settle a later mark that reuses its id.\n clearAcceptedDispatch(deps, sessionId)\n settleDiscarded(deps, sessionId)\n clearAnchors(deps, sessionId)\n clearPending(deps, sessionId)\n clearPlan(deps, sessionId)\n await appendResetReceipt(deps.receipts, exec, sessionId, turn, pending.stepId, code)\n}\n\n/**\n * The host's spill-notice predicate, resolved at most once per process.\n *\n * The spill policy is never declared as a dependency (design §5.4), so its notice module is\n * imported dynamically: a static import would make the plugin fail to load on\n * a host without it. A missing package means no receipt can carry its footer,\n * so the guard simply does not fire. The deps seam wins, which is what keeps\n * the guard testable without the host.\n */\nlet noticePredicate: Promise<((text: string) => boolean) | undefined> | undefined\n\nfunction resolveNoticePredicate(\n deps: HookDeps,\n): Promise<((text: string) => boolean) | undefined> {\n if (typeof deps.hasSpillNotice === 'function') return Promise.resolve(deps.hasSpillNotice)\n noticePredicate ??= import('@deepseek-ai/dsh-spill-policy/notice')\n .then((module) => (typeof module.hasSpillNotice === 'function' ? module.hasSpillNotice : undefined))\n .catch(() => undefined)\n return noticePredicate\n}\n\n/**\n * The host's spill footer renderer, resolved lazily.\n *\n * `projectApply` cannot statically import the spill policy for the same reason\n * the notice predicate cannot. A missing package makes apply-mode projection\n * degrade to `projection-skipped:no-footer` in `projectApply` itself — and,\n * because that turns the plugin's headline feature off, the first resolution\n * that yields nothing is logged once (never per receipt, which would drown the\n * log of a busy session). `status` maps the same receipt code to\n * `ERR_HOST_NO_SPILL_NOTICE`, so the degradation also reaches the operator who\n * never reads the log.\n */\nlet footerFormatter: Promise<FormatFooter | undefined> | undefined\n/** One warning per process; a missing host module is not a per-call event. */\nlet footerMissingLogged = false\n\n/** Log the missing-footer degradation once; a foreign logger must not throw. */\nfunction noteMissingFooter(deps: HookDeps): void {\n if (footerMissingLogged) return\n footerMissingLogged = true\n try {\n deps.logger?.warn?.(\n 'dsh-boost: ERR_HOST_NO_SPILL_NOTICE: @deepseek-ai/dsh-spill-policy/notice resolved no formatSpillNotice; ' +\n 'apply-mode projection is disabled (projection-skipped:no-footer) until the host spill policy is available',\n )\n } catch {\n // A logger failure must not become a tool failure.\n }\n}\n\nfunction resolveFooterFormatter(deps: HookDeps): Promise<FormatFooter | undefined> {\n // The seam wins over the memoised import, exactly like `hasSpillNotice`: a\n // test states \"the module resolved nothing\" without uninstalling the host\n // package. It is deliberately not memoised — it belongs to one deps object.\n if (typeof deps.resolveFooter === 'function') {\n return Promise.resolve()\n .then(() => deps.resolveFooter?.())\n .then((formatter) => {\n if (formatter === undefined) noteMissingFooter(deps)\n return formatter\n })\n .catch(() => {\n noteMissingFooter(deps)\n return undefined\n })\n }\n footerFormatter ??= import('@deepseek-ai/dsh-spill-policy/notice')\n .then((module) => {\n if (typeof module.formatSpillNotice !== 'function') return undefined\n return (omitted: { kind: 'exact'; count: number }, ref: SpillHandle) =>\n // T6's `SpillBackend` widens the host's branded `SpillLocator` to\n // `string`; the value is the same at runtime.\n module.formatSpillNotice(\n omitted,\n ref as unknown as Parameters<typeof module.formatSpillNotice>[1],\n )\n })\n .catch(() => undefined)\n .then((formatter) => {\n if (formatter === undefined) noteMissingFooter(deps)\n return formatter\n })\n return footerFormatter\n}\n\n/**\n * The canonical text of the decision that will enter history, when it carries\n * a content array.\n *\n * The host spill policy registers with `{ prepend: true }`: it calls `next()`\n * and applies its footer to *that* decision, so the footer lives in\n * `decision.content` and never in the `result.content` this listener received.\n * `undefined` means \"the decision carries no content\"; the caller then falls\n * back to the receiver as it arrived.\n */\nfunction decisionTextOf(decision: PostExecuteDecision): string | undefined {\n const content = decision.content\n if (!Array.isArray(content)) return undefined\n return canonicalise(content as ReadonlyArray<{ type: string; text?: string }>, false).text\n}\n\n/**\n * Whether projection must be skipped because the host already spilled this\n * receipt (design §5.4).\n *\n * A predicate that throws counts as \"already spilled\": when the notice cannot\n * be ruled out, a second projection could hide the original twice, so the safe\n * direction is to leave the receipt alone.\n */\nasync function isAlreadySpilled(deps: HookDeps, receiptText: string): Promise<boolean> {\n try {\n const hasNotice = await resolveNoticePredicate(deps)\n return hasNotice !== undefined && alreadySpilled(receiptText, hasNotice)\n } catch {\n return true\n }\n}\n\n/** Whether the plugin is active for this session (fail-closed on any doubt). */\nfunction isActiveSession(deps: HookDeps, sessionId: string): boolean {\n const scope = deps.scope\n if (scope == null || typeof scope.judgement !== 'function') return false\n try {\n return scope.judgement(sessionId)\n } catch {\n return false\n }\n}\n\n/**\n * The live scope document, or the strict default when it cannot be read.\n *\n * Read once per decision pass rather than cached: `boost` writes the document\n * while the plugin runs, and the projection/shadow switches must follow it. A\n * missing or throwing reader degrades to `DEFAULT_SCOPE`, whose `shadow: true`\n * makes the substitution path record-only — the safe direction.\n */\nasync function scopeDocOf(deps: HookDeps): Promise<ScopeDoc> {\n try {\n const read = deps.scope?.read\n if (typeof read !== 'function') return DEFAULT_SCOPE\n const result = await read.call(deps.scope)\n const raw = (result as { doc?: unknown } | undefined)?.doc\n if (raw === null || typeof raw !== 'object') return DEFAULT_SCOPE\n return raw as ScopeDoc\n } catch {\n return DEFAULT_SCOPE\n }\n}\n\n// ---------------------------------------------------------------------------\n// Retrieval accounting\n// ---------------------------------------------------------------------------\n\n/** The calls that can retrieve a spilled artifact (design §5.3). */\nconst RETRIEVAL_TOOLS: ReadonlySet<string> = new Set(['read', 'grep'])\n\n/** A detected retrieval, held until the final visible content is known. */\ntype PendingRetrieval = { locator: string }\n\n/**\n * Detect a retrieval without writing anything yet.\n *\n * Detection has to happen before the visibility gate (a projected receipt\n * consumed context whether or not the workspace is still visible), but the\n * cost must wait until projection has decided what the model will actually\n * see (review I3). The split keeps both properties.\n */\nfunction pendingRetrievalOf(\n deps: HookDeps,\n exec: PostExecuteExec,\n sessionId: string,\n): PendingRetrieval | undefined {\n try {\n const name = exec?.name\n if (typeof name !== 'string' || !RETRIEVAL_TOOLS.has(name)) return undefined\n const ledger = deps.retrievals\n if (ledger == null || typeof ledger.locate !== 'function') return undefined\n const locator = ledger.locate(sessionId, exec.arguments)\n return locator === undefined ? undefined : { locator }\n } catch {\n return undefined\n }\n}\n\n/**\n * The one-time cost of one retrieval, or `undefined` when it cannot be priced.\n *\n * This is the **per-receipt** figure: the call block (name + arguments) plus\n * the content the model saw. The replay multiplier is applied once, to both\n * sides of the net formula, in `status` — multiplying only the cost by the\n * horizon made a cheap partial re-read look like a loss (review C1).\n *\n * `content` is the decision's final visible text, so a retrieval that is itself\n * projected is charged for the window, not the raw result (review I3). A\n * missing/non-finite estimate is omitted rather than fabricated.\n */\nfunction retrievalCostOf(\n deps: HookDeps,\n exec: PostExecuteExec,\n content: string,\n): { callTokens: number; contentTokens: number; totalTokens: number } | undefined {\n const estimate = estimatorOf(deps)\n if (estimate === undefined) return undefined\n\n const contentTokens = safeEstimate(estimate, content)\n if (contentTokens === undefined) return undefined\n\n let params = ''\n try {\n params = JSON.stringify(exec.arguments) ?? ''\n } catch {\n params = ''\n }\n const callTokens = safeEstimate(estimate, `${exec.name ?? 'tool'} ${params}`)\n if (callTokens === undefined) return undefined\n\n const totalTokens = callTokens + contentTokens\n return Number.isFinite(totalTokens) ? { callTokens, contentTokens, totalTokens } : undefined\n}\n\n/**\n * Count a `read`/`grep` that names one of this session's spill locators.\n *\n * `appendReceipt` is the store's only write path, and `kind:'projection'` with\n * `retrieved:true` is exactly what `boost status` aggregates as\n * `projection_retrievals` and `projection_retrieval_tokens`. No\n * `saved_projection_tokens` is written: this line documents a cost, not\n * another gross saving.\n *\n * `visibleText` is the content that enters history after projection, which is\n * what the model must pay to replay.\n */\nasync function recordProjectionRetrieval(\n deps: HookDeps,\n exec: PostExecuteExec,\n sessionId: string,\n pending: PendingRetrieval,\n visibleText: string,\n): Promise<void> {\n try {\n const name = exec?.name\n if (typeof name !== 'string') return\n const cost = retrievalCostOf(deps, exec, visibleText)\n const entry: ReceiptInput = {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: clockTurnOf(deps, sessionId) ?? 0,\n kind: 'projection',\n code: 'projection-retrieval',\n tool: name,\n retrieved: true,\n locator: pending.locator,\n // The visible content replays over this horizon in `status`'s net, so it\n // must be the horizon in effect when the retrieval happened, not one read\n // from the whole ledger later.\n horizon_steps: projectionHorizonOf(deps, sessionId),\n preview: previewOf(visibleText),\n ...(exec.arguments !== undefined ? { args: exec.arguments } : {}),\n }\n if (cost === undefined) {\n entry.estimate = 'unknown'\n } else {\n entry.retrieval_call_tokens = cost.callTokens\n entry.retrieval_content_tokens = cost.contentTokens\n entry.retrieval_tokens = cost.totalTokens\n entry.estimate = deps.estimateKind ?? 'unknown'\n }\n await appendReceipt(deps, entry)\n } catch {\n // A retrieval is evidence, never a precondition of the tool result.\n }\n}\n\n// ---------------------------------------------------------------------------\n// Admission and the decision branch\n// ---------------------------------------------------------------------------\n\n/**\n * The conservative saving of skipping one model step: the last real request's\n * replayed context (`input + cacheRead`).\n *\n * The step that is skipped would have replayed at least this much: the context\n * only grows as receipts enter it. A missing ledger or sample is 0, never an\n * interpolation, so admission falls back to the model when it cannot measure\n * (design §5.3: measured, not estimated).\n */\nfunction savedTokensOf(deps: HookDeps, sessionId: string): number {\n try {\n const last = sessionUsage(deps, sessionId)?.last()\n if (last === undefined) return 0\n const { input, cacheRead } = last\n if (!Number.isFinite(input) || !Number.isFinite(cacheRead) || input < 0 || cacheRead < 0) return 0\n const total = input + cacheRead\n return Number.isFinite(total) ? total : 0\n } catch {\n return 0\n }\n}\n\n/**\n * Whether this commit clears the admission threshold.\n *\n * A plan with exactly one candidate is the design's deterministic-single\n * exemption: there is no selector call to pay for, so the threshold does not\n * apply. Any other plan pays no selector either once only one candidate\n * survives, but it still has to show a net win over the threshold; the\n * conservative direction here is to keep the gate on.\n */\nfunction admittedFor(\n deps: HookDeps,\n sessionId: string,\n plan: Plan,\n overheadTokens: number,\n): boolean {\n try {\n const threshold = deps.config?.admission?.thresholdTokens\n const thresholdTokens =\n typeof threshold === 'number' && Number.isFinite(threshold)\n ? threshold\n : DEFAULT_CONFIG.admission.thresholdTokens\n return worthSubstituting({\n savedTokens: savedTokensOf(deps, sessionId),\n overheadTokens,\n thresholdTokens,\n deterministicSingle: plan.steps.length === 1,\n })\n } catch {\n return false\n }\n}\n\n/**\n * Whether the session's turn budget is already empty, without consuming it.\n *\n * A selector call is real spend, so this check runs before the selector is\n * priced or called; the consuming `takeBudget` stays at the commit point.\n * `undefined` from `sessionBudget` has two different meanings (row 21): no\n * budget is wired at all (no cap), or one is wired but was not lent to this\n * session (exhausted, fail closed). Shadow mode never calls this: it spends no\n * step.\n */\nfunction budgetExhausted(deps: HookDeps, sessionId: string): boolean {\n try {\n const budget = sessionBudget(deps, sessionId)\n if (budget == null) return budgetWired(deps)\n if (typeof budget.exhausted !== 'function') return false\n return budget.exhausted() === true\n } catch {\n return budgetWired(deps)\n }\n}\n\n/**\n * Claim one budget step.\n *\n * No budget wired means no cap is applied. A wired budget that this session may\n * not borrow is a refusal, not \"no cap\": `take` fails and the caller records\n * `steps-exhausted` without enqueueing (row 21).\n */\nfunction takeBudget(deps: HookDeps, sessionId: string): boolean {\n try {\n const budget = sessionBudget(deps, sessionId)\n if (budget == null) return !budgetWired(deps)\n if (typeof budget.take !== 'function') return true\n return budget.take()\n } catch {\n return false\n }\n}\n\n/** Record the substitution for the usage pairing; the stream hook settles it. */\nfunction markSubstituted(deps: HookDeps, sessionId: string, candidateId: string): void {\n try {\n sessionUsage(deps, sessionId)?.markSubstituted(candidateId)\n } catch {\n // A ledger miss costs a measurement, never this call.\n }\n}\n\n/** The session's pending usage-mark candidate, or `undefined` for a foreign ledger. */\nfunction pendingCandidateOf(deps: HookDeps, sessionId: string): string | undefined {\n try {\n return sessionUsage(deps, sessionId)?.pendingCandidateId()\n } catch {\n return undefined\n }\n}\n\n/**\n * The last substitution dispatch `tools/execute` accepted for a session.\n *\n * `ReceiptSessionState` records the same callId -> candidate mapping, but the\n * candidate's own `tools/post-execute` consumes it when it files the receipt.\n * A turn rollover needs the fact *after* that consumption: a late parallel\n * tool result can roll the turn before the next real request, and the usage\n * mark must then be reported instead of discarded as if nothing ran. The\n * accepted dispatch is mirrored here together with the evidence that would\n * otherwise be parked for the next settlement.\n *\n * One record per session: a later accepted dispatch (or a later synthesis)\n * replaces it, a session whose usage mark is already gone drops it, and a\n * rollover consumes it. The `HookDeps` key keeps two assemblies in one process\n * from reading each other's sessions. The record is small and per-session; it\n * is never persisted. It is also written at synthesis time through\n * {@link HookDeps.noteSynthesis}: a dispatch denied by `tools/pre-execute`\n * never reaches `tools/execute`, and that skipped model round must still be\n * reportable at a rollover (row 27).\n */\nconst ACCEPTED_DISPATCH = new WeakMap<\n HookDeps,\n Map<string, { turn: number; candidateId: string; evidence?: SubstitutionEvidence }>\n>()\n\n/** Mirror an accepted dispatch for a possible rollover settlement. */\nfunction noteAcceptedDispatch(\n deps: HookDeps,\n sessionId: string,\n turn: number,\n candidateId: string,\n evidence: SubstitutionEvidence | undefined,\n): void {\n let bySession = ACCEPTED_DISPATCH.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n ACCEPTED_DISPATCH.set(deps, bySession)\n }\n bySession.set(sessionId, {\n turn,\n candidateId,\n ...(evidence === undefined ? {} : { evidence }),\n })\n}\n\n/**\n * Consume the accepted dispatch that matches `candidateId`, if any.\n *\n * The turn check is a staleness guard: the record that a pending mark belongs\n * to was written in the turn now rolling over. A record written in the new\n * turn cannot belong to it. The record's own turn is returned so the settled\n * receipt pairs with the dispatch, not with the rollover (row 26).\n */\nfunction takeAcceptedDispatch(\n deps: HookDeps,\n sessionId: string,\n candidateId: string,\n turn: number,\n): { turn: number; evidence?: SubstitutionEvidence } | undefined {\n const bySession = ACCEPTED_DISPATCH.get(deps)\n const record = bySession?.get(sessionId)\n bySession?.delete(sessionId)\n if (record === undefined || record.candidateId !== candidateId || record.turn === turn) {\n return undefined\n }\n return record.evidence === undefined\n ? { turn: record.turn }\n : { turn: record.turn, evidence: record.evidence }\n}\n\n/** Drop the mirrored dispatch; no pending mark is waiting to settle it. */\nexport function clearAcceptedDispatch(deps: HookDeps, sessionId: string): void {\n ACCEPTED_DISPATCH.get(deps)?.delete(sessionId)\n}\n\n/**\n * Settle the usage mark at a turn rollover, reporting a substitution that ran.\n *\n * The ordinary path settles at the first real request after synthesis. A late\n * parallel tool result can roll the turn before that request; the mark must not\n * survive into the new turn, where it would pair with a request that is not the\n * substitution's next one. If `tools/execute` never accepted the synthesized\n * dispatch, the substitution did not run and the mark is a discard. If it did\n * — or if the synthesis itself was mirrored before a `tools/pre-execute`\n * denial (row 27) — the model round really was skipped: the settlement line is\n * written with whatever sample the ledger holds (`'unknown'` when no after-mark\n * request has run yet), with the evidence captured at dispatch, and with the\n * dispatch turn the mirror recorded rather than the rollover turn (row 26), so\n * the substitution is reported instead of disappearing.\n */\nasync function settleRollover(deps: HookDeps, sessionId: string, turn: number): Promise<void> {\n const candidateId = pendingCandidateOf(deps, sessionId)\n if (candidateId === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n\n const dispatched = takeAcceptedDispatch(deps, sessionId, candidateId, turn)\n if (dispatched === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n\n let settled: ReturnType<UsageLedger['settle']>\n try {\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) {\n settleDiscarded(deps, sessionId)\n return\n }\n settled = ledger.settle()\n } catch {\n settleDiscarded(deps, sessionId)\n return\n }\n\n // The parked evidence lives in `llm-stream`'s private map and would outlive\n // the mark. `settleDiscarded` is the module's idempotent cleanup: the ledger\n // was settled above, so this call only forgets that evidence. It runs before\n // the receipt write so the `await` cannot let a new mark be created and then\n // be consumed by this cleanup.\n settleDiscarded(deps, sessionId)\n\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n // Row 26: the substitution happened in the dispatch turn the mirror\n // recorded. Stamping the rollover turn paired a turn-1 substitution with a\n // turn-2 settled line, which reads as a saving from the wrong round.\n turn: dispatched.turn,\n stepId: 'root',\n kind: 'substitute-settled',\n code: 'substitute-settled',\n candidateId,\n ...(dispatched.evidence ?? {}),\n saved_input_tokens: settled.saved_input_tokens,\n cache_hit_delta: settled.cache_hit_delta,\n output_tokens: settled.output_tokens,\n })\n}\n\n/**\n * The receipt ids a candidate's `$public` templates refer to, plus `'root'`.\n *\n * These are the anchors the invalidation check compares against: the chosen\n * candidate's arguments were computed from those receipts, so if any of them\n * is rewritten externally the decision is stale. The walk is iterative and\n * depth-capped because it runs over model-written args; `parsePlan` already\n * caps them at 64 levels, but the hook must not depend on that.\n */\nfunction referencedReceiptIds(args: unknown): Set<string> {\n const ids = new Set<string>(['root'])\n const stack: Array<{ value: unknown; depth: number }> = [{ value: args, depth: 1 }]\n while (stack.length > 0) {\n const frame = stack.pop()\n if (frame === undefined) break\n if (frame.depth > 64) continue\n if (Array.isArray(frame.value)) {\n for (const child of frame.value) {\n if (typeof child === 'object' && child !== null) {\n stack.push({ value: child, depth: frame.depth + 1 })\n }\n }\n continue\n }\n if (typeof frame.value !== 'object' || frame.value === null) continue\n const { $public: template, ...rest } = frame.value as Record<string, unknown>\n if (\n typeof template === 'object' &&\n template !== null &&\n typeof (template as { after?: unknown }).after === 'string'\n ) {\n ids.add((template as { after: string }).after)\n }\n for (const child of Object.values(rest)) {\n if (typeof child === 'object' && child !== null) {\n stack.push({ value: child, depth: frame.depth + 1 })\n }\n }\n }\n return ids\n}\n\n/**\n * Store the session's anchors for the committed candidate.\n *\n * `stepId` is `'root'` because the guards and templates were evaluated against\n * the receipt that just arrived; the map carries that receipt's canonical text\n * plus the text of every receipt the candidate's `$public` templates reference\n * (design §5.2-7). Missing references are omitted rather than invented.\n */\nfunction setAnchors(deps: HookDeps, ctx: DecisionContext, candidateArgs: unknown): void {\n try {\n const anchorsStore = deps.anchors\n if (anchorsStore == null || typeof anchorsStore.set !== 'function') return\n const receipts = ctx.state.receiptsFor(ctx.sessionId, ctx.turn)\n const anchors: Record<string, string> = {}\n for (const id of referencedReceiptIds(candidateArgs)) {\n const receipt = receipts.get(id)\n if (receipt !== undefined) anchors[id] = receipt.text\n }\n anchorsStore.set(ctx.sessionId, { stepId: 'root', anchors })\n } catch {\n // Anchors are a guard input, not the guard: losing them costs a reset.\n }\n}\n\n/**\n * Whether the session may be substituted for right now.\n *\n * Both gates must agree: the cached judgement said yes (the listener would\n * have returned otherwise), and the live document still lists the session's\n * workspace. The second check cannot be skipped: the cache is refreshed by a\n * different task, and a stale \"visible\" must never authorize a replacement.\n */\nfunction substitutableSession(deps: HookDeps, sessionId: string, doc: ScopeDoc): boolean {\n try {\n const workspaceId = deps.resolveSession?.(sessionId)\n if (typeof workspaceId !== 'string') return false\n return isVisible(doc, workspaceId)\n } catch {\n return false\n }\n}\n\n/**\n * A selector-facing summary of one already-bound candidate.\n *\n * The selector only needs to tell candidates apart; the args are included so\n * two calls to the same tool with different paths are distinguishable. The\n * bound tree is safe to show (it is what will run) and bounded so one huge\n * argument cannot dominate the selector prompt.\n */\nfunction selectorSummary(candidate: Candidate): string {\n let args = ''\n try {\n args = JSON.stringify(candidate.args) ?? ''\n } catch {\n // A model-written plan is already JSON, but the summary is evidence-shaped\n // and must not make the selector call throw.\n }\n const text = `${candidate.tool} ${args}`.trim()\n const points = Array.from(text)\n return points.length > 200 ? `${points.slice(0, 200).join('')}…` : text\n}\n\n/** Bound the receipt the selector pays for, using the projection's head/tail shape. */\nfunction selectorReceiptOf(deps: HookDeps, ctx: DecisionContext): string {\n const text = ctx.receipt.text\n const points = Array.from(text)\n if (points.length <= SELECTOR_RECEIPT_MAX_CHARS) return text\n\n const toolName = ctx.exec.name\n const family = toolName === undefined ? undefined : familyOf(toolName)\n const params = family !== undefined ? deps.config.projection[family] : undefined\n const configured = params !== undefined ? params.headChars + params.tailChars : 0\n const total = Math.min(\n SELECTOR_RECEIPT_MAX_CHARS,\n configured > 0 ? configured : SELECTOR_RECEIPT_MAX_CHARS,\n )\n const ratio = configured > 0 && params !== undefined ? params.headChars / configured : 0.8\n const headChars = Math.min(total, Math.max(0, Math.round(total * ratio)))\n const tailChars = total - headChars\n const head = points.slice(0, headChars).join('')\n const tail = tailChars > 0 ? points.slice(-tailChars).join('') : ''\n const omitted = points.length - headChars - tailChars\n return `${head}\\n…[selector window: omitted ${omitted} chars]…\\n${tail}`\n}\n\n/** The configured selector output budget, with the design default as a fallback. */\nfunction selectorMaxTokens(deps: HookDeps): number {\n const raw = deps.config?.selector?.maxTokens\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {\n return DEFAULT_CONFIG.selector.maxTokens\n }\n return Math.floor(raw)\n}\n\n/** The route the selector call would inherit, or `undefined` when it cannot run. */\nfunction selectorRouteOf(deps: HookDeps, sessionId: string): SelectorRoute | undefined {\n try {\n const route = deps.selectorRoute?.(sessionId)\n if (\n route === undefined ||\n typeof route.provider !== 'string' ||\n typeof route.model !== 'string'\n ) {\n return undefined\n }\n return route\n } catch {\n return undefined\n }\n}\n\n/** Whether the selector is missing its LLM or its effective route. */\nfunction selectorSeamUnavailable(deps: HookDeps, ctx: DecisionContext): boolean {\n const llm = deps.llm\n return llm == null || typeof llm.stream !== 'function' || selectorRouteOf(deps, ctx.sessionId) === undefined\n}\n\n/**\n * The selector's fast upper bound: its output cap plus the estimated input.\n *\n * `maxTokens` bounds only the output; everything the request sends is input:\n * the system prompt, the user template, the candidate list and the receipt.\n * Charging only the receipt and the candidates under-counts the call by the\n * prompt (about 60–70 tokens) and makes admission optimistic exactly where it\n * decides whether to call. The priced string is built with the selector's own\n * exported template, so the estimate cannot drift from the request (row 36).\n * `undefined` means the caller cannot price the call; it must not guess.\n */\nfunction selectorChargeOf(\n deps: HookDeps,\n candidates: readonly Candidate[],\n receiptText: string,\n): number | undefined {\n const estimate = deps.estimateText\n if (typeof estimate !== 'function') return undefined\n const prompt = selectorPromptText({\n candidates: candidates.map((candidate) => ({\n id: candidate.id,\n summary: selectorSummary(candidate),\n })),\n receiptText,\n })\n const input = safeEstimate(estimate, `${SELECTOR_SYSTEM_PROMPT}\\n${prompt}`)\n if (input === undefined || input < 0) return undefined\n return selectorMaxTokens(deps) + input\n}\n\n/**\n * Ask the selector to pick one of `decision.candidates` and return that same\n * decision candidate, whose `args` are already bound.\n *\n * Never throws and never guesses. A missing LLM seam, a missing route, an\n * abstention or a thrown call all leave the plan untouched and write one\n * `skip` receipt explaining why; the next post-execute may try again. The\n * `SELECTOR_PURPOSE` marker is set by `choose` itself, so the frozen stream\n * hook can recognize and pass the aux request through.\n */\nasync function chooseCandidate(\n deps: HookDeps,\n ctx: DecisionContext,\n candidates: readonly Candidate[],\n receiptText: string,\n): Promise<Candidate | undefined> {\n const llm = deps.llm\n if (llm == null || typeof llm.stream !== 'function') {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return undefined\n }\n\n let route: SelectorRoute | undefined\n try {\n route = deps.selectorRoute?.(ctx.sessionId)\n } catch {\n route = undefined\n }\n if (\n route === undefined ||\n typeof route.provider !== 'string' ||\n typeof route.model !== 'string'\n ) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return undefined\n }\n\n try {\n const result = await choose({\n llm,\n provider: route.provider,\n model: route.model,\n ...(typeof route.reasoningEffort === 'string'\n ? { reasoningEffort: route.reasoningEffort }\n : {}),\n candidates: candidates.map((candidate) => ({\n id: candidate.id,\n summary: selectorSummary(candidate),\n })),\n receiptText,\n maxTokens: deps.config.selector.maxTokens,\n })\n if ('choice' in result) {\n // `candidates` are the decision's copies: their args are the bound tree.\n return candidates.find((candidate) => candidate.id === result.choice)\n }\n // §5.2-3 distinguishes a timeout/no-label abstention from a failed call:\n // `choose` maps its own dispatch failure to `abstain: 'error'`, and that is\n // the `selector-error` branch, not a second abstention reason.\n const code = result.abstain === 'error' ? 'selector-error' : 'selector-abstain'\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', code, { stepId: 'root', reason: result.abstain }),\n )\n return undefined\n } catch {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'selector-error', { stepId: 'root', reason: 'error' }),\n )\n return undefined\n }\n}\n\n// ---------------------------------------------------------------------------\n// Row 7: the step's admitted tool set\n// ---------------------------------------------------------------------------\n\n/**\n * Read this step's admission predicate, or `undefined` when it cannot be\n * verified.\n *\n * `view(scope)` takes the exact requesting agent; the host admits no other\n * scope. A missing `toolSet`, a missing `view` and a throwing `view` are all\n * \"no evidence\" and take the documented `no-toolset` path: the substitution\n * proceeds and records that it ran without admission evidence. Refusing on\n * absence would silently disable the feature on paths we cannot enumerate,\n * while a real model step always carries one (row 7).\n */\nfunction admissionViewOf(exec: PostExecuteExec | undefined): ((tool: string) => boolean) | undefined {\n const toolSet = exec?.toolSet\n if (toolSet == null || typeof toolSet.view !== 'function') return undefined\n try {\n const view = toolSet.view(exec?.agent)\n if (view == null || typeof view.has !== 'function') return undefined\n return (tool: string) => view.has(tool) === true\n } catch {\n return undefined\n }\n}\n\n/**\n * The substitution decision and its side effects.\n *\n * The fixed order is the plan's: existence of a plan and a receipt first, then\n * `worthSubstituting`, then `budget.take()`. The step's admission filter\n * (row 7) runs inside `decide`, before the selector is priced and before the\n * budget is taken; when its evidence is unavailable the commit still happens\n * and a `substitute-skipped:no-toolset` line records that it did.\n * Nothing below spends budget on a decision that will not be dispatched.\n *\n * `ask-selector` is fulfilled here since Task 23c-2: the decision carries only\n * already-bound candidates, so the selector's choice is committed from\n * `decision.candidates[].args` — never from `plan.steps[i].args`, which still\n * holds `$public` templates. The selector call is the plugin's own aux request\n * (`purpose: 'boost-selector'`), so the frozen stream hook passes it through.\n * A missing route or a missing LLM is a record-only abstention, never a guess.\n * `fallback` records the decision code and leaves the pending entry alone: this\n * invocation has enqueued nothing, so any entry it finds belongs to another\n * call, and clearing it would cancel a live substitution in a multi-call step.\n * A plan is **one-shot per receipt**: the first post-execute that reads it\n * removes it from the session map, whatever the outcome (commit, guard\n * failure, selector abstention, no candidate). The protocol says a block\n * describes the next call and may be omitted when unsure; retaining it would\n * let a plan the model has withdrawn fire against a much later receipt. The\n * remaining candidates are not reused either; the model writes a fresh block\n * for the next call (and may still reference an earlier receipt by id).\n *\n * A shadow commit parks nothing, but projection is independent of the shadow\n * flag (design §5.2-5) and still runs in `applyDecision`.\n */\nasync function decideSubstitution(\n deps: HookDeps,\n ctx: DecisionContext,\n): Promise<void> {\n // Fail-closed gate (design §5.2-3): a store that cannot record evidence\n // cannot justify spending a selector call or a budget step. No receipt is\n // attempted here either; the store is already failing, and status exposes\n // `receipts.stopped()` to the operator.\n //\n // The plan is still consumed here. This receipt cannot use it, and a plan is\n // one-shot per receipt: keeping it for a later receipt is exactly the stale\n // plan the one-shot rule exists to prevent. A store that recovers mid-turn\n // would otherwise let the next receipt fire a decision the model wrote for\n // this one.\n if (receiptsStopped(deps)) {\n clearPlan(deps, ctx.sessionId)\n return\n }\n\n const plan = safePlan(deps, ctx.sessionId)\n if (plan === undefined) return\n // One-shot: capture the plan for this pass, then drop it before any branch can\n // return, so no later receipt can reuse it.\n clearPlan(deps, ctx.sessionId)\n\n // Design §9: no token meter means no substitution. The meter is what prices\n // `worthSubstituting` and the selector's input, so running without it would\n // spend real money on a fabricated estimate. Refuse before `decide`, before\n // the selector and before admission; shadow mode is record-only and may\n // still run. Projection is not gated (it needs no token numbers to clip).\n const estimator = estimatorOf(deps)\n if (\n !ctx.doc.shadow &&\n (estimator === undefined || safeEstimate(estimator, 'dsh-boost meter probe') === undefined)\n ) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'ERR_HOST_NO_TOKENMETER', {\n stepId: 'root',\n reason: 'no-token-meter',\n }),\n )\n return\n }\n\n // Row 7: this step's `ResolvedToolSet` is the host's admission set, so\n // `decide` drops a candidate whose tool it does not admit before the selector\n // or the budget is touched. Shadow mode is record-only and measures potential\n // across the whole whitelist, so it passes no admission filter.\n const admission = ctx.doc.shadow ? undefined : admissionViewOf(ctx.exec)\n const noToolset = !ctx.doc.shadow && admission === undefined\n\n let decision: ReturnType<typeof decide>\n try {\n decision = decide({\n plan,\n stepId: 'root',\n receipts: ctx.state.receiptsFor(ctx.sessionId, ctx.turn),\n whitelist: SUBSTITUTION_WHITELIST,\n shadow: ctx.doc.shadow,\n ...(admission === undefined ? {} : { admitted: admission }),\n })\n } catch {\n return\n }\n\n // Substitution synthesises a dispatch and expects POSIX process semantics;\n // on Windows it is refused **before** the selector, admission and budget, so\n // the path cannot spend anything to decline. Shadow mode is record-only and\n // stays available: it changes nothing the model sees. The stable operator\n // signal is `boost status`'s `ERR_HOST_PLATFORM_UNSUPPORTED`; this receipt\n // keeps the refusal auditable per call rather than silently doing less.\n if (!isPosixOnly() && !ctx.doc.shadow) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', {\n stepId: 'root',\n reason: 'platform-unsupported',\n }),\n )\n return\n }\n\n let candidate: Candidate | undefined\n let boundArgs: Record<string, unknown> | undefined\n let candidateId: string | undefined\n\n // A selector call pays its output cap plus the input actually sent. A single\n // surviving candidate pays no selector at all. This must run before `choose`:\n // a selector call that cannot be paid for is never sent.\n let selectorOverhead = 0\n let selectorReceiptText = ''\n if (decision.kind === 'ask-selector') {\n // Row 2: the budget is checked before the selector is paid for. Without\n // this, an exhausted step would still send a real model request and then\n // record `steps-exhausted` after the money was spent. Shadow mode is\n // record-only and takes no step, so it keeps measuring.\n if (!ctx.doc.shadow && budgetExhausted(deps, ctx.sessionId)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }))\n return\n }\n // Availability is checked before pricing: a missing LLM/route is the\n // `selector-unavailable` degradation, not an admission decision.\n if (selectorSeamUnavailable(deps, ctx)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }))\n return\n }\n selectorReceiptText = selectorReceiptOf(deps, ctx)\n const charge = selectorChargeOf(deps, decision.candidates, selectorReceiptText)\n if (charge === undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root', reason: 'no-estimator' }),\n )\n return\n }\n selectorOverhead = charge\n if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }))\n return\n }\n // The decision's candidates already carry the bound trees; committing from\n // the plan here would dispatch a `$public` template.\n const chosen = await chooseCandidate(deps, ctx, decision.candidates, selectorReceiptText)\n if (chosen === undefined) return\n candidate = chosen\n boundArgs = chosen.args\n candidateId = chosen.id\n } else if (decision.kind === 'fallback') {\n // This invocation enqueued nothing, so any pending entry belongs to another\n // call in the step; cancelling it would leave the budget spent and usage\n // marked for a substitution that never runs (review F2).\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', decision.code, { stepId: 'root' }))\n return\n } else {\n candidate = plan.steps.find((step) => step.id === decision.candidateId)\n boundArgs = decision.args\n candidateId = decision.candidateId\n }\n\n if (candidate === undefined || boundArgs === undefined || candidateId === undefined) {\n // decide only commits its own plan's ids; this is containment, not a path.\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'no-candidate', { stepId: 'root' }))\n return\n }\n\n // The live visibility check runs for the shadow path too: the record-only\n // measurement must describe the same population the real admission would\n // consider, not a broader one (review F2). The cached judgement passed above,\n // but the document may have changed while the session ran.\n if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'skip:no-scope', { stepId: 'root' }))\n return\n }\n\n if (ctx.doc.shadow) {\n // Record-only: the same `shadow` flag was passed to `decide` above, so the\n // recorded potential matches the policy that produced it. No queue entry\n // and no budget. Projection is a separate switch and still runs afterwards\n // (design §5.2-5); this branch only stops the substitution side.\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'shadow', 'ok', {\n decision: 'commit',\n candidateId,\n // The executed tool is the model's call; the candidate's tool is what\n // the gate decided. The shadow report's per-family hit rate must use\n // the latter (the shadow receipt's `tool` is the former).\n candidateTool: candidate.tool,\n admitted: admittedFor(deps, ctx.sessionId, plan, selectorOverhead),\n whitelisted: SUBSTITUTION_WHITELIST.has(candidate.tool),\n stepId: 'root',\n args: boundArgs,\n // G2: the plan and the guards are why this candidate was legitimate.\n ...substitutionEvidence(plan.goal, candidate.guards),\n }),\n )\n return\n }\n\n const step = clockStepOf(deps, ctx.sessionId)\n if (step === undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-step' }),\n )\n return\n }\n if (deps.queue == null || typeof deps.queue.set !== 'function') {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-queue' }),\n )\n return\n }\n\n if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }))\n return\n }\n\n if (!takeBudget(deps, ctx.sessionId)) {\n // No entry is ours to clear here: this invocation enqueued nothing, so a\n // live entry belongs to another call in the step (review F2).\n await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }))\n return\n }\n\n const callId = callIdFor(ctx.sessionId, ctx.turn, step, candidateId)\n const entry: AuditedPendingEntry = {\n callId,\n candidateId,\n // The candidate's tool name identifies the call; the executable args are\n // the *decision's* bound tree, never the plan's `$public` template.\n name: candidate.tool,\n args: boundArgs,\n turn: ctx.turn,\n step,\n // The plan is one-shot (cleared above), so the evidence must travel with\n // the entry: the synth-time receipt is written after this turn's plan is\n // gone, and the settled receipt only knows the candidate id.\n evidence: substitutionEvidence(plan.goal, candidate.guards),\n }\n try {\n deps.queue.set(ctx.sessionId, entry)\n } catch {\n await appendReceipt(\n deps,\n // The step was already taken and this receipt is the only evidence that\n // it bought no substitution; a throwing queue must not also hide the cost.\n ledgerEntry(ctx, 'skip', 'substitution-unavailable', {\n stepId: 'root',\n reason: 'queue-failed',\n budget: 'spent',\n }),\n )\n return\n }\n\n // Row 7: the commit is real but the admission evidence was not available.\n // Recording it here (not at the missing-evidence point above) means the note\n // names the candidate that actually committed and only exists when one did.\n if (noToolset) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', 'substitute-skipped:no-toolset', {\n stepId: 'root',\n candidateId,\n }),\n )\n }\n\n markSubstituted(deps, ctx.sessionId, candidateId)\n // Anchors name the templates the executed call was bound from: the decision's\n // args are already expanded, so only the plan copy still carries the\n // `$public` references. That tree is inspected here, never dispatched.\n setAnchors(deps, ctx, plan.steps.find((step) => step.id === candidateId)?.args ?? boundArgs)\n return\n}\n\n/** The session's plan, or `undefined` when none is known (or the map is foreign). */\nfunction safePlan(deps: HookDeps, sessionId: string): Plan | undefined {\n try {\n const plans = deps.plans\n if (plans == null || typeof plans.get !== 'function') return undefined\n const plan = plans.get(sessionId)\n if (plan === undefined || plan === null) return undefined\n // A spent plan has nothing left to decide; skipping the call also avoids a\n // `guard-trivial` receipt on every later tool call of the turn.\n if (!Array.isArray(plan.steps) || plan.steps.length === 0) return undefined\n return plan\n } catch {\n return undefined\n }\n}\n\n// ---------------------------------------------------------------------------\n// Projection\n// ---------------------------------------------------------------------------\n\n/** The text projection may replace, or `undefined` when it must stay intact. */\nfunction projectionTargetOf(\n decision: PostExecuteDecision,\n receipt: CanonicalReceipt,\n result: PostExecuteResult | undefined,\n): string | undefined {\n // A `value` replacement cannot be combined with `content`: the host throws a\n // TypeError for both, which would replace the tool result with an error.\n if (Object.hasOwn(decision, 'value')) return undefined\n if (decision.kind !== 'accept') return undefined\n\n if (Object.hasOwn(decision, 'content')) {\n const content = decision.content\n if (!Array.isArray(content)) return undefined\n // Replacing a multi-block result with one text block is only lossless when\n // every block is text; an image or file block must stay where it is.\n if (!content.every((block) => textBlock(block))) return undefined\n return canonicalise(content as ReadonlyArray<{ type: string; text?: string }>, false).text\n }\n\n const content = result?.content\n if (content !== undefined && !(Array.isArray(content) && content.every((block) => textBlock(block)))) {\n return undefined\n }\n return receipt.text\n}\n\n/** Whether a block is a text block this hook can fold into one string. */\nfunction textBlock(block: unknown): boolean {\n return typeof block === 'object' && block !== null && (block as { type?: unknown }).type === 'text'\n}\n\n/** The estimator, or `undefined` when none is wired (projection then stays off). */\nfunction estimatorOf(deps: HookDeps): ((t: string) => number) | undefined {\n const estimate = deps.estimateText\n return typeof estimate === 'function' ? estimate : undefined\n}\n\n/** One estimate, sanitised: a non-finite or throwing result means \"cannot price\". */\nfunction safeEstimate(estimate: (t: string) => number, text: string): number | undefined {\n try {\n const value = estimate(text)\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The replay horizon in effect for one projection decision, pinned on its receipt.\n *\n * `status` applies `(1 + horizon)` to every projection's saving. Reading one\n * current horizon at status time re-valued receipts from other sessions and\n * other moments whenever the cross-session minimum moved, so a historical net\n * saving jumped when an unrelated session started or ended. The receipt now\n * carries the horizon its decision was made under; `status` only falls back to\n * the current horizon for receipts that predate the field, and says how many\n * those were.\n *\n * The runtime horizon is design §5.3's `min(config, mean of the session's last\n * historyTurns turns)`. Its instance lives in `src/index.ts` (`apply` builds\n * one `RuntimeStepHorizon`), so the decision path can only read it through\n * {@link HookDeps.horizonFor}; until that one line is wired, the resolved\n * config's `horizonSteps` is the value in effect. A throwing or malformed\n * answer falls back the same way, never to a fabricated number.\n */\nfunction projectionHorizonOf(deps: HookDeps, sessionId: string): number {\n try {\n const live = deps.horizonFor?.(sessionId)\n if (typeof live === 'number' && Number.isFinite(live) && live >= 0) return Math.floor(live)\n } catch {\n // A foreign horizon is evidence, never a reason to lose the receipt.\n }\n const raw = deps.config?.horizonSteps\n return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0\n ? Math.floor(raw)\n : DEFAULT_CONFIG.horizonSteps\n}\n\n/** `projection-skipped:<reason>`; `projectApply` already prefixes one reason. */\nfunction projectionSkipCode(reason: string): string {\n return reason.startsWith('projection-skipped:') ? reason : `projection-skipped:${reason}`\n}\n\n/**\n * Project the receipt that will enter history.\n *\n * Shadow mode only prices the receipt: it writes a `{kind:'shadow'}` record and\n * returns the decision untouched, so nothing the model sees changes. Apply mode\n * persists the canonical original through the host spill backend and replaces\n * the content only after `projectApply`'s own guards pass; a skip leaves the\n * decision intact. The regression guard (`assembled.length < original.length`)\n * lives inside `projectApply`; here only pricing and evidence are added.\n *\n * The live visibility recheck runs before either mode. The listener gate reads\n * the cached judgement from prompt assembly time; a workspace disabled since\n * then must not have its receipt clipped or accounted, in shadow or apply mode.\n */\nasync function projectDecision(\n deps: HookDeps,\n receipt: CanonicalReceipt,\n decision: PostExecuteDecision,\n ctx: DecisionContext,\n): Promise<PostExecuteDecision> {\n const mode: ProjectionMode = ctx.doc.projection\n if (mode === 'off') return decision\n\n // Projection gets the same live recheck substitution performs. The cached\n // judgement passed the listener gate, but the prompt was assembled before\n // the tool ran: `boost` may have disabled the workspace in between, and a\n // projection changes what the model sees. The cache alone must not authorize\n // that (design §5.5).\n if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) return decision\n\n const toolName = ctx.exec.name\n const family = toolName === undefined ? undefined : familyOf(toolName)\n if (family === undefined) {\n // `edit`, `web_fetch`, `todo_write`, `boost` and friends are by-design\n // passes, not mapper gaps. Only a decorated (`mcp__*`) name means the\n // mapper may have missed a real family, so only that is counted.\n if (typeof toolName === 'string' && toolName.startsWith('mcp__')) {\n try {\n deps.projectionCounters?.unknownFamily(toolName)\n } catch {\n // A counter is evidence, never a precondition.\n }\n }\n return decision\n }\n const target = projectionTargetOf(decision, receipt, ctx.result)\n if (target === undefined) return decision\n\n // Clipping does not need a token meter; only its accounting does (design\n // §9). With no estimator the replacement still happens, but the receipts\n // carry `estimate:'unknown'` and no fabricated numbers.\n const estimate = estimatorOf(deps)\n\n try {\n if (mode === 'shadow') {\n const outcome = await projectShadow({\n text: target,\n isError: receipt.isError,\n family,\n cfg: deps.config,\n // Same sanitiser as the apply path: a throwing or non-finite host\n // estimate must never become `null` in the shadow account. Without a\n // meter the NaN makes `projectShadow` record an unpriced event.\n estimate: (text) =>\n estimate === undefined ? Number.NaN : (safeEstimate(estimate, text) ?? Number.NaN),\n })\n if (outcome.kind === 'shadow') {\n const priced =\n outcome.before !== undefined &&\n outcome.after !== undefined &&\n outcome.saved !== undefined\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'shadow', 'projection-shadow', {\n decision: 'projection',\n unit: 'raw',\n // The shadow ledger's one-time figure is replayable with the same\n // horizon as the applied one; pinning it keeps the two comparable.\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n ...(priced\n ? {\n before: outcome.before,\n after: outcome.after,\n saved_projection_tokens: outcome.saved,\n }\n : {}),\n estimate: priced ? (deps.estimateKind ?? 'unknown') : 'unknown',\n }),\n )\n }\n return decision\n }\n\n const { content, outcome } = await projectApply({\n text: target,\n isError: receipt.isError,\n family,\n cfg: deps.config,\n sessionId: ctx.sessionId,\n toolName: ctx.exec.name ?? 'tool',\n callId: typeof ctx.exec.callId === 'string' ? ctx.exec.callId : undefined,\n label: family,\n spill: deps.spill,\n formatFooter: await resolveFooterFormatter(deps),\n })\n\n if (outcome.kind === 'applied') {\n // Remember the artifact's only address: this is what makes a later read\n // of it a counted retrieval instead of a free one (design §5.3).\n if (outcome.locator !== undefined) deps.retrievals?.record(ctx.sessionId, outcome.locator)\n\n // The applied event is always recorded; only the token figures depend on\n // the meter. `estimate` is always present and names the producer\n // (`deps.estimateKind`, defaulting to `'unknown'`), never a guess.\n // One-time `before`/`after`/`saved_projection_tokens` are the\n // authoritative names (§5.3); `status` applies the replay factor once to\n // the aggregate, never per receipt. `horizon_steps` is the horizon this\n // decision was made under, so a later status cannot re-value it.\n const before = estimate === undefined ? undefined : safeEstimate(estimate, target)\n const after = estimate === undefined ? undefined : safeEstimate(estimate, content)\n if (before !== undefined && after !== undefined) {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'projection', 'projected', {\n unit: 'raw',\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n before,\n after,\n saved_projection_tokens: before - after,\n estimate: deps.estimateKind ?? 'unknown',\n }),\n )\n } else {\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'projection', 'projected', {\n unit: 'raw',\n horizon_steps: projectionHorizonOf(deps, ctx.sessionId),\n ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),\n estimate: 'unknown',\n }),\n )\n }\n return { ...decision, content: [{ type: 'text', text: content }] }\n }\n\n if (\n outcome.kind === 'skipped' &&\n outcome.reason !== undefined &&\n PROJECTION_DEGRADATIONS.has(outcome.reason)\n ) {\n // `projection-skipped:no-spill` is the receipt behind\n // `boost status`'s `ERR_HOST_NO_SPILL`; the other degradation codes\n // exist for the same audit trail. Ordinary \"not worth it\" skips are\n // deterministic policy, not a per-call decision (design §5.3), so they\n // write nothing.\n // A skip projected nothing, so it is a `skip` receipt, not a\n // `projection` one. `kind:'projection'` is not a promise of numeric\n // fields: the meterless apply branch above always writes\n // `estimate:'unknown'` but omits `before`/`after`/\n // `saved_projection_tokens` entirely (design §9), and consumers must\n // treat those as unpriced rather than assume the numbers exist.\n await appendReceipt(\n deps,\n ledgerEntry(ctx, 'skip', projectionSkipCode(outcome.reason)),\n )\n }\n return decision\n } catch {\n // `projectApply`/`projectShadow` already contain their own host calls; this\n // is the last belt for a bug in either of them.\n return decision\n }\n}\n\n/**\n * The decision + projection stage.\n *\n * Both seams live in one place so the listener's order is visible in one\n * function: decide, then the double-projection guard, then project. A shadow\n * substitution does not stop the projection: the two switches are independent\n * (design §5.2-5), and in projection-shadow mode the projection writes only\n * its accounting line.\n */\nasync function applyDecision(\n deps: HookDeps,\n decision: PostExecuteDecision,\n ctx: DecisionContext,\n): Promise<PostExecuteDecision> {\n // Projection below runs for a shadow commit too: the decision side never\n // suppresses the projection ledger.\n await decideSubstitution(deps, ctx)\n\n // Second-projection guard. Two host shapers are outer to this listener:\n //\n // - The spill policy registers with `{ prepend: true }`: it calls `next()`\n // and adds its footer to *that* decision after this listener returns. So\n // this check sees only a footer an inner listener already wrote, never the\n // host's own; it must not be read as full double-spill detection.\n // - For `glob`/`grep`, `@deepseek-ai/dsh-tool-fs-search` is outer too\n // (`dsh-base` loads it first) and would replace an over-cap result with its\n // own spill-backed preview. The plugin pre-empts it **deliberately**:\n // `acceptedDirectCallValue` does nothing as soon as the decision carries\n // `content` (`dsh-tool-fs-search/lib/index.js:490-493`), so the projection\n // accept below wins and the host preview never runs. That is the intended\n // trade for these two families: the plugin's window triggers at 700\n // characters, far below the host's 100-path / 250-match caps, and its own\n // footer keeps the spill locator, so the host preview has nothing to add\n // to a receipt this listener already clipped. A family the plugin does not\n // project leaves the host shaper untouched.\n //\n // Both the receiver as it arrived and the decision that will enter history\n // are checked (design §5.4).\n if (await isAlreadySpilled(deps, ctx.receipt.text)) return decision\n const downstreamText = decisionTextOf(decision) ?? ctx.receipt.text\n if (downstreamText !== ctx.receipt.text && await isAlreadySpilled(deps, downstreamText)) {\n return decision\n }\n return projectDecision(deps, ctx.receipt, decision, ctx)\n}\n\n// ---------------------------------------------------------------------------\n// The two listeners\n// ---------------------------------------------------------------------------\n\n/**\n * The `tools/post-execute` body.\n *\n * `next()` runs first, exactly like the host's own spill policy: a listener\n * either returns a decision or calls `next()` and returns its result, and\n * bypassing it would silently drop the listeners mounted after this one. The\n * fixed order that follows is `scope gate → canonicalise → invalidate →\n * substitution decision → double-projection guard → projection → return the\n * decision` (design §5.2-7/§5.4-5).\n *\n * Everything after `next()` is contained: the host turns a throwing\n * `post-execute` listener into an error result and the real tool output is\n * lost. A failure in our own wiring must therefore return the decision as it\n * arrived, never a thrown error.\n */\nasync function postExecute(\n deps: HookDeps,\n state: ReceiptSessionState,\n exec: PostExecuteExec | undefined,\n result: PostExecuteResult | undefined,\n next: () => Promise<PostExecuteDecision>,\n): Promise<PostExecuteDecision> {\n const decision = await next()\n\n // The host cancels a call by aborting `exec.signal`; an async listener must\n // observe it before doing work whose result the model will never receive.\n // `next()` still runs — the waterfall must not drop the listeners mounted\n // after this one, and the host only replaces a successful accepted outcome\n // after they settle — but nothing after it does.\n if (cancelled(exec)) return decision\n\n // A PTC inner call traverses this waterfall with `parent` set. Its result\n // belongs to the enclosing `run_code` step, not to a step of its own: it must\n // not become `root`, drive a decision, consume the outer plan or overwrite the\n // outer anchors. Leaving it untouched is what keeps a plan from being decided\n // from an inner receipt.\n if (exec !== undefined && exec.parent !== undefined) return decision\n\n if (exec?.agent === undefined) {\n await appendSkipNoScope(deps.receipts, exec)\n return decision\n }\n\n // Exposure gate: an out-of-scope session pays nothing. This is the same\n // cached judgement the protocol section reads; a miss is false (fail-closed,\n // design §5.5).\n const sessionId = sessionIdOf(exec)\n if (sessionId === undefined) {\n // The agent exists but carries no usable session id, so neither the scope\n // gate nor the retrieval ledger can attribute this call. Fail closed and\n // keep the pass visible; the no-agent branch above does the same.\n await appendSkipNoScope(deps.receipts, exec)\n return decision\n }\n\n // The mirrored dispatch is only meaningful while its usage mark is pending.\n // Once the mark is gone (settled by the next real request, or discarded), the\n // record is stale and a later turn's mark could reuse the candidate id.\n if (pendingCandidateOf(deps, sessionId) === undefined) clearAcceptedDispatch(deps, sessionId)\n\n // A substituted call denied by `tools/pre-execute` (approval or sandbox)\n // returns a post-result without invoking `tools/execute`, while post-execute\n // still runs. Matching the call id here clears the pending entry even though\n // no dispatch mapping exists, so the substitution is not re-synthesized on\n // every later step of the turn.\n clearMatchingPending(deps, sessionId, exec)\n\n // Detect the retrieval before the visibility gate (a projected receipt\n // already consumed context regardless of today's scope), but write its cost\n // only after projection, when the final visible content is known (review I3).\n const retrieval = pendingRetrievalOf(deps, exec, sessionId)\n\n if (!isActiveSession(deps, sessionId)) {\n if (retrieval !== undefined) {\n const arrival = canonicalise(result?.content ?? [], result?.isError === true)\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, arrival.text)\n }\n await appendSkipNoScope(deps.receipts, exec, sessionId, clockTurnOf(deps, sessionId) ?? 0)\n return decision\n }\n\n try {\n // Canonicalise the original receiver, not a downstream replacement: guards\n // and the selector read the receipt as it arrived.\n const receipt = canonicalise(result?.content ?? [], result?.isError === true)\n const turn = clockTurnOf(deps, sessionId) ?? 0\n\n // The receipt map is the gate's memory for this turn. `begin` folds the\n // previous turn away (anchors live in the store, receipts and in-flight\n // dispatches here), then the arriving receipt becomes `root` and, if it is\n // the call we substituted, also becomes the candidate's receipt.\n const { rolledOver } = state.begin(sessionId, turn)\n if (rolledOver) {\n // A pending entry and its decision-time usage mark from the previous turn\n // can never match a call in this one, so both are dead weight; the reset\n // path does the same mid-turn (F2). The mark is settled **without** a\n // settlement receipt when no substitution ran, exactly like\n // `resetInvalidatedPending` and `applyAbandon`. This branch is reachable\n // with a live mark because a parallel tool result can land after the host\n // advanced the turn but before this turn's first `llm/stream`, so the old\n // \"the stream always runs first\" argument does not hold (D1). When the\n // synthesized dispatch *was* accepted, the skipped model round is real:\n // `settleRollover` reports it with the sample the ledger has (row 28).\n await settleRollover(deps, sessionId, turn)\n clearAnchors(deps, sessionId)\n clearPending(deps, sessionId)\n // The plan map is normally reconciled by `SessionRuntime.notePlanTurn` on\n // the first real request of a turn. If that request has not run yet, a\n // plan still in the map belongs to the previous turn and would fire\n // against this new-turn receipt; drop it. When the request did run,\n // `notePlanTurn` reports false and the plan present was parsed by that\n // request's response: keep it, because clearing would discard a valid\n // new-turn plan.\n let planForThisTurn = false\n try {\n planForThisTurn = deps.sessions?.notePlanTurn(sessionId, turn) === false\n } catch {\n planForThisTurn = false\n }\n if (!planForThisTurn) clearPlan(deps, sessionId)\n }\n state.recordRoot(sessionId, turn, receipt)\n fileDispatchedReceipt(state, exec, sessionId, turn, receipt)\n\n // Conservative local invalidation check. The tool-result path cannot see\n // the host pruner (it rewrites session surface nodes, not this waterfall)\n // or compaction, so only the **marker** branch is meaningful here: it\n // catches a receipt whose tool output itself carries the pruner literal.\n // The anchor comparison needs the anchored receipt's current text and\n // belongs to the model-request path (23c); running it here would compare a\n // different call's text and fire a false compaction-reset after every\n // commit (review F1). A hit only abandons the decision, which is safe.\n const pending = pendingAnchorsOf(deps, sessionId)\n // `!= null` rather than `!== undefined`: a foreign store can hand back a\n // null, and dereferencing it would throw out of the hook.\n if (pending != null) {\n const reset = markerResetOf(pending, receipt.text)\n if (reset !== undefined) {\n await resetInvalidatedPending(deps, exec, sessionId, turn, pending, reset)\n if (retrieval !== undefined) {\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, receipt.text)\n }\n return decision\n }\n }\n\n const ctx: DecisionContext = {\n sessionId,\n exec,\n receipt,\n doc: await scopeDocOf(deps),\n result,\n state,\n turn,\n retrievalCall: retrieval !== undefined,\n }\n const outgoing = await applyDecision(deps, decision, ctx)\n if (retrieval !== undefined) {\n // The retrieval receipt's content figure must price what enters history\n // after projection, not the raw result it arrived with.\n const visible = decisionTextOf(outgoing) ?? receipt.text\n await recordProjectionRetrieval(deps, exec, sessionId, retrieval, visible)\n }\n return outgoing\n } catch {\n // Never lose the tool's real output to a wiring bug in this listener.\n return decision\n }\n}\n\n/**\n * Drop a pending entry whose call id matches the arriving result.\n *\n * The execute hook clears the entry when it inspects an accepted or rejected\n * dispatch, but a call denied by `tools/pre-execute` never reaches that hook;\n * post-execute is then the only observer that knows the substituted call is\n * over. A different call id is an ordinary call and leaves the entry alone.\n */\nfunction clearMatchingPending(\n deps: HookDeps,\n sessionId: string,\n exec: PostExecuteExec,\n): void {\n const pending = peekPending(deps, sessionId)\n if (pending === undefined) return\n if (typeof exec.callId !== 'string' || exec.callId !== pending.callId) return\n clearPending(deps, sessionId)\n}\n\n/** File an executed candidate's receipt under its plan id, consuming the dispatch record. */\nfunction fileDispatchedReceipt(\n state: ReceiptSessionState,\n exec: PostExecuteExec | undefined,\n sessionId: string,\n turn: number,\n receipt: CanonicalReceipt,\n): void {\n const callId = exec?.callId\n if (typeof callId !== 'string') return\n const candidateId = state.takeDispatch(sessionId, turn, callId)\n if (candidateId === undefined) return\n state.recordCandidate(sessionId, turn, candidateId, receipt)\n}\n\n/** The host's `ToolExecutionResult` failure branch for a refused dispatch. */\nfunction dispatchFailure(message: string): unknown {\n return {\n isError: true,\n error: {\n message,\n info: { name: 'DispatchRejectedError', code: 'dispatch-rejected' },\n },\n content: [{ type: 'text', text: `Error: ${message}` }],\n }\n}\n\n/** Record one refused dispatch; a receipt write never changes the verdict. */\nasync function appendDispatchRejected(\n deps: HookDeps,\n exec: DispatchExec,\n entry: PendingEntry,\n sessionId: string,\n): Promise<void> {\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: clockTurnOf(deps, sessionId) ?? 0,\n stepId: 'root',\n kind: 'skip',\n code: 'dispatch-rejected',\n tool: exec.name,\n callId: typeof exec.callId === 'string' ? exec.callId : undefined,\n candidateId: entry.candidateId,\n // The refused call's own args, not the pending decision's: the operator\n // needs to see exactly what the host was asked to run.\n args: exec.arguments,\n preview: callPreview(exec.name, exec.arguments),\n })\n}\n\n/**\n * The inspect half of `tools/execute`: no `next()` is called here, so a throw\n * can never cause the dispatch to run twice.\n *\n * Every operation is contained (the lookup, the clearing, the receipt write),\n * so the only throw this function can produce is a bug of its own; the caller\n * then fails open.\n */\nasync function inspectDispatch(\n deps: HookDeps,\n exec: DispatchExec,\n): Promise<\n | { kind: 'next' }\n | { kind: 'reject'; message: string }\n | {\n kind: 'accept'\n sessionId: string\n callId: string\n candidateId: string\n /** The plan/guard evidence the entry carried; mirrored for a rollover settle. */\n evidence: SubstitutionEvidence | undefined\n }\n> {\n // Row 30: a PTC inner call carries `parent` and belongs to the enclosing\n // `run_code` step. Its host-assigned call id is not the root decision's, so\n // even a collision must not be read as our dispatch.\n if (exec.parent !== undefined) return { kind: 'next' }\n\n const sessionId = sessionIdOf(exec)\n if (sessionId === undefined) return { kind: 'next' }\n\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'next' }\n\n const reject = async (message: string) => {\n clearPending(deps, sessionId)\n await appendDispatchRejected(deps, exec, entry, sessionId)\n return { kind: 'reject' as const, message }\n }\n\n // A different call id is an ordinary call, not tampering: the host assigns\n // call ids, so only a call that carries the id we chose is the dispatch under\n // inspection. Rejecting the rest would lose a legitimate tool's output (F2).\n if (typeof exec.callId !== 'string' || exec.callId !== entry.callId) {\n return { kind: 'next' }\n }\n // `rejectIfTampered` compares name and parsed arguments only; the call id was\n // compared above.\n if (rejectIfTampered(exec, entry).reject) {\n return reject(\n 'dsh-boost refused a substituted call: the dispatched arguments do not match the pending decision',\n )\n }\n\n // Accept path: the entry has done its job, so drop it before dispatching.\n clearPending(deps, sessionId)\n return {\n kind: 'accept',\n sessionId,\n callId: entry.callId,\n candidateId: entry.candidateId,\n evidence: (entry as AuditedPendingEntry).evidence,\n }\n}\n\n/**\n * The `tools/execute` hook body: refuse a tampered substitution.\n *\n * With no pending entry the plugin is not substituting this call, so `next()`\n * runs untouched. The entry describes the dispatch we synthesised: a call that\n * carries the **same** call id is inspected, compared with the decision, and\n * the entry is cleared on both the accept and the reject path so it cannot\n * outlive its dispatch. A call with a **different** call id is an ordinary call\n * — the host assigns ids — and passes through without touching the entry\n * (review F2: rejecting it would lose a legitimate tool's output). On the\n * accept path the call id is remembered so the following `post-execute` can\n * file the receipt under its candidate id.\n *\n * The mount fails open on an internal error (the design's fail-closed means\n * \"pass through, do not substitute\", never \"intercept\"): a broken queue must\n * not block every tool call in the process.\n */\nasync function executeHook(\n deps: HookDeps,\n state: ReceiptSessionState,\n exec: DispatchExec,\n next: () => Promise<unknown>,\n): Promise<unknown> {\n // Row 30: a PTC inner dispatch is the enclosing `run_code` step's business,\n // not this hook's; `next()` runs untouched so the inner tool still executes.\n if (exec?.parent !== undefined) return next()\n\n let outcome: Awaited<ReturnType<typeof inspectDispatch>>\n try {\n outcome = await inspectDispatch(deps, exec)\n } catch {\n return next()\n }\n\n if (outcome.kind === 'reject') return dispatchFailure(outcome.message)\n if (outcome.kind === 'accept') {\n const turn = clockTurnOf(deps, outcome.sessionId) ?? 0\n try {\n state.recordDispatch(outcome.sessionId, turn, outcome.callId, outcome.candidateId)\n } catch {\n // Losing the mapping costs the candidate receipt, not this call.\n }\n // The same fact, kept outside `ReceiptSessionState` because the candidate's\n // post-execute consumes that mapping before a rollover can look at it.\n noteAcceptedDispatch(\n deps,\n outcome.sessionId,\n turn,\n outcome.candidateId,\n outcome.evidence,\n )\n }\n return next()\n}\n\n// ---------------------------------------------------------------------------\n// Registration\n// ---------------------------------------------------------------------------\n\n/** Mount the projection waterfall. */\nfunction registerPostExecute(\n ctx: PluginContext,\n deps: HookDeps,\n state: ReceiptSessionState,\n): void {\n ctx.on('tools/post-execute', (exec, result, next) => postExecute(deps, state, exec, result, next))\n}\n\n/** Mount the model-request waterfall; the hook function is built once per registration. */\nfunction registerLlmStream(ctx: PluginContext, deps: HookDeps): void {\n const hook = streamHook(deps)\n ctx.on('llm/stream', (options, next) => hook(options, next))\n}\n\n/** Mount the dispatch waterfall. */\nfunction registerExecute(ctx: PluginContext, deps: HookDeps, state: ReceiptSessionState): void {\n ctx.on('tools/execute', (exec, next) => executeHook(deps, state, exec, next))\n}\n\n/** Mount the protocol section, whose provider stays synchronous and per-agent. */\nfunction registerProtocolSection(ctx: PluginContext, scope: ScopeStore | undefined): void {\n ctx.systemPrompt.section({\n name: PROTOCOL_NAME,\n order: PROTOCOL_ORDER,\n interpolate: false,\n text: (context) => protocolText(scope, context),\n })\n}\n\n/**\n * Register the plugin's four host integration points.\n *\n * The prompt section is registered first on purpose: it is the only mount that\n * rejects a duplicate name, so a second `apply` aborts here before any event\n * hook is mounted twice (the host turns a duplicate section into an error, and\n * `apply` treats that as \"already mounted\"). Registering it last would leave\n * three live duplicate listeners behind.\n *\n * One `ReceiptSessionState` belongs to the whole registration: the execute\n * mount writes the in-flight call mapping and the post-execute mount consumes\n * it, so the two waterfalls must share it.\n *\n * `scope`, `receipts`, `anchors` and `resolveSession` are required by\n * `HookDeps`, but they are still checked at the point of use: a host wiring the\n * plugin without one of the optional pieces still gets the four mount points,\n * and every degraded path is fail-closed instead of throwing during\n * registration.\n */\nexport function registerHooks(ctx: PluginContext, deps: HookDeps): void {\n const state = deps.sessionState ?? new ReceiptSessionState()\n // Publish the instance we created. `clearSession` and Task 23c-2's session-end\n // wiring reach the state through `deps.sessionState`; a caller that omits it\n // (the plan's 23c-2 assembly list does) would otherwise leave the created\n // receipt/dispatch maps unreachable and leaked per session.\n deps.sessionState = state\n // The logger is a host service the caller already has; publishing it here\n // keeps the degradation warnings reachable without widening every caller's\n // deps literal. A deps object that already names one keeps it.\n deps.logger ??= ctx.logger\n // Row 27: `llm/stream` records the synthesis through this seam, because the\n // mirror lives here and a denied dispatch never reaches `tools/execute`.\n deps.noteSynthesis ??= (sessionId, turn, candidateId, evidence) =>\n noteAcceptedDispatch(deps, sessionId, turn, candidateId, evidence)\n registerProtocolSection(ctx, deps.scope)\n registerPostExecute(ctx, deps, state)\n registerLlmStream(ctx, deps)\n registerExecute(ctx, deps, state)\n}\n"]}
|