dsh-boost 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +476 -0
  4. package/README.md +408 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +276 -0
  43. package/dist/hooks/llm-stream.js +1008 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +247 -0
  49. package/dist/hooks/post-execute.js +1776 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +18 -0
  64. package/dist/host/root.js +43 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +866 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +367 -0
  100. package/dist/tools/boost.js +768 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +113 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1,1776 @@
1
+ /**
2
+ * Host hook assembly: the four mount points the plugin owns, and the
3
+ * post-execute decision path that turns the gate into a working product.
4
+ *
5
+ * Registration stays split one function per mount so each body can be replaced
6
+ * without rewriting the mount:
7
+ *
8
+ * - `tools/post-execute` first gates on the same cached scope judgement the
9
+ * protocol section reads, then canonicalises the result and runs a
10
+ * conservative invalidation check. It files the arriving receipt under
11
+ * `'root'`, works the substitution decision (`decide` → admission → pending
12
+ * queue / shadow receipt / fallback), then the double-projection guard, and
13
+ * finally projects the receipt when the scope document asks for it. Order is
14
+ * fixed: `next() → scope gate → canonicalise → invalidate → decide →
15
+ * (shadow receipt | admit and enqueue | fallback) → double-projection guard →
16
+ * projection → return the decision` (plan §Task 23b). A call with no
17
+ * `exec.agent` is not the plugin's to inspect: the downstream decision is
18
+ * returned untouched and a `skip:no-scope` receipt keeps the pass visible
19
+ * (design §5.5). A call carrying `exec.parent` is a PTC inner dispatch and
20
+ * returns before any of this: it is not the step's root receipt.
21
+ * - `llm/stream` is the model-request waterfall. Its body lives in
22
+ * `./llm-stream.ts` (Task 23c-1) and is re-exported below: it lets the
23
+ * plugin's own selector request through untouched, then answers a pending
24
+ * decision with a synthesized turn or delegates to `next()` after the
25
+ * turn/anchor checks. The mount is registered here because `registerHooks`
26
+ * is the single assembly surface.
27
+ * - `tools/execute` looks the session's pending substitution up with `peek`
28
+ * (never `take`: the entry must survive to this hook), compares the arriving
29
+ * `callId` itself. A **differing** `callId` is not tampering: the host assigns
30
+ * call ids and our synthesized turn sets the one we chose, so a call carrying
31
+ * a different id is an ordinary call that has nothing to do with the
32
+ * substitution — it passes through untouched. Only when the ids are equal does
33
+ * `rejectIfTampered` run, and only then is the entry cleared (on accept or
34
+ * reject), because the entry has then served its purpose.
35
+ * - the `systemPrompt` section reads the per-agent judgement cache
36
+ * synchronously. Its `text` must be a function, never a static string: a
37
+ * static string would inject the protocol into every session unconditionally
38
+ * and defeat the scope document (design §5.5).
39
+ *
40
+ * ## What Task 23b added
41
+ *
42
+ * The receipt map (`ReceiptSessionState`) keys `'root'` to the receipt that
43
+ * just arrived and each executed candidate's id to its own receipt, so guards
44
+ * and `$public` templates always read the arrival-time canonical text and a
45
+ * later step can project a value from an earlier step. The executable args
46
+ * always come from the *decision* (`decision.args` / `decision.candidates[i]
47
+ * .args`), never from `plan.steps[i].args`, which still holds `$public`
48
+ * templates. A plan is one-shot per receipt: the first post-execute that reads
49
+ * it removes it, so neither a guard failure nor a commit can leave the block
50
+ * alive to fire against a later receipt (the model writes a new block for its
51
+ * next call). It also means `decide` cannot re-commit the same step.
52
+ *
53
+ * The `shadow` flag from the scope document drives both `decide` (which skips
54
+ * the whitelist) and the record-only branch: a shadow commit writes a
55
+ * `{kind:'shadow'}` receipt and neither enqueues nor takes budget. It does
56
+ * **not** suppress projection: `shadow` and `projection` are independent
57
+ * switches (design §5.2-5), and projection-shadow mode writes only its
58
+ * accounting receipt. Admission runs in the mandated order — existence,
59
+ * `worthSubstituting`, then `budget.take()` — so a fallback never spends budget
60
+ * for a call it did not substitute.
61
+ *
62
+ * Everything here is contained: the host turns a throwing `post-execute`
63
+ * listener into an error result and the tool's real output is lost, so every
64
+ * foreign call (stores, queue, clock, usage, estimator) is wrapped. The
65
+ * `tools/execute` mount is contained too, failing open on an internal error:
66
+ * the design's fail-closed definition is "pass through, do not substitute",
67
+ * never "intercept the call" (design §5.5).
68
+ *
69
+ * The provider's `c.scope` is the agent itself at runtime: the host builds the
70
+ * assembly context as `{ agent, scope: agent, signal }`
71
+ * (`@deepseek-ai/dsh-agent/lib/index.js:410`), even though the declared type is
72
+ * the opaque `ScopeKey`. Keying the cache on anything else — or falling back to
73
+ * a no-argument judgement — would leak one session's visibility into another.
74
+ *
75
+ * @module dsh-boost/hooks/post-execute
76
+ */
77
+ import { worthSubstituting } from '../admission/ledger.js';
78
+ import { DEFAULT_CONFIG } from '../config.js';
79
+ import { decide } from '../gate/decide.js';
80
+ import { alreadySpilled, looksPruned } from '../gate/invalidate.js';
81
+ import { isPosixOnly } from '../host/platform.js';
82
+ import { PROTOCOL_NAME, PROTOCOL_ORDER, PROTOCOL_TEXT } from '../prompt/protocol.js';
83
+ import { projectApply, projectShadow } from '../projection/apply.js';
84
+ import { canonicalise } from '../projection/canonicalise.js';
85
+ import { DEFAULT_SCOPE, isVisible } from '../scope/doc.js';
86
+ import { SELECTOR_SYSTEM_PROMPT, choose, selectorPromptText } from '../selector/jev.js';
87
+ import { familyOf } from '../tools/family.js';
88
+ import { rejectIfTampered } from './execute.js';
89
+ import { receiptsStopped, sessionBudget, sessionClock, sessionUsage, settleDiscarded, streamHook, } from './llm-stream.js';
90
+ import { callIdFor } from './pending.js';
91
+ import { ReceiptSessionState, appendReceipt, callPreview, clearAnchors, clearPlan, clearPending, clockTurnOf, peekPending, previewOf, } from './session-state.js';
92
+ /**
93
+ * The `llm/stream` body lives in its own module (Task 23c-1). It is re-exported
94
+ * here because `registerHooks` is the assembly surface the rest of the plugin
95
+ * and the integration tests import; the mount below uses the same function.
96
+ */
97
+ export { streamHook };
98
+ /**
99
+ * The substitution whitelist: exactly the read-only trio (design §5.2-5).
100
+ *
101
+ * One constant drives both `decide` (non-shadow) and the `whitelisted` field
102
+ * written to the shadow/substitute receipts, so the policy the gate enforced
103
+ * and the policy the audit trail reports cannot drift. `bash`, `web_fetch` and
104
+ * every write tool stay out: they have no deterministic read-only judgement.
105
+ */
106
+ export const SUBSTITUTION_WHITELIST = new Set(['read', 'grep', 'glob']);
107
+ /**
108
+ * Hard cap on the receipt text shown to the selector.
109
+ *
110
+ * A full 40 KB receipt would dominate the selector call before the candidate
111
+ * summaries are added. This cap keeps the receipt near 300 tokens even when the
112
+ * tool family's projection window is larger, while still showing the
113
+ * projection's head/tail shape. The actual input+output charge is computed
114
+ * from the text that is sent, never from this cap alone.
115
+ */
116
+ const SELECTOR_RECEIPT_MAX_CHARS = 1_200;
117
+ /** Skip reasons that mean the projection machinery degraded, not "nothing to cut". */
118
+ const PROJECTION_DEGRADATIONS = new Set([
119
+ 'no-spill',
120
+ 'no-owner',
121
+ 'projection-skipped:no-footer',
122
+ 'spill-failed',
123
+ 'footer-failed',
124
+ ]);
125
+ /** The judgement-cache key carried by the assembly context's `scope`. */
126
+ function agentKeyOf(scope) {
127
+ const id = scope?.session?.header?.id;
128
+ return typeof id === 'string' ? id : undefined;
129
+ }
130
+ /** The session a hook call belongs to, or `undefined` when the host supplied none. */
131
+ function sessionIdOf(exec) {
132
+ const id = exec?.agent?.session?.header?.id;
133
+ return typeof id === 'string' ? id : undefined;
134
+ }
135
+ /**
136
+ * The protocol section's synchronous provider.
137
+ *
138
+ * It may only read the cached judgement: the host assembles prompts
139
+ * synchronously, so there is nothing to await. A missing store, a store without
140
+ * `judgement`, a context without `scope`, and a scope without a session id all
141
+ * mean "inject nothing" (fail-closed, design §5.5).
142
+ */
143
+ function protocolText(scope, context) {
144
+ if (scope == null || typeof scope.judgement !== 'function')
145
+ return '';
146
+ const key = agentKeyOf(context?.scope);
147
+ if (key === undefined)
148
+ return '';
149
+ return scope.judgement(key) ? PROTOCOL_TEXT : '';
150
+ }
151
+ // ---------------------------------------------------------------------------
152
+ // Defensive readers: every foreign call is wrapped
153
+ // ---------------------------------------------------------------------------
154
+ /**
155
+ * The host step index, or `undefined` when no clock can supply one.
156
+ *
157
+ * `undefined` is fail-closed: the decision path refuses to invent a step
158
+ * (a plugin-side counter would collide two substitutions in one turn — T23a).
159
+ */
160
+ function clockStepOf(deps, sessionId) {
161
+ try {
162
+ const step = sessionClock(deps, sessionId)?.step();
163
+ return typeof step === 'number' && Number.isFinite(step) ? step : undefined;
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ }
169
+ /** The session's anchors without ever failing the call. */
170
+ function pendingAnchorsOf(deps, sessionId) {
171
+ try {
172
+ return deps.anchors?.get(sessionId);
173
+ }
174
+ catch {
175
+ return undefined;
176
+ }
177
+ }
178
+ /**
179
+ * The only invalidation branch that is live at this call site: the prune marker.
180
+ *
181
+ * `invalidate` also compares the anchor text, but a `tools/post-execute` receipt
182
+ * is a *different* call's body, so that comparison can never establish the
183
+ * anchored receipt's identity here; it would fire `compaction-reset` after every
184
+ * commit, drop the anchors obligation 10 exists to keep for 23c, and skip one
185
+ * decision (review F1). The anchor branch belongs on the model-request path
186
+ * (`llm/stream`, 23c), where the compared text is the anchored receipt's current
187
+ * body in the outgoing messages.
188
+ */
189
+ function markerResetOf(pending, receiptText) {
190
+ try {
191
+ if (pending == null)
192
+ return undefined;
193
+ return looksPruned(receiptText) ? 'pruned-reset' : undefined;
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ }
199
+ /** Write one ledger record, keyed to the session and host turn. */
200
+ function ledgerEntry(ctx, kind, code, extra = {}) {
201
+ return {
202
+ version: 1,
203
+ ts: new Date().toISOString(),
204
+ sessionId: ctx.sessionId,
205
+ turn: ctx.turn,
206
+ kind,
207
+ code,
208
+ ...(typeof ctx.exec.name === 'string' ? { tool: ctx.exec.name } : {}),
209
+ // The operator's evidence line: the canonical receipt head and the executed
210
+ // args. Without args every same-tool/same-turn receipt hashed identically
211
+ // (stepId is always 'root').
212
+ preview: previewOf(ctx.receipt.text),
213
+ ...(ctx.exec.arguments !== undefined ? { args: ctx.exec.arguments } : {}),
214
+ ...extra,
215
+ };
216
+ }
217
+ /**
218
+ * Caps on the plan evidence a substitution receipt carries.
219
+ *
220
+ * G2 (design line 71) requires the receipt to answer "why was the model not
221
+ * asked" with 计划、守卫、绑定、回执、节省量; without the plan and the guards an
222
+ * auditor sees what ran but not why it was legitimate. The plan is
223
+ * model-written text though, and a receipt is one line: 256 code points of
224
+ * goal (the same order as `preview`), at most 8 guards, and at most 300 code
225
+ * points per guard. The bound is a *code-point* cap, not a byte cap: one
226
+ * pathological plan can contribute up to ~9.6 KB from the guards alone
227
+ * (8 × 300 code points × 4 UTF-8 bytes for 4-byte characters) plus up to
228
+ * ~1 KB from the 256-code-point goal. That is bounded and auditable, but a
229
+ * receipt line can exceed 10 KB — status and readers must not assume 2.7 KB.
230
+ * Truncation is always visible: the goal ends in `…`, an oversized guard
231
+ * becomes `{truncated_json: "…"}`, and `guards_total` is present whenever
232
+ * guards were left out.
233
+ */
234
+ const MAX_RECEIPT_PLAN_CODE_POINTS = 256;
235
+ const MAX_RECEIPT_GUARDS = 8;
236
+ const MAX_RECEIPT_GUARD_CODE_POINTS = 300;
237
+ /** Cap a string by code point so a surrogate pair is never split. */
238
+ function capText(value, cap) {
239
+ const points = Array.from(value);
240
+ if (points.length <= cap)
241
+ return value;
242
+ return `${points.slice(0, Math.max(0, cap - 1)).join('')}…`;
243
+ }
244
+ /**
245
+ * The plan/goal and guard evidence for one committed candidate.
246
+ *
247
+ * Guards are carried as written while they fit. Only a guard whose own JSON
248
+ * exceeds {@link MAX_RECEIPT_GUARD_CODE_POINTS} (a multi-KB `text_contains`,
249
+ * say) is replaced by a `truncated_json` marker, so the array stays bounded
250
+ * without silently dropping the guard's form.
251
+ */
252
+ export function substitutionEvidence(goal, guards) {
253
+ const carried = guards.slice(0, MAX_RECEIPT_GUARDS).map((guard) => {
254
+ const json = JSON.stringify(guard) ?? '';
255
+ return Array.from(json).length <= MAX_RECEIPT_GUARD_CODE_POINTS
256
+ ? guard
257
+ : { truncated_json: capText(json, MAX_RECEIPT_GUARD_CODE_POINTS) };
258
+ });
259
+ return {
260
+ plan: capText(typeof goal === 'string' ? goal : '', MAX_RECEIPT_PLAN_CODE_POINTS),
261
+ guards: carried,
262
+ ...(guards.length > MAX_RECEIPT_GUARDS ? { guards_total: guards.length } : {}),
263
+ };
264
+ }
265
+ /**
266
+ * Append one `skip:no-scope` receipt.
267
+ *
268
+ * The no-agent case has no session id and no turn; the empty session id and
269
+ * turn zero are honest placeholders, and the `code` is the field status counts.
270
+ */
271
+ async function appendSkipNoScope(receipts, exec, sessionId = '', turn = 0) {
272
+ if (receipts == null || typeof receipts.append !== 'function')
273
+ return;
274
+ try {
275
+ await receipts.append({
276
+ version: 1,
277
+ ts: new Date().toISOString(),
278
+ sessionId,
279
+ turn,
280
+ kind: 'skip',
281
+ code: 'skip:no-scope',
282
+ tool: exec?.name,
283
+ });
284
+ }
285
+ catch {
286
+ // A receipt is evidence, not a precondition: never break the call for it.
287
+ }
288
+ }
289
+ /** Append one invalidation receipt; a receipt failure never breaks the call. */
290
+ async function appendResetReceipt(receipts, exec, sessionId, turn, stepId, code) {
291
+ if (receipts == null || typeof receipts.append !== 'function')
292
+ return;
293
+ try {
294
+ await receipts.append({
295
+ version: 1,
296
+ ts: new Date().toISOString(),
297
+ sessionId,
298
+ turn,
299
+ stepId,
300
+ kind: 'reset',
301
+ code,
302
+ tool: exec?.name,
303
+ });
304
+ }
305
+ catch {
306
+ // A receipt is evidence, not a precondition: never break the call for it.
307
+ }
308
+ }
309
+ /**
310
+ * Abandon the pending decision after an external rewrite.
311
+ *
312
+ * Only the plugin's own anchor record is touched — the session log's current
313
+ * body is never read (design §5.2-7). Clearing happens before the receipt write
314
+ * so a stalled store cannot leave the stale anchors in place; both steps are
315
+ * contained so the tool result survives.
316
+ *
317
+ * The decision-time usage mark is settled **without** a settlement receipt
318
+ * first, exactly like `applyAbandon`: the substitution was never synthesized,
319
+ * so there is no saving to report. Leaving the mark would let the next real
320
+ * request pair itself with it and write a `substitute-settled` line for a
321
+ * substitution that never ran (row 1).
322
+ */
323
+ async function resetInvalidatedPending(deps, exec, sessionId, turn, pending, code) {
324
+ // Design §5.2-7: a reset returns to the slow path *and* empties pending, so no
325
+ // queued substitution can fire from anchors that no longer name live text. The
326
+ // plan is dropped too: it was written for the invalidated receipt, and leaving
327
+ // it would let it fire against a later one.
328
+ settleDiscarded(deps, sessionId);
329
+ clearAnchors(deps, sessionId);
330
+ clearPending(deps, sessionId);
331
+ clearPlan(deps, sessionId);
332
+ await appendResetReceipt(deps.receipts, exec, sessionId, turn, pending.stepId, code);
333
+ }
334
+ /**
335
+ * The host's spill-notice predicate, resolved at most once per process.
336
+ *
337
+ * The spill policy is never declared as a dependency (design §5.4), so its notice module is
338
+ * imported dynamically: a static import would make the plugin fail to load on
339
+ * a host without it. A missing package means no receipt can carry its footer,
340
+ * so the guard simply does not fire. The deps seam wins, which is what keeps
341
+ * the guard testable without the host.
342
+ */
343
+ let noticePredicate;
344
+ function resolveNoticePredicate(deps) {
345
+ if (typeof deps.hasSpillNotice === 'function')
346
+ return Promise.resolve(deps.hasSpillNotice);
347
+ noticePredicate ??= import('@deepseek-ai/dsh-spill-policy/notice')
348
+ .then((module) => (typeof module.hasSpillNotice === 'function' ? module.hasSpillNotice : undefined))
349
+ .catch(() => undefined);
350
+ return noticePredicate;
351
+ }
352
+ /**
353
+ * The host's spill footer renderer, resolved lazily.
354
+ *
355
+ * `projectApply` cannot statically import the spill policy for the same reason
356
+ * the notice predicate cannot. A missing package makes apply-mode projection
357
+ * degrade to `projection-skipped:no-footer` in `projectApply` itself — and,
358
+ * because that turns the plugin's headline feature off, the first resolution
359
+ * that yields nothing is logged once (never per receipt, which would drown the
360
+ * log of a busy session). `status` maps the same receipt code to
361
+ * `ERR_HOST_NO_SPILL_NOTICE`, so the degradation also reaches the operator who
362
+ * never reads the log.
363
+ */
364
+ let footerFormatter;
365
+ /** One warning per process; a missing host module is not a per-call event. */
366
+ let footerMissingLogged = false;
367
+ /** Log the missing-footer degradation once; a foreign logger must not throw. */
368
+ function noteMissingFooter(deps) {
369
+ if (footerMissingLogged)
370
+ return;
371
+ footerMissingLogged = true;
372
+ try {
373
+ deps.logger?.warn?.('dsh-boost: ERR_HOST_NO_SPILL_NOTICE: @deepseek-ai/dsh-spill-policy/notice resolved no formatSpillNotice; ' +
374
+ 'apply-mode projection is disabled (projection-skipped:no-footer) until the host spill policy is available');
375
+ }
376
+ catch {
377
+ // A logger failure must not become a tool failure.
378
+ }
379
+ }
380
+ function resolveFooterFormatter(deps) {
381
+ // The seam wins over the memoised import, exactly like `hasSpillNotice`: a
382
+ // test states "the module resolved nothing" without uninstalling the host
383
+ // package. It is deliberately not memoised — it belongs to one deps object.
384
+ if (typeof deps.resolveFooter === 'function') {
385
+ return Promise.resolve()
386
+ .then(() => deps.resolveFooter?.())
387
+ .then((formatter) => {
388
+ if (formatter === undefined)
389
+ noteMissingFooter(deps);
390
+ return formatter;
391
+ })
392
+ .catch(() => {
393
+ noteMissingFooter(deps);
394
+ return undefined;
395
+ });
396
+ }
397
+ footerFormatter ??= import('@deepseek-ai/dsh-spill-policy/notice')
398
+ .then((module) => {
399
+ if (typeof module.formatSpillNotice !== 'function')
400
+ return undefined;
401
+ return (omitted, ref) =>
402
+ // T6's `SpillBackend` widens the host's branded `SpillLocator` to
403
+ // `string`; the value is the same at runtime.
404
+ module.formatSpillNotice(omitted, ref);
405
+ })
406
+ .catch(() => undefined)
407
+ .then((formatter) => {
408
+ if (formatter === undefined)
409
+ noteMissingFooter(deps);
410
+ return formatter;
411
+ });
412
+ return footerFormatter;
413
+ }
414
+ /**
415
+ * The canonical text of the decision that will enter history, when it carries
416
+ * a content array.
417
+ *
418
+ * The host spill policy registers with `{ prepend: true }`: it calls `next()`
419
+ * and applies its footer to *that* decision, so the footer lives in
420
+ * `decision.content` and never in the `result.content` this listener received.
421
+ * `undefined` means "the decision carries no content"; the caller then falls
422
+ * back to the receiver as it arrived.
423
+ */
424
+ function decisionTextOf(decision) {
425
+ const content = decision.content;
426
+ if (!Array.isArray(content))
427
+ return undefined;
428
+ return canonicalise(content, false).text;
429
+ }
430
+ /**
431
+ * Whether projection must be skipped because the host already spilled this
432
+ * receipt (design §5.4).
433
+ *
434
+ * A predicate that throws counts as "already spilled": when the notice cannot
435
+ * be ruled out, a second projection could hide the original twice, so the safe
436
+ * direction is to leave the receipt alone.
437
+ */
438
+ async function isAlreadySpilled(deps, receiptText) {
439
+ try {
440
+ const hasNotice = await resolveNoticePredicate(deps);
441
+ return hasNotice !== undefined && alreadySpilled(receiptText, hasNotice);
442
+ }
443
+ catch {
444
+ return true;
445
+ }
446
+ }
447
+ /** Whether the plugin is active for this session (fail-closed on any doubt). */
448
+ function isActiveSession(deps, sessionId) {
449
+ const scope = deps.scope;
450
+ if (scope == null || typeof scope.judgement !== 'function')
451
+ return false;
452
+ try {
453
+ return scope.judgement(sessionId);
454
+ }
455
+ catch {
456
+ return false;
457
+ }
458
+ }
459
+ /**
460
+ * The live scope document, or the strict default when it cannot be read.
461
+ *
462
+ * Read once per decision pass rather than cached: `boost` writes the document
463
+ * while the plugin runs, and the projection/shadow switches must follow it. A
464
+ * missing or throwing reader degrades to `DEFAULT_SCOPE`, whose `shadow: true`
465
+ * makes the substitution path record-only — the safe direction.
466
+ */
467
+ async function scopeDocOf(deps) {
468
+ try {
469
+ const read = deps.scope?.read;
470
+ if (typeof read !== 'function')
471
+ return DEFAULT_SCOPE;
472
+ const result = await read.call(deps.scope);
473
+ const raw = result?.doc;
474
+ if (raw === null || typeof raw !== 'object')
475
+ return DEFAULT_SCOPE;
476
+ return raw;
477
+ }
478
+ catch {
479
+ return DEFAULT_SCOPE;
480
+ }
481
+ }
482
+ // ---------------------------------------------------------------------------
483
+ // Retrieval accounting
484
+ // ---------------------------------------------------------------------------
485
+ /** The calls that can retrieve a spilled artifact (design §5.3). */
486
+ const RETRIEVAL_TOOLS = new Set(['read', 'grep']);
487
+ /**
488
+ * Detect a retrieval without writing anything yet.
489
+ *
490
+ * Detection has to happen before the visibility gate (a projected receipt
491
+ * consumed context whether or not the workspace is still visible), but the
492
+ * cost must wait until projection has decided what the model will actually
493
+ * see (review I3). The split keeps both properties.
494
+ */
495
+ function pendingRetrievalOf(deps, exec, sessionId) {
496
+ try {
497
+ const name = exec?.name;
498
+ if (typeof name !== 'string' || !RETRIEVAL_TOOLS.has(name))
499
+ return undefined;
500
+ const ledger = deps.retrievals;
501
+ if (ledger == null || typeof ledger.locate !== 'function')
502
+ return undefined;
503
+ const locator = ledger.locate(sessionId, exec.arguments);
504
+ return locator === undefined ? undefined : { locator };
505
+ }
506
+ catch {
507
+ return undefined;
508
+ }
509
+ }
510
+ /**
511
+ * The one-time cost of one retrieval, or `undefined` when it cannot be priced.
512
+ *
513
+ * This is the **per-receipt** figure: the call block (name + arguments) plus
514
+ * the content the model saw. The replay multiplier is applied once, to both
515
+ * sides of the net formula, in `status` — multiplying only the cost by the
516
+ * horizon made a cheap partial re-read look like a loss (review C1).
517
+ *
518
+ * `content` is the decision's final visible text, so a retrieval that is itself
519
+ * projected is charged for the window, not the raw result (review I3). A
520
+ * missing/non-finite estimate is omitted rather than fabricated.
521
+ */
522
+ function retrievalCostOf(deps, exec, content) {
523
+ const estimate = estimatorOf(deps);
524
+ if (estimate === undefined)
525
+ return undefined;
526
+ const contentTokens = safeEstimate(estimate, content);
527
+ if (contentTokens === undefined)
528
+ return undefined;
529
+ let params = '';
530
+ try {
531
+ params = JSON.stringify(exec.arguments) ?? '';
532
+ }
533
+ catch {
534
+ params = '';
535
+ }
536
+ const callTokens = safeEstimate(estimate, `${exec.name ?? 'tool'} ${params}`);
537
+ if (callTokens === undefined)
538
+ return undefined;
539
+ const totalTokens = callTokens + contentTokens;
540
+ return Number.isFinite(totalTokens) ? { callTokens, contentTokens, totalTokens } : undefined;
541
+ }
542
+ /**
543
+ * Count a `read`/`grep` that names one of this session's spill locators.
544
+ *
545
+ * `appendReceipt` is the store's only write path, and `kind:'projection'` with
546
+ * `retrieved:true` is exactly what `boost status` aggregates as
547
+ * `projection_retrievals` and `projection_retrieval_tokens`. No
548
+ * `saved_projection_tokens` is written: this line documents a cost, not
549
+ * another gross saving.
550
+ *
551
+ * `visibleText` is the content that enters history after projection, which is
552
+ * what the model must pay to replay.
553
+ */
554
+ async function recordProjectionRetrieval(deps, exec, sessionId, pending, visibleText) {
555
+ try {
556
+ const name = exec?.name;
557
+ if (typeof name !== 'string')
558
+ return;
559
+ const cost = retrievalCostOf(deps, exec, visibleText);
560
+ const entry = {
561
+ version: 1,
562
+ ts: new Date().toISOString(),
563
+ sessionId,
564
+ turn: clockTurnOf(deps, sessionId) ?? 0,
565
+ kind: 'projection',
566
+ code: 'projection-retrieval',
567
+ tool: name,
568
+ retrieved: true,
569
+ locator: pending.locator,
570
+ // The visible content replays over this horizon in `status`'s net, so it
571
+ // must be the horizon in effect when the retrieval happened, not one read
572
+ // from the whole ledger later.
573
+ horizon_steps: projectionHorizonOf(deps, sessionId),
574
+ preview: previewOf(visibleText),
575
+ ...(exec.arguments !== undefined ? { args: exec.arguments } : {}),
576
+ };
577
+ if (cost === undefined) {
578
+ entry.estimate = 'unknown';
579
+ }
580
+ else {
581
+ entry.retrieval_call_tokens = cost.callTokens;
582
+ entry.retrieval_content_tokens = cost.contentTokens;
583
+ entry.retrieval_tokens = cost.totalTokens;
584
+ entry.estimate = deps.estimateKind ?? 'unknown';
585
+ }
586
+ await appendReceipt(deps, entry);
587
+ }
588
+ catch {
589
+ // A retrieval is evidence, never a precondition of the tool result.
590
+ }
591
+ }
592
+ // ---------------------------------------------------------------------------
593
+ // Admission and the decision branch
594
+ // ---------------------------------------------------------------------------
595
+ /**
596
+ * The conservative saving of skipping one model step: the last real request's
597
+ * replayed context (`input + cacheRead`).
598
+ *
599
+ * The step that is skipped would have replayed at least this much: the context
600
+ * only grows as receipts enter it. A missing ledger or sample is 0, never an
601
+ * interpolation, so admission falls back to the model when it cannot measure
602
+ * (design §5.3: measured, not estimated).
603
+ */
604
+ function savedTokensOf(deps, sessionId) {
605
+ try {
606
+ const last = sessionUsage(deps, sessionId)?.last();
607
+ if (last === undefined)
608
+ return 0;
609
+ const { input, cacheRead } = last;
610
+ if (!Number.isFinite(input) || !Number.isFinite(cacheRead) || input < 0 || cacheRead < 0)
611
+ return 0;
612
+ const total = input + cacheRead;
613
+ return Number.isFinite(total) ? total : 0;
614
+ }
615
+ catch {
616
+ return 0;
617
+ }
618
+ }
619
+ /**
620
+ * Whether this commit clears the admission threshold.
621
+ *
622
+ * A plan with exactly one candidate is the design's deterministic-single
623
+ * exemption: there is no selector call to pay for, so the threshold does not
624
+ * apply. Any other plan pays no selector either once only one candidate
625
+ * survives, but it still has to show a net win over the threshold; the
626
+ * conservative direction here is to keep the gate on.
627
+ */
628
+ function admittedFor(deps, sessionId, plan, overheadTokens) {
629
+ try {
630
+ const threshold = deps.config?.admission?.thresholdTokens;
631
+ const thresholdTokens = typeof threshold === 'number' && Number.isFinite(threshold)
632
+ ? threshold
633
+ : DEFAULT_CONFIG.admission.thresholdTokens;
634
+ return worthSubstituting({
635
+ savedTokens: savedTokensOf(deps, sessionId),
636
+ overheadTokens,
637
+ thresholdTokens,
638
+ deterministicSingle: plan.steps.length === 1,
639
+ });
640
+ }
641
+ catch {
642
+ return false;
643
+ }
644
+ }
645
+ /**
646
+ * Whether the session's turn budget is already empty, without consuming it.
647
+ *
648
+ * A selector call is real spend, so this check runs before the selector is
649
+ * priced or called; the consuming `takeBudget` stays at the commit point.
650
+ * A missing or foreign budget means "not exhausted", matching `takeBudget`'s
651
+ * no-cap contract. Shadow mode never calls this: it spends no step.
652
+ */
653
+ function budgetExhausted(deps, sessionId) {
654
+ try {
655
+ const budget = sessionBudget(deps, sessionId);
656
+ if (budget == null || typeof budget.exhausted !== 'function')
657
+ return false;
658
+ return budget.exhausted() === true;
659
+ }
660
+ catch {
661
+ return false;
662
+ }
663
+ }
664
+ /** Claim one budget step; no budget wired means no cap is applied. */
665
+ function takeBudget(deps, sessionId) {
666
+ try {
667
+ const budget = sessionBudget(deps, sessionId);
668
+ if (budget == null || typeof budget.take !== 'function')
669
+ return true;
670
+ return budget.take();
671
+ }
672
+ catch {
673
+ return false;
674
+ }
675
+ }
676
+ /** Record the substitution for the usage pairing; the stream hook settles it. */
677
+ function markSubstituted(deps, sessionId, candidateId) {
678
+ try {
679
+ sessionUsage(deps, sessionId)?.markSubstituted(candidateId);
680
+ }
681
+ catch {
682
+ // A ledger miss costs a measurement, never this call.
683
+ }
684
+ }
685
+ /**
686
+ * The receipt ids a candidate's `$public` templates refer to, plus `'root'`.
687
+ *
688
+ * These are the anchors the invalidation check compares against: the chosen
689
+ * candidate's arguments were computed from those receipts, so if any of them
690
+ * is rewritten externally the decision is stale. The walk is iterative and
691
+ * depth-capped because it runs over model-written args; `parsePlan` already
692
+ * caps them at 64 levels, but the hook must not depend on that.
693
+ */
694
+ function referencedReceiptIds(args) {
695
+ const ids = new Set(['root']);
696
+ const stack = [{ value: args, depth: 1 }];
697
+ while (stack.length > 0) {
698
+ const frame = stack.pop();
699
+ if (frame === undefined)
700
+ break;
701
+ if (frame.depth > 64)
702
+ continue;
703
+ if (Array.isArray(frame.value)) {
704
+ for (const child of frame.value) {
705
+ if (typeof child === 'object' && child !== null) {
706
+ stack.push({ value: child, depth: frame.depth + 1 });
707
+ }
708
+ }
709
+ continue;
710
+ }
711
+ if (typeof frame.value !== 'object' || frame.value === null)
712
+ continue;
713
+ const { $public: template, ...rest } = frame.value;
714
+ if (typeof template === 'object' &&
715
+ template !== null &&
716
+ typeof template.after === 'string') {
717
+ ids.add(template.after);
718
+ }
719
+ for (const child of Object.values(rest)) {
720
+ if (typeof child === 'object' && child !== null) {
721
+ stack.push({ value: child, depth: frame.depth + 1 });
722
+ }
723
+ }
724
+ }
725
+ return ids;
726
+ }
727
+ /**
728
+ * Store the session's anchors for the committed candidate.
729
+ *
730
+ * `stepId` is `'root'` because the guards and templates were evaluated against
731
+ * the receipt that just arrived; the map carries that receipt's canonical text
732
+ * plus the text of every receipt the candidate's `$public` templates reference
733
+ * (design §5.2-7). Missing references are omitted rather than invented.
734
+ */
735
+ function setAnchors(deps, ctx, candidateArgs) {
736
+ try {
737
+ const anchorsStore = deps.anchors;
738
+ if (anchorsStore == null || typeof anchorsStore.set !== 'function')
739
+ return;
740
+ const receipts = ctx.state.receiptsFor(ctx.sessionId, ctx.turn);
741
+ const anchors = {};
742
+ for (const id of referencedReceiptIds(candidateArgs)) {
743
+ const receipt = receipts.get(id);
744
+ if (receipt !== undefined)
745
+ anchors[id] = receipt.text;
746
+ }
747
+ anchorsStore.set(ctx.sessionId, { stepId: 'root', anchors });
748
+ }
749
+ catch {
750
+ // Anchors are a guard input, not the guard: losing them costs a reset.
751
+ }
752
+ }
753
+ /**
754
+ * Whether the session may be substituted for right now.
755
+ *
756
+ * Both gates must agree: the cached judgement said yes (the listener would
757
+ * have returned otherwise), and the live document still lists the session's
758
+ * workspace. The second check cannot be skipped: the cache is refreshed by a
759
+ * different task, and a stale "visible" must never authorize a replacement.
760
+ */
761
+ function substitutableSession(deps, sessionId, doc) {
762
+ try {
763
+ const workspaceId = deps.resolveSession?.(sessionId);
764
+ if (typeof workspaceId !== 'string')
765
+ return false;
766
+ return isVisible(doc, workspaceId);
767
+ }
768
+ catch {
769
+ return false;
770
+ }
771
+ }
772
+ /**
773
+ * A selector-facing summary of one already-bound candidate.
774
+ *
775
+ * The selector only needs to tell candidates apart; the args are included so
776
+ * two calls to the same tool with different paths are distinguishable. The
777
+ * bound tree is safe to show (it is what will run) and bounded so one huge
778
+ * argument cannot dominate the selector prompt.
779
+ */
780
+ function selectorSummary(candidate) {
781
+ let args = '';
782
+ try {
783
+ args = JSON.stringify(candidate.args) ?? '';
784
+ }
785
+ catch {
786
+ // A model-written plan is already JSON, but the summary is evidence-shaped
787
+ // and must not make the selector call throw.
788
+ }
789
+ const text = `${candidate.tool} ${args}`.trim();
790
+ const points = Array.from(text);
791
+ return points.length > 200 ? `${points.slice(0, 200).join('')}…` : text;
792
+ }
793
+ /** Bound the receipt the selector pays for, using the projection's head/tail shape. */
794
+ function selectorReceiptOf(deps, ctx) {
795
+ const text = ctx.receipt.text;
796
+ const points = Array.from(text);
797
+ if (points.length <= SELECTOR_RECEIPT_MAX_CHARS)
798
+ return text;
799
+ const toolName = ctx.exec.name;
800
+ const family = toolName === undefined ? undefined : familyOf(toolName);
801
+ const params = family !== undefined ? deps.config.projection[family] : undefined;
802
+ const configured = params !== undefined ? params.headChars + params.tailChars : 0;
803
+ const total = Math.min(SELECTOR_RECEIPT_MAX_CHARS, configured > 0 ? configured : SELECTOR_RECEIPT_MAX_CHARS);
804
+ const ratio = configured > 0 && params !== undefined ? params.headChars / configured : 0.8;
805
+ const headChars = Math.min(total, Math.max(0, Math.round(total * ratio)));
806
+ const tailChars = total - headChars;
807
+ const head = points.slice(0, headChars).join('');
808
+ const tail = tailChars > 0 ? points.slice(-tailChars).join('') : '';
809
+ const omitted = points.length - headChars - tailChars;
810
+ return `${head}\n…[selector window: omitted ${omitted} chars]…\n${tail}`;
811
+ }
812
+ /** The configured selector output budget, with the design default as a fallback. */
813
+ function selectorMaxTokens(deps) {
814
+ const raw = deps.config?.selector?.maxTokens;
815
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {
816
+ return DEFAULT_CONFIG.selector.maxTokens;
817
+ }
818
+ return Math.floor(raw);
819
+ }
820
+ /** The route the selector call would inherit, or `undefined` when it cannot run. */
821
+ function selectorRouteOf(deps, sessionId) {
822
+ try {
823
+ const route = deps.selectorRoute?.(sessionId);
824
+ if (route === undefined ||
825
+ typeof route.provider !== 'string' ||
826
+ typeof route.model !== 'string') {
827
+ return undefined;
828
+ }
829
+ return route;
830
+ }
831
+ catch {
832
+ return undefined;
833
+ }
834
+ }
835
+ /** Whether the selector is missing its LLM or its effective route. */
836
+ function selectorSeamUnavailable(deps, ctx) {
837
+ const llm = deps.llm;
838
+ return llm == null || typeof llm.stream !== 'function' || selectorRouteOf(deps, ctx.sessionId) === undefined;
839
+ }
840
+ /**
841
+ * The selector's fast upper bound: its output cap plus the estimated input.
842
+ *
843
+ * `maxTokens` bounds only the output; everything the request sends is input:
844
+ * the system prompt, the user template, the candidate list and the receipt.
845
+ * Charging only the receipt and the candidates under-counts the call by the
846
+ * prompt (about 60–70 tokens) and makes admission optimistic exactly where it
847
+ * decides whether to call. The priced string is built with the selector's own
848
+ * exported template, so the estimate cannot drift from the request (row 36).
849
+ * `undefined` means the caller cannot price the call; it must not guess.
850
+ */
851
+ function selectorChargeOf(deps, candidates, receiptText) {
852
+ const estimate = deps.estimateText;
853
+ if (typeof estimate !== 'function')
854
+ return undefined;
855
+ const prompt = selectorPromptText({
856
+ candidates: candidates.map((candidate) => ({
857
+ id: candidate.id,
858
+ summary: selectorSummary(candidate),
859
+ })),
860
+ receiptText,
861
+ });
862
+ const input = safeEstimate(estimate, `${SELECTOR_SYSTEM_PROMPT}\n${prompt}`);
863
+ if (input === undefined || input < 0)
864
+ return undefined;
865
+ return selectorMaxTokens(deps) + input;
866
+ }
867
+ /**
868
+ * Ask the selector to pick one of `decision.candidates` and return that same
869
+ * decision candidate, whose `args` are already bound.
870
+ *
871
+ * Never throws and never guesses. A missing LLM seam, a missing route, an
872
+ * abstention or a thrown call all leave the plan untouched and write one
873
+ * `skip` receipt explaining why; the next post-execute may try again. The
874
+ * `SELECTOR_PURPOSE` marker is set by `choose` itself, so the frozen stream
875
+ * hook can recognize and pass the aux request through.
876
+ */
877
+ async function chooseCandidate(deps, ctx, candidates, receiptText) {
878
+ const llm = deps.llm;
879
+ if (llm == null || typeof llm.stream !== 'function') {
880
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
881
+ return undefined;
882
+ }
883
+ let route;
884
+ try {
885
+ route = deps.selectorRoute?.(ctx.sessionId);
886
+ }
887
+ catch {
888
+ route = undefined;
889
+ }
890
+ if (route === undefined ||
891
+ typeof route.provider !== 'string' ||
892
+ typeof route.model !== 'string') {
893
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
894
+ return undefined;
895
+ }
896
+ try {
897
+ const result = await choose({
898
+ llm,
899
+ provider: route.provider,
900
+ model: route.model,
901
+ ...(typeof route.reasoningEffort === 'string'
902
+ ? { reasoningEffort: route.reasoningEffort }
903
+ : {}),
904
+ candidates: candidates.map((candidate) => ({
905
+ id: candidate.id,
906
+ summary: selectorSummary(candidate),
907
+ })),
908
+ receiptText,
909
+ maxTokens: deps.config.selector.maxTokens,
910
+ });
911
+ if ('choice' in result) {
912
+ // `candidates` are the decision's copies: their args are the bound tree.
913
+ return candidates.find((candidate) => candidate.id === result.choice);
914
+ }
915
+ // §5.2-3 distinguishes a timeout/no-label abstention from a failed call:
916
+ // `choose` maps its own dispatch failure to `abstain: 'error'`, and that is
917
+ // the `selector-error` branch, not a second abstention reason.
918
+ const code = result.abstain === 'error' ? 'selector-error' : 'selector-abstain';
919
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', code, { stepId: 'root', reason: result.abstain }));
920
+ return undefined;
921
+ }
922
+ catch {
923
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-error', { stepId: 'root', reason: 'error' }));
924
+ return undefined;
925
+ }
926
+ }
927
+ /**
928
+ * The substitution decision and its side effects.
929
+ *
930
+ * The fixed order is the plan's: existence of a plan and a receipt first, then
931
+ * `worthSubstituting`, then `budget.take()`. Nothing below spends budget on a
932
+ * decision that will not be dispatched.
933
+ *
934
+ * `ask-selector` is fulfilled here since Task 23c-2: the decision carries only
935
+ * already-bound candidates, so the selector's choice is committed from
936
+ * `decision.candidates[].args` — never from `plan.steps[i].args`, which still
937
+ * holds `$public` templates. The selector call is the plugin's own aux request
938
+ * (`purpose: 'boost-selector'`), so the frozen stream hook passes it through.
939
+ * A missing route or a missing LLM is a record-only abstention, never a guess.
940
+ * `fallback` records the decision code and leaves the pending entry alone: this
941
+ * invocation has enqueued nothing, so any entry it finds belongs to another
942
+ * call, and clearing it would cancel a live substitution in a multi-call step.
943
+ * A plan is **one-shot per receipt**: the first post-execute that reads it
944
+ * removes it from the session map, whatever the outcome (commit, guard
945
+ * failure, selector abstention, no candidate). The protocol says a block
946
+ * describes the next call and may be omitted when unsure; retaining it would
947
+ * let a plan the model has withdrawn fire against a much later receipt. The
948
+ * remaining candidates are not reused either; the model writes a fresh block
949
+ * for the next call (and may still reference an earlier receipt by id).
950
+ *
951
+ * A shadow commit parks nothing, but projection is independent of the shadow
952
+ * flag (design §5.2-5) and still runs in `applyDecision`.
953
+ */
954
+ async function decideSubstitution(deps, ctx) {
955
+ // Fail-closed gate (design §5.2-3): a store that cannot record evidence
956
+ // cannot justify spending a selector call or a budget step. No receipt is
957
+ // attempted here either; the store is already failing, and status exposes
958
+ // `receipts.stopped()` to the operator.
959
+ //
960
+ // The plan is still consumed here. This receipt cannot use it, and a plan is
961
+ // one-shot per receipt: keeping it for a later receipt is exactly the stale
962
+ // plan the one-shot rule exists to prevent. A store that recovers mid-turn
963
+ // would otherwise let the next receipt fire a decision the model wrote for
964
+ // this one.
965
+ if (receiptsStopped(deps)) {
966
+ clearPlan(deps, ctx.sessionId);
967
+ return;
968
+ }
969
+ const plan = safePlan(deps, ctx.sessionId);
970
+ if (plan === undefined)
971
+ return;
972
+ // One-shot: capture the plan for this pass, then drop it before any branch can
973
+ // return, so no later receipt can reuse it.
974
+ clearPlan(deps, ctx.sessionId);
975
+ // Design §9: no token meter means no substitution. The meter is what prices
976
+ // `worthSubstituting` and the selector's input, so running without it would
977
+ // spend real money on a fabricated estimate. Refuse before `decide`, before
978
+ // the selector and before admission; shadow mode is record-only and may
979
+ // still run. Projection is not gated (it needs no token numbers to clip).
980
+ const estimator = estimatorOf(deps);
981
+ if (!ctx.doc.shadow &&
982
+ (estimator === undefined || safeEstimate(estimator, 'dsh-boost meter probe') === undefined)) {
983
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'ERR_HOST_NO_TOKENMETER', {
984
+ stepId: 'root',
985
+ reason: 'no-token-meter',
986
+ }));
987
+ return;
988
+ }
989
+ let decision;
990
+ try {
991
+ decision = decide({
992
+ plan,
993
+ stepId: 'root',
994
+ receipts: ctx.state.receiptsFor(ctx.sessionId, ctx.turn),
995
+ whitelist: SUBSTITUTION_WHITELIST,
996
+ shadow: ctx.doc.shadow,
997
+ });
998
+ }
999
+ catch {
1000
+ return;
1001
+ }
1002
+ // Substitution synthesises a dispatch and expects POSIX process semantics;
1003
+ // on Windows it is refused **before** the selector, admission and budget, so
1004
+ // the path cannot spend anything to decline. Shadow mode is record-only and
1005
+ // stays available: it changes nothing the model sees. The stable operator
1006
+ // signal is `boost status`'s `ERR_HOST_PLATFORM_UNSUPPORTED`; this receipt
1007
+ // keeps the refusal auditable per call rather than silently doing less.
1008
+ if (!isPosixOnly() && !ctx.doc.shadow) {
1009
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', {
1010
+ stepId: 'root',
1011
+ reason: 'platform-unsupported',
1012
+ }));
1013
+ return;
1014
+ }
1015
+ let candidate;
1016
+ let boundArgs;
1017
+ let candidateId;
1018
+ // A selector call pays its output cap plus the input actually sent. A single
1019
+ // surviving candidate pays no selector at all. This must run before `choose`:
1020
+ // a selector call that cannot be paid for is never sent.
1021
+ let selectorOverhead = 0;
1022
+ let selectorReceiptText = '';
1023
+ if (decision.kind === 'ask-selector') {
1024
+ // Row 2: the budget is checked before the selector is paid for. Without
1025
+ // this, an exhausted step would still send a real model request and then
1026
+ // record `steps-exhausted` after the money was spent. Shadow mode is
1027
+ // record-only and takes no step, so it keeps measuring.
1028
+ if (!ctx.doc.shadow && budgetExhausted(deps, ctx.sessionId)) {
1029
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }));
1030
+ return;
1031
+ }
1032
+ // Availability is checked before pricing: a missing LLM/route is the
1033
+ // `selector-unavailable` degradation, not an admission decision.
1034
+ if (selectorSeamUnavailable(deps, ctx)) {
1035
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
1036
+ return;
1037
+ }
1038
+ selectorReceiptText = selectorReceiptOf(deps, ctx);
1039
+ const charge = selectorChargeOf(deps, decision.candidates, selectorReceiptText);
1040
+ if (charge === undefined) {
1041
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root', reason: 'no-estimator' }));
1042
+ return;
1043
+ }
1044
+ selectorOverhead = charge;
1045
+ if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {
1046
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }));
1047
+ return;
1048
+ }
1049
+ // The decision's candidates already carry the bound trees; committing from
1050
+ // the plan here would dispatch a `$public` template.
1051
+ const chosen = await chooseCandidate(deps, ctx, decision.candidates, selectorReceiptText);
1052
+ if (chosen === undefined)
1053
+ return;
1054
+ candidate = chosen;
1055
+ boundArgs = chosen.args;
1056
+ candidateId = chosen.id;
1057
+ }
1058
+ else if (decision.kind === 'fallback') {
1059
+ // This invocation enqueued nothing, so any pending entry belongs to another
1060
+ // call in the step; cancelling it would leave the budget spent and usage
1061
+ // marked for a substitution that never runs (review F2).
1062
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', decision.code, { stepId: 'root' }));
1063
+ return;
1064
+ }
1065
+ else {
1066
+ candidate = plan.steps.find((step) => step.id === decision.candidateId);
1067
+ boundArgs = decision.args;
1068
+ candidateId = decision.candidateId;
1069
+ }
1070
+ if (candidate === undefined || boundArgs === undefined || candidateId === undefined) {
1071
+ // decide only commits its own plan's ids; this is containment, not a path.
1072
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'no-candidate', { stepId: 'root' }));
1073
+ return;
1074
+ }
1075
+ // The live visibility check runs for the shadow path too: the record-only
1076
+ // measurement must describe the same population the real admission would
1077
+ // consider, not a broader one (review F2). The cached judgement passed above,
1078
+ // but the document may have changed while the session ran.
1079
+ if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) {
1080
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'skip:no-scope', { stepId: 'root' }));
1081
+ return;
1082
+ }
1083
+ if (ctx.doc.shadow) {
1084
+ // Record-only: the same `shadow` flag was passed to `decide` above, so the
1085
+ // recorded potential matches the policy that produced it. No queue entry
1086
+ // and no budget. Projection is a separate switch and still runs afterwards
1087
+ // (design §5.2-5); this branch only stops the substitution side.
1088
+ await appendReceipt(deps, ledgerEntry(ctx, 'shadow', 'ok', {
1089
+ decision: 'commit',
1090
+ candidateId,
1091
+ // The executed tool is the model's call; the candidate's tool is what
1092
+ // the gate decided. The shadow report's per-family hit rate must use
1093
+ // the latter (the shadow receipt's `tool` is the former).
1094
+ candidateTool: candidate.tool,
1095
+ admitted: admittedFor(deps, ctx.sessionId, plan, selectorOverhead),
1096
+ whitelisted: SUBSTITUTION_WHITELIST.has(candidate.tool),
1097
+ stepId: 'root',
1098
+ args: boundArgs,
1099
+ // G2: the plan and the guards are why this candidate was legitimate.
1100
+ ...substitutionEvidence(plan.goal, candidate.guards),
1101
+ }));
1102
+ return;
1103
+ }
1104
+ const step = clockStepOf(deps, ctx.sessionId);
1105
+ if (step === undefined) {
1106
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-step' }));
1107
+ return;
1108
+ }
1109
+ if (deps.queue == null || typeof deps.queue.set !== 'function') {
1110
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-queue' }));
1111
+ return;
1112
+ }
1113
+ if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {
1114
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }));
1115
+ return;
1116
+ }
1117
+ if (!takeBudget(deps, ctx.sessionId)) {
1118
+ // No entry is ours to clear here: this invocation enqueued nothing, so a
1119
+ // live entry belongs to another call in the step (review F2).
1120
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }));
1121
+ return;
1122
+ }
1123
+ const callId = callIdFor(ctx.sessionId, ctx.turn, step, candidateId);
1124
+ const entry = {
1125
+ callId,
1126
+ candidateId,
1127
+ // The candidate's tool name identifies the call; the executable args are
1128
+ // the *decision's* bound tree, never the plan's `$public` template.
1129
+ name: candidate.tool,
1130
+ args: boundArgs,
1131
+ turn: ctx.turn,
1132
+ step,
1133
+ // The plan is one-shot (cleared above), so the evidence must travel with
1134
+ // the entry: the synth-time receipt is written after this turn's plan is
1135
+ // gone, and the settled receipt only knows the candidate id.
1136
+ evidence: substitutionEvidence(plan.goal, candidate.guards),
1137
+ };
1138
+ try {
1139
+ deps.queue.set(ctx.sessionId, entry);
1140
+ }
1141
+ catch {
1142
+ await appendReceipt(deps,
1143
+ // The step was already taken and this receipt is the only evidence that
1144
+ // it bought no substitution; a throwing queue must not also hide the cost.
1145
+ ledgerEntry(ctx, 'skip', 'substitution-unavailable', {
1146
+ stepId: 'root',
1147
+ reason: 'queue-failed',
1148
+ budget: 'spent',
1149
+ }));
1150
+ return;
1151
+ }
1152
+ markSubstituted(deps, ctx.sessionId, candidateId);
1153
+ // Anchors name the templates the executed call was bound from: the decision's
1154
+ // args are already expanded, so only the plan copy still carries the
1155
+ // `$public` references. That tree is inspected here, never dispatched.
1156
+ setAnchors(deps, ctx, plan.steps.find((step) => step.id === candidateId)?.args ?? boundArgs);
1157
+ return;
1158
+ }
1159
+ /** The session's plan, or `undefined` when none is known (or the map is foreign). */
1160
+ function safePlan(deps, sessionId) {
1161
+ try {
1162
+ const plans = deps.plans;
1163
+ if (plans == null || typeof plans.get !== 'function')
1164
+ return undefined;
1165
+ const plan = plans.get(sessionId);
1166
+ if (plan === undefined || plan === null)
1167
+ return undefined;
1168
+ // A spent plan has nothing left to decide; skipping the call also avoids a
1169
+ // `guard-trivial` receipt on every later tool call of the turn.
1170
+ if (!Array.isArray(plan.steps) || plan.steps.length === 0)
1171
+ return undefined;
1172
+ return plan;
1173
+ }
1174
+ catch {
1175
+ return undefined;
1176
+ }
1177
+ }
1178
+ // ---------------------------------------------------------------------------
1179
+ // Projection
1180
+ // ---------------------------------------------------------------------------
1181
+ /** The text projection may replace, or `undefined` when it must stay intact. */
1182
+ function projectionTargetOf(decision, receipt, result) {
1183
+ // A `value` replacement cannot be combined with `content`: the host throws a
1184
+ // TypeError for both, which would replace the tool result with an error.
1185
+ if (Object.hasOwn(decision, 'value'))
1186
+ return undefined;
1187
+ if (decision.kind !== 'accept')
1188
+ return undefined;
1189
+ if (Object.hasOwn(decision, 'content')) {
1190
+ const content = decision.content;
1191
+ if (!Array.isArray(content))
1192
+ return undefined;
1193
+ // Replacing a multi-block result with one text block is only lossless when
1194
+ // every block is text; an image or file block must stay where it is.
1195
+ if (!content.every((block) => textBlock(block)))
1196
+ return undefined;
1197
+ return canonicalise(content, false).text;
1198
+ }
1199
+ const content = result?.content;
1200
+ if (content !== undefined && !(Array.isArray(content) && content.every((block) => textBlock(block)))) {
1201
+ return undefined;
1202
+ }
1203
+ return receipt.text;
1204
+ }
1205
+ /** Whether a block is a text block this hook can fold into one string. */
1206
+ function textBlock(block) {
1207
+ return typeof block === 'object' && block !== null && block.type === 'text';
1208
+ }
1209
+ /** The estimator, or `undefined` when none is wired (projection then stays off). */
1210
+ function estimatorOf(deps) {
1211
+ const estimate = deps.estimateText;
1212
+ return typeof estimate === 'function' ? estimate : undefined;
1213
+ }
1214
+ /** One estimate, sanitised: a non-finite or throwing result means "cannot price". */
1215
+ function safeEstimate(estimate, text) {
1216
+ try {
1217
+ const value = estimate(text);
1218
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
1219
+ }
1220
+ catch {
1221
+ return undefined;
1222
+ }
1223
+ }
1224
+ /**
1225
+ * The replay horizon in effect for one projection decision, pinned on its receipt.
1226
+ *
1227
+ * `status` applies `(1 + horizon)` to every projection's saving. Reading one
1228
+ * current horizon at status time re-valued receipts from other sessions and
1229
+ * other moments whenever the cross-session minimum moved, so a historical net
1230
+ * saving jumped when an unrelated session started or ended. The receipt now
1231
+ * carries the horizon its decision was made under; `status` only falls back to
1232
+ * the current horizon for receipts that predate the field, and says how many
1233
+ * those were.
1234
+ *
1235
+ * The runtime horizon is design §5.3's `min(config, mean of the session's last
1236
+ * historyTurns turns)`. Its instance lives in `src/index.ts` (`apply` builds
1237
+ * one `RuntimeStepHorizon`), so the decision path can only read it through
1238
+ * {@link HookDeps.horizonFor}; until that one line is wired, the resolved
1239
+ * config's `horizonSteps` is the value in effect. A throwing or malformed
1240
+ * answer falls back the same way, never to a fabricated number.
1241
+ */
1242
+ function projectionHorizonOf(deps, sessionId) {
1243
+ try {
1244
+ const live = deps.horizonFor?.(sessionId);
1245
+ if (typeof live === 'number' && Number.isFinite(live) && live >= 0)
1246
+ return Math.floor(live);
1247
+ }
1248
+ catch {
1249
+ // A foreign horizon is evidence, never a reason to lose the receipt.
1250
+ }
1251
+ const raw = deps.config?.horizonSteps;
1252
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0
1253
+ ? Math.floor(raw)
1254
+ : DEFAULT_CONFIG.horizonSteps;
1255
+ }
1256
+ /** `projection-skipped:<reason>`; `projectApply` already prefixes one reason. */
1257
+ function projectionSkipCode(reason) {
1258
+ return reason.startsWith('projection-skipped:') ? reason : `projection-skipped:${reason}`;
1259
+ }
1260
+ /**
1261
+ * Project the receipt that will enter history.
1262
+ *
1263
+ * Shadow mode only prices the receipt: it writes a `{kind:'shadow'}` record and
1264
+ * returns the decision untouched, so nothing the model sees changes. Apply mode
1265
+ * persists the canonical original through the host spill backend and replaces
1266
+ * the content only after `projectApply`'s own guards pass; a skip leaves the
1267
+ * decision intact. The regression guard (`assembled.length < original.length`)
1268
+ * lives inside `projectApply`; here only pricing and evidence are added.
1269
+ *
1270
+ * The live visibility recheck runs before either mode. The listener gate reads
1271
+ * the cached judgement from prompt assembly time; a workspace disabled since
1272
+ * then must not have its receipt clipped or accounted, in shadow or apply mode.
1273
+ */
1274
+ async function projectDecision(deps, receipt, decision, ctx) {
1275
+ const mode = ctx.doc.projection;
1276
+ if (mode === 'off')
1277
+ return decision;
1278
+ // Projection gets the same live recheck substitution performs. The cached
1279
+ // judgement passed the listener gate, but the prompt was assembled before
1280
+ // the tool ran: `boost` may have disabled the workspace in between, and a
1281
+ // projection changes what the model sees. The cache alone must not authorize
1282
+ // that (design §5.5).
1283
+ if (!substitutableSession(deps, ctx.sessionId, ctx.doc))
1284
+ return decision;
1285
+ const toolName = ctx.exec.name;
1286
+ const family = toolName === undefined ? undefined : familyOf(toolName);
1287
+ if (family === undefined) {
1288
+ // `edit`, `web_fetch`, `todo_write`, `boost` and friends are by-design
1289
+ // passes, not mapper gaps. Only a decorated (`mcp__*`) name means the
1290
+ // mapper may have missed a real family, so only that is counted.
1291
+ if (typeof toolName === 'string' && toolName.startsWith('mcp__')) {
1292
+ try {
1293
+ deps.projectionCounters?.unknownFamily(toolName);
1294
+ }
1295
+ catch {
1296
+ // A counter is evidence, never a precondition.
1297
+ }
1298
+ }
1299
+ return decision;
1300
+ }
1301
+ const target = projectionTargetOf(decision, receipt, ctx.result);
1302
+ if (target === undefined)
1303
+ return decision;
1304
+ // Clipping does not need a token meter; only its accounting does (design
1305
+ // §9). With no estimator the replacement still happens, but the receipts
1306
+ // carry `estimate:'unknown'` and no fabricated numbers.
1307
+ const estimate = estimatorOf(deps);
1308
+ try {
1309
+ if (mode === 'shadow') {
1310
+ const outcome = await projectShadow({
1311
+ text: target,
1312
+ isError: receipt.isError,
1313
+ family,
1314
+ cfg: deps.config,
1315
+ // Same sanitiser as the apply path: a throwing or non-finite host
1316
+ // estimate must never become `null` in the shadow account. Without a
1317
+ // meter the NaN makes `projectShadow` record an unpriced event.
1318
+ estimate: (text) => estimate === undefined ? Number.NaN : (safeEstimate(estimate, text) ?? Number.NaN),
1319
+ });
1320
+ if (outcome.kind === 'shadow') {
1321
+ const priced = outcome.before !== undefined &&
1322
+ outcome.after !== undefined &&
1323
+ outcome.saved !== undefined;
1324
+ await appendReceipt(deps, ledgerEntry(ctx, 'shadow', 'projection-shadow', {
1325
+ decision: 'projection',
1326
+ unit: 'raw',
1327
+ // The shadow ledger's one-time figure is replayable with the same
1328
+ // horizon as the applied one; pinning it keeps the two comparable.
1329
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1330
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1331
+ ...(priced
1332
+ ? {
1333
+ before: outcome.before,
1334
+ after: outcome.after,
1335
+ saved_projection_tokens: outcome.saved,
1336
+ }
1337
+ : {}),
1338
+ estimate: priced ? (deps.estimateKind ?? 'unknown') : 'unknown',
1339
+ }));
1340
+ }
1341
+ return decision;
1342
+ }
1343
+ const { content, outcome } = await projectApply({
1344
+ text: target,
1345
+ isError: receipt.isError,
1346
+ family,
1347
+ cfg: deps.config,
1348
+ sessionId: ctx.sessionId,
1349
+ toolName: ctx.exec.name ?? 'tool',
1350
+ callId: typeof ctx.exec.callId === 'string' ? ctx.exec.callId : undefined,
1351
+ label: family,
1352
+ spill: deps.spill,
1353
+ formatFooter: await resolveFooterFormatter(deps),
1354
+ });
1355
+ if (outcome.kind === 'applied') {
1356
+ // Remember the artifact's only address: this is what makes a later read
1357
+ // of it a counted retrieval instead of a free one (design §5.3).
1358
+ if (outcome.locator !== undefined)
1359
+ deps.retrievals?.record(ctx.sessionId, outcome.locator);
1360
+ // The applied event is always recorded; only the token figures depend on
1361
+ // the meter. `estimate` is always present and names the producer
1362
+ // (`deps.estimateKind`, defaulting to `'unknown'`), never a guess.
1363
+ // One-time `before`/`after`/`saved_projection_tokens` are the
1364
+ // authoritative names (§5.3); `status` applies the replay factor once to
1365
+ // the aggregate, never per receipt. `horizon_steps` is the horizon this
1366
+ // decision was made under, so a later status cannot re-value it.
1367
+ const before = estimate === undefined ? undefined : safeEstimate(estimate, target);
1368
+ const after = estimate === undefined ? undefined : safeEstimate(estimate, content);
1369
+ if (before !== undefined && after !== undefined) {
1370
+ await appendReceipt(deps, ledgerEntry(ctx, 'projection', 'projected', {
1371
+ unit: 'raw',
1372
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1373
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1374
+ before,
1375
+ after,
1376
+ saved_projection_tokens: before - after,
1377
+ estimate: deps.estimateKind ?? 'unknown',
1378
+ }));
1379
+ }
1380
+ else {
1381
+ await appendReceipt(deps, ledgerEntry(ctx, 'projection', 'projected', {
1382
+ unit: 'raw',
1383
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1384
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1385
+ estimate: 'unknown',
1386
+ }));
1387
+ }
1388
+ return { ...decision, content: [{ type: 'text', text: content }] };
1389
+ }
1390
+ if (outcome.kind === 'skipped' &&
1391
+ outcome.reason !== undefined &&
1392
+ PROJECTION_DEGRADATIONS.has(outcome.reason)) {
1393
+ // `projection-skipped:no-spill` is the receipt behind
1394
+ // `boost status`'s `ERR_HOST_NO_SPILL`; the other degradation codes
1395
+ // exist for the same audit trail. Ordinary "not worth it" skips are
1396
+ // deterministic policy, not a per-call decision (design §5.3), so they
1397
+ // write nothing.
1398
+ // A skip projected nothing, so it is a `skip` receipt, not a
1399
+ // `projection` one. `kind:'projection'` is not a promise of numeric
1400
+ // fields: the meterless apply branch above always writes
1401
+ // `estimate:'unknown'` but omits `before`/`after`/
1402
+ // `saved_projection_tokens` entirely (design §9), and consumers must
1403
+ // treat those as unpriced rather than assume the numbers exist.
1404
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', projectionSkipCode(outcome.reason)));
1405
+ }
1406
+ return decision;
1407
+ }
1408
+ catch {
1409
+ // `projectApply`/`projectShadow` already contain their own host calls; this
1410
+ // is the last belt for a bug in either of them.
1411
+ return decision;
1412
+ }
1413
+ }
1414
+ /**
1415
+ * The decision + projection stage.
1416
+ *
1417
+ * Both seams live in one place so the listener's order is visible in one
1418
+ * function: decide, then the double-projection guard, then project. A shadow
1419
+ * substitution does not stop the projection: the two switches are independent
1420
+ * (design §5.2-5), and in projection-shadow mode the projection writes only
1421
+ * its accounting line.
1422
+ */
1423
+ async function applyDecision(deps, decision, ctx) {
1424
+ // Projection below runs for a shadow commit too: the decision side never
1425
+ // suppresses the projection ledger.
1426
+ await decideSubstitution(deps, ctx);
1427
+ // Second-projection guard. The host spiller registers with `{ prepend: true }`:
1428
+ // it calls `next()` and adds its footer to that decision *after* this listener
1429
+ // returns. So this check sees only the footer an inner listener already wrote,
1430
+ // never the host's own; it must not be read as full double-spill detection.
1431
+ // Both the receiver as it arrived and the decision that will enter history are
1432
+ // checked (design §5.4).
1433
+ if (await isAlreadySpilled(deps, ctx.receipt.text))
1434
+ return decision;
1435
+ const downstreamText = decisionTextOf(decision) ?? ctx.receipt.text;
1436
+ if (downstreamText !== ctx.receipt.text && await isAlreadySpilled(deps, downstreamText)) {
1437
+ return decision;
1438
+ }
1439
+ return projectDecision(deps, ctx.receipt, decision, ctx);
1440
+ }
1441
+ // ---------------------------------------------------------------------------
1442
+ // The two listeners
1443
+ // ---------------------------------------------------------------------------
1444
+ /**
1445
+ * The `tools/post-execute` body.
1446
+ *
1447
+ * `next()` runs first, exactly like the host's own spill policy: a listener
1448
+ * either returns a decision or calls `next()` and returns its result, and
1449
+ * bypassing it would silently drop the listeners mounted after this one. The
1450
+ * fixed order that follows is `scope gate → canonicalise → invalidate →
1451
+ * substitution decision → double-projection guard → projection → return the
1452
+ * decision` (design §5.2-7/§5.4-5).
1453
+ *
1454
+ * Everything after `next()` is contained: the host turns a throwing
1455
+ * `post-execute` listener into an error result and the real tool output is
1456
+ * lost. A failure in our own wiring must therefore return the decision as it
1457
+ * arrived, never a thrown error.
1458
+ */
1459
+ async function postExecute(deps, state, exec, result, next) {
1460
+ const decision = await next();
1461
+ // A PTC inner call traverses this waterfall with `parent` set. Its result
1462
+ // belongs to the enclosing `run_code` step, not to a step of its own: it must
1463
+ // not become `root`, drive a decision, consume the outer plan or overwrite the
1464
+ // outer anchors. Leaving it untouched is what keeps a plan from being decided
1465
+ // from an inner receipt.
1466
+ if (exec !== undefined && exec.parent !== undefined)
1467
+ return decision;
1468
+ if (exec?.agent === undefined) {
1469
+ await appendSkipNoScope(deps.receipts, exec);
1470
+ return decision;
1471
+ }
1472
+ // Exposure gate: an out-of-scope session pays nothing. This is the same
1473
+ // cached judgement the protocol section reads; a miss is false (fail-closed,
1474
+ // design §5.5).
1475
+ const sessionId = sessionIdOf(exec);
1476
+ if (sessionId === undefined) {
1477
+ // The agent exists but carries no usable session id, so neither the scope
1478
+ // gate nor the retrieval ledger can attribute this call. Fail closed and
1479
+ // keep the pass visible; the no-agent branch above does the same.
1480
+ await appendSkipNoScope(deps.receipts, exec);
1481
+ return decision;
1482
+ }
1483
+ // A substituted call denied by `tools/pre-execute` (approval or sandbox)
1484
+ // returns a post-result without invoking `tools/execute`, while post-execute
1485
+ // still runs. Matching the call id here clears the pending entry even though
1486
+ // no dispatch mapping exists, so the substitution is not re-synthesized on
1487
+ // every later step of the turn.
1488
+ clearMatchingPending(deps, sessionId, exec);
1489
+ // Detect the retrieval before the visibility gate (a projected receipt
1490
+ // already consumed context regardless of today's scope), but write its cost
1491
+ // only after projection, when the final visible content is known (review I3).
1492
+ const retrieval = pendingRetrievalOf(deps, exec, sessionId);
1493
+ if (!isActiveSession(deps, sessionId)) {
1494
+ if (retrieval !== undefined) {
1495
+ const arrival = canonicalise(result?.content ?? [], result?.isError === true);
1496
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, arrival.text);
1497
+ }
1498
+ await appendSkipNoScope(deps.receipts, exec, sessionId, clockTurnOf(deps, sessionId) ?? 0);
1499
+ return decision;
1500
+ }
1501
+ try {
1502
+ // Canonicalise the original receiver, not a downstream replacement: guards
1503
+ // and the selector read the receipt as it arrived.
1504
+ const receipt = canonicalise(result?.content ?? [], result?.isError === true);
1505
+ const turn = clockTurnOf(deps, sessionId) ?? 0;
1506
+ // The receipt map is the gate's memory for this turn. `begin` folds the
1507
+ // previous turn away (anchors live in the store, receipts and in-flight
1508
+ // dispatches here), then the arriving receipt becomes `root` and, if it is
1509
+ // the call we substituted, also becomes the candidate's receipt.
1510
+ const { rolledOver } = state.begin(sessionId, turn);
1511
+ if (rolledOver) {
1512
+ // A pending entry and its decision-time usage mark from the previous turn
1513
+ // can never match a call in this one, so both are dead weight; the reset
1514
+ // path does the same mid-turn (F2). The mark is settled **without** a
1515
+ // settlement receipt, exactly like `resetInvalidatedPending` and
1516
+ // `applyAbandon`: no substitution ran, so there is no saving to report.
1517
+ // This branch is reachable with a live mark because a parallel tool
1518
+ // result can land after the host advanced the turn but before this turn's
1519
+ // first `llm/stream`, so the old "the stream always runs first" argument
1520
+ // does not hold (D1).
1521
+ settleDiscarded(deps, sessionId);
1522
+ clearAnchors(deps, sessionId);
1523
+ clearPending(deps, sessionId);
1524
+ // The plan map is normally reconciled by `SessionRuntime.notePlanTurn` on
1525
+ // the first real request of a turn. If that request has not run yet, a
1526
+ // plan still in the map belongs to the previous turn and would fire
1527
+ // against this new-turn receipt; drop it. When the request did run,
1528
+ // `notePlanTurn` reports false and the plan present was parsed by that
1529
+ // request's response: keep it, because clearing would discard a valid
1530
+ // new-turn plan.
1531
+ let planForThisTurn = false;
1532
+ try {
1533
+ planForThisTurn = deps.sessions?.notePlanTurn(sessionId, turn) === false;
1534
+ }
1535
+ catch {
1536
+ planForThisTurn = false;
1537
+ }
1538
+ if (!planForThisTurn)
1539
+ clearPlan(deps, sessionId);
1540
+ }
1541
+ state.recordRoot(sessionId, turn, receipt);
1542
+ fileDispatchedReceipt(state, exec, sessionId, turn, receipt);
1543
+ // Conservative local invalidation check. The tool-result path cannot see
1544
+ // the host pruner (it rewrites session surface nodes, not this waterfall)
1545
+ // or compaction, so only the **marker** branch is meaningful here: it
1546
+ // catches a receipt whose tool output itself carries the pruner literal.
1547
+ // The anchor comparison needs the anchored receipt's current text and
1548
+ // belongs to the model-request path (23c); running it here would compare a
1549
+ // different call's text and fire a false compaction-reset after every
1550
+ // commit (review F1). A hit only abandons the decision, which is safe.
1551
+ const pending = pendingAnchorsOf(deps, sessionId);
1552
+ // `!= null` rather than `!== undefined`: a foreign store can hand back a
1553
+ // null, and dereferencing it would throw out of the hook.
1554
+ if (pending != null) {
1555
+ const reset = markerResetOf(pending, receipt.text);
1556
+ if (reset !== undefined) {
1557
+ await resetInvalidatedPending(deps, exec, sessionId, turn, pending, reset);
1558
+ if (retrieval !== undefined) {
1559
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, receipt.text);
1560
+ }
1561
+ return decision;
1562
+ }
1563
+ }
1564
+ const ctx = {
1565
+ sessionId,
1566
+ exec,
1567
+ receipt,
1568
+ doc: await scopeDocOf(deps),
1569
+ result,
1570
+ state,
1571
+ turn,
1572
+ retrievalCall: retrieval !== undefined,
1573
+ };
1574
+ const outgoing = await applyDecision(deps, decision, ctx);
1575
+ if (retrieval !== undefined) {
1576
+ // The retrieval receipt's content figure must price what enters history
1577
+ // after projection, not the raw result it arrived with.
1578
+ const visible = decisionTextOf(outgoing) ?? receipt.text;
1579
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, visible);
1580
+ }
1581
+ return outgoing;
1582
+ }
1583
+ catch {
1584
+ // Never lose the tool's real output to a wiring bug in this listener.
1585
+ return decision;
1586
+ }
1587
+ }
1588
+ /**
1589
+ * Drop a pending entry whose call id matches the arriving result.
1590
+ *
1591
+ * The execute hook clears the entry when it inspects an accepted or rejected
1592
+ * dispatch, but a call denied by `tools/pre-execute` never reaches that hook;
1593
+ * post-execute is then the only observer that knows the substituted call is
1594
+ * over. A different call id is an ordinary call and leaves the entry alone.
1595
+ */
1596
+ function clearMatchingPending(deps, sessionId, exec) {
1597
+ const pending = peekPending(deps, sessionId);
1598
+ if (pending === undefined)
1599
+ return;
1600
+ if (typeof exec.callId !== 'string' || exec.callId !== pending.callId)
1601
+ return;
1602
+ clearPending(deps, sessionId);
1603
+ }
1604
+ /** File an executed candidate's receipt under its plan id, consuming the dispatch record. */
1605
+ function fileDispatchedReceipt(state, exec, sessionId, turn, receipt) {
1606
+ const callId = exec?.callId;
1607
+ if (typeof callId !== 'string')
1608
+ return;
1609
+ const candidateId = state.takeDispatch(sessionId, turn, callId);
1610
+ if (candidateId === undefined)
1611
+ return;
1612
+ state.recordCandidate(sessionId, turn, candidateId, receipt);
1613
+ }
1614
+ /** The host's `ToolExecutionResult` failure branch for a refused dispatch. */
1615
+ function dispatchFailure(message) {
1616
+ return {
1617
+ isError: true,
1618
+ error: {
1619
+ message,
1620
+ info: { name: 'DispatchRejectedError', code: 'dispatch-rejected' },
1621
+ },
1622
+ content: [{ type: 'text', text: `Error: ${message}` }],
1623
+ };
1624
+ }
1625
+ /** Record one refused dispatch; a receipt write never changes the verdict. */
1626
+ async function appendDispatchRejected(deps, exec, entry, sessionId) {
1627
+ await appendReceipt(deps, {
1628
+ version: 1,
1629
+ ts: new Date().toISOString(),
1630
+ sessionId,
1631
+ turn: clockTurnOf(deps, sessionId) ?? 0,
1632
+ stepId: 'root',
1633
+ kind: 'skip',
1634
+ code: 'dispatch-rejected',
1635
+ tool: exec.name,
1636
+ callId: typeof exec.callId === 'string' ? exec.callId : undefined,
1637
+ candidateId: entry.candidateId,
1638
+ // The refused call's own args, not the pending decision's: the operator
1639
+ // needs to see exactly what the host was asked to run.
1640
+ args: exec.arguments,
1641
+ preview: callPreview(exec.name, exec.arguments),
1642
+ });
1643
+ }
1644
+ /**
1645
+ * The inspect half of `tools/execute`: no `next()` is called here, so a throw
1646
+ * can never cause the dispatch to run twice.
1647
+ *
1648
+ * Every operation is contained (the lookup, the clearing, the receipt write),
1649
+ * so the only throw this function can produce is a bug of its own; the caller
1650
+ * then fails open.
1651
+ */
1652
+ async function inspectDispatch(deps, exec) {
1653
+ const sessionId = sessionIdOf(exec);
1654
+ if (sessionId === undefined)
1655
+ return { kind: 'next' };
1656
+ const entry = peekPending(deps, sessionId);
1657
+ if (entry === undefined)
1658
+ return { kind: 'next' };
1659
+ const reject = async (message) => {
1660
+ clearPending(deps, sessionId);
1661
+ await appendDispatchRejected(deps, exec, entry, sessionId);
1662
+ return { kind: 'reject', message };
1663
+ };
1664
+ // A different call id is an ordinary call, not tampering: the host assigns
1665
+ // call ids, so only a call that carries the id we chose is the dispatch under
1666
+ // inspection. Rejecting the rest would lose a legitimate tool's output (F2).
1667
+ if (typeof exec.callId !== 'string' || exec.callId !== entry.callId) {
1668
+ return { kind: 'next' };
1669
+ }
1670
+ // `rejectIfTampered` compares name and parsed arguments only; the call id was
1671
+ // compared above.
1672
+ if (rejectIfTampered(exec, entry).reject) {
1673
+ return reject('dsh-boost refused a substituted call: the dispatched arguments do not match the pending decision');
1674
+ }
1675
+ // Accept path: the entry has done its job, so drop it before dispatching.
1676
+ clearPending(deps, sessionId);
1677
+ return { kind: 'accept', sessionId, callId: entry.callId, candidateId: entry.candidateId };
1678
+ }
1679
+ /**
1680
+ * The `tools/execute` hook body: refuse a tampered substitution.
1681
+ *
1682
+ * With no pending entry the plugin is not substituting this call, so `next()`
1683
+ * runs untouched. The entry describes the dispatch we synthesised: a call that
1684
+ * carries the **same** call id is inspected, compared with the decision, and
1685
+ * the entry is cleared on both the accept and the reject path so it cannot
1686
+ * outlive its dispatch. A call with a **different** call id is an ordinary call
1687
+ * — the host assigns ids — and passes through without touching the entry
1688
+ * (review F2: rejecting it would lose a legitimate tool's output). On the
1689
+ * accept path the call id is remembered so the following `post-execute` can
1690
+ * file the receipt under its candidate id.
1691
+ *
1692
+ * The mount fails open on an internal error (the design's fail-closed means
1693
+ * "pass through, do not substitute", never "intercept"): a broken queue must
1694
+ * not block every tool call in the process.
1695
+ */
1696
+ async function executeHook(deps, state, exec, next) {
1697
+ let outcome;
1698
+ try {
1699
+ outcome = await inspectDispatch(deps, exec);
1700
+ }
1701
+ catch {
1702
+ return next();
1703
+ }
1704
+ if (outcome.kind === 'reject')
1705
+ return dispatchFailure(outcome.message);
1706
+ if (outcome.kind === 'accept') {
1707
+ try {
1708
+ state.recordDispatch(outcome.sessionId, clockTurnOf(deps, outcome.sessionId) ?? 0, outcome.callId, outcome.candidateId);
1709
+ }
1710
+ catch {
1711
+ // Losing the mapping costs the candidate receipt, not this call.
1712
+ }
1713
+ }
1714
+ return next();
1715
+ }
1716
+ // ---------------------------------------------------------------------------
1717
+ // Registration
1718
+ // ---------------------------------------------------------------------------
1719
+ /** Mount the projection waterfall. */
1720
+ function registerPostExecute(ctx, deps, state) {
1721
+ ctx.on('tools/post-execute', (exec, result, next) => postExecute(deps, state, exec, result, next));
1722
+ }
1723
+ /** Mount the model-request waterfall; the hook function is built once per registration. */
1724
+ function registerLlmStream(ctx, deps) {
1725
+ const hook = streamHook(deps);
1726
+ ctx.on('llm/stream', (options, next) => hook(options, next));
1727
+ }
1728
+ /** Mount the dispatch waterfall. */
1729
+ function registerExecute(ctx, deps, state) {
1730
+ ctx.on('tools/execute', (exec, next) => executeHook(deps, state, exec, next));
1731
+ }
1732
+ /** Mount the protocol section, whose provider stays synchronous and per-agent. */
1733
+ function registerProtocolSection(ctx, scope) {
1734
+ ctx.systemPrompt.section({
1735
+ name: PROTOCOL_NAME,
1736
+ order: PROTOCOL_ORDER,
1737
+ interpolate: false,
1738
+ text: (context) => protocolText(scope, context),
1739
+ });
1740
+ }
1741
+ /**
1742
+ * Register the plugin's four host integration points.
1743
+ *
1744
+ * The prompt section is registered first on purpose: it is the only mount that
1745
+ * rejects a duplicate name, so a second `apply` aborts here before any event
1746
+ * hook is mounted twice (the host turns a duplicate section into an error, and
1747
+ * `apply` treats that as "already mounted"). Registering it last would leave
1748
+ * three live duplicate listeners behind.
1749
+ *
1750
+ * One `ReceiptSessionState` belongs to the whole registration: the execute
1751
+ * mount writes the in-flight call mapping and the post-execute mount consumes
1752
+ * it, so the two waterfalls must share it.
1753
+ *
1754
+ * `scope`, `receipts`, `anchors` and `resolveSession` are required by
1755
+ * `HookDeps`, but they are still checked at the point of use: a host wiring the
1756
+ * plugin without one of the optional pieces still gets the four mount points,
1757
+ * and every degraded path is fail-closed instead of throwing during
1758
+ * registration.
1759
+ */
1760
+ export function registerHooks(ctx, deps) {
1761
+ const state = deps.sessionState ?? new ReceiptSessionState();
1762
+ // Publish the instance we created. `clearSession` and Task 23c-2's session-end
1763
+ // wiring reach the state through `deps.sessionState`; a caller that omits it
1764
+ // (the plan's 23c-2 assembly list does) would otherwise leave the created
1765
+ // receipt/dispatch maps unreachable and leaked per session.
1766
+ deps.sessionState = state;
1767
+ // The logger is a host service the caller already has; publishing it here
1768
+ // keeps the degradation warnings reachable without widening every caller's
1769
+ // deps literal. A deps object that already names one keeps it.
1770
+ deps.logger ??= ctx.logger;
1771
+ registerProtocolSection(ctx, deps.scope);
1772
+ registerPostExecute(ctx, deps, state);
1773
+ registerLlmStream(ctx, deps);
1774
+ registerExecute(ctx, deps, state);
1775
+ }
1776
+ //# sourceMappingURL=post-execute.js.map