dsh-boost 0.1.0 → 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.
Files changed (54) hide show
  1. package/README.en.md +184 -70
  2. package/README.md +148 -59
  3. package/dist/gate/decide.js +33 -2
  4. package/dist/gate/decide.js.map +1 -1
  5. package/dist/hooks/llm-stream.js +242 -89
  6. package/dist/hooks/llm-stream.js.map +1 -1
  7. package/dist/hooks/post-execute.js +282 -25
  8. package/dist/hooks/post-execute.js.map +1 -1
  9. package/dist/hooks/session-state.js +18 -8
  10. package/dist/hooks/session-state.js.map +1 -1
  11. package/dist/host/root.js +22 -1
  12. package/dist/host/root.js.map +1 -1
  13. package/dist/index.js +494 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/scope/doc.js.map +1 -1
  16. package/dist/scope/store.js +24 -9
  17. package/dist/scope/store.js.map +1 -1
  18. package/dist/tools/boost.js +37 -4
  19. package/dist/tools/boost.js.map +1 -1
  20. package/dist/types.d.ts +18 -1
  21. package/dist/types.js.map +1 -1
  22. package/package.json +10 -6
  23. package/dist/admission/fixed-cost.d.ts +0 -23
  24. package/dist/admission/ledger.d.ts +0 -113
  25. package/dist/admission/retrieval.d.ts +0 -65
  26. package/dist/admission/usage.d.ts +0 -75
  27. package/dist/config.d.ts +0 -43
  28. package/dist/gate/binding.d.ts +0 -113
  29. package/dist/gate/decide.d.ts +0 -82
  30. package/dist/gate/guard.d.ts +0 -69
  31. package/dist/gate/invalidate.d.ts +0 -112
  32. package/dist/gate/plan.d.ts +0 -86
  33. package/dist/hooks/clock.d.ts +0 -68
  34. package/dist/hooks/execute.d.ts +0 -79
  35. package/dist/hooks/llm-stream.d.ts +0 -276
  36. package/dist/hooks/pending.d.ts +0 -89
  37. package/dist/hooks/post-execute.d.ts +0 -247
  38. package/dist/hooks/session-state.d.ts +0 -158
  39. package/dist/hooks/synthesize.d.ts +0 -74
  40. package/dist/host/loader.d.ts +0 -23
  41. package/dist/host/platform.d.ts +0 -18
  42. package/dist/host/root.d.ts +0 -18
  43. package/dist/projection/apply.d.ts +0 -174
  44. package/dist/projection/canonicalise.d.ts +0 -43
  45. package/dist/projection/counters.d.ts +0 -65
  46. package/dist/projection/truncate.d.ts +0 -47
  47. package/dist/prompt/protocol.d.ts +0 -45
  48. package/dist/receipts/store.d.ts +0 -198
  49. package/dist/scope/doc.d.ts +0 -117
  50. package/dist/scope/resolve.d.ts +0 -91
  51. package/dist/scope/store.d.ts +0 -135
  52. package/dist/selector/jev.d.ts +0 -93
  53. package/dist/tools/boost.d.ts +0 -367
  54. package/dist/tools/family.d.ts +0 -26
@@ -86,7 +86,7 @@ import { DEFAULT_SCOPE, isVisible } from '../scope/doc.js';
86
86
  import { SELECTOR_SYSTEM_PROMPT, choose, selectorPromptText } from '../selector/jev.js';
87
87
  import { familyOf } from '../tools/family.js';
88
88
  import { rejectIfTampered } from './execute.js';
89
- import { receiptsStopped, sessionBudget, sessionClock, sessionUsage, settleDiscarded, streamHook, } from './llm-stream.js';
89
+ import { budgetWired, receiptsStopped, sessionBudget, sessionClock, sessionUsage, settleDiscarded, streamHook, } from './llm-stream.js';
90
90
  import { callIdFor } from './pending.js';
91
91
  import { ReceiptSessionState, appendReceipt, callPreview, clearAnchors, clearPlan, clearPending, clockTurnOf, peekPending, previewOf, } from './session-state.js';
92
92
  /**
@@ -132,6 +132,24 @@ function sessionIdOf(exec) {
132
132
  const id = exec?.agent?.session?.header?.id;
133
133
  return typeof id === 'string' ? id : undefined;
134
134
  }
135
+ /**
136
+ * Whether the host cancelled the call that produced this result.
137
+ *
138
+ * `tools/post-execute` is async, and the host contract (`dsh-tools`'
139
+ * `events.d.ts`) requires async listeners to observe `exec.signal`. A
140
+ * cancelled call's result never reaches the model, so projecting it would pay
141
+ * a spill write and persist an artifact nobody can read. The signal crosses
142
+ * the host boundary, so a malformed one means "not cancelled" rather than a
143
+ * reason to throw out of the hook.
144
+ */
145
+ function cancelled(exec) {
146
+ try {
147
+ return exec?.signal?.aborted === true;
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
135
153
  /**
136
154
  * The protocol section's synchronous provider.
137
155
  *
@@ -324,7 +342,9 @@ async function resetInvalidatedPending(deps, exec, sessionId, turn, pending, cod
324
342
  // Design §5.2-7: a reset returns to the slow path *and* empties pending, so no
325
343
  // queued substitution can fire from anchors that no longer name live text. The
326
344
  // plan is dropped too: it was written for the invalidated receipt, and leaving
327
- // it would let it fire against a later one.
345
+ // it would let it fire against a later one. A dispatch accepted for the
346
+ // invalidated decision must not settle a later mark that reuses its id.
347
+ clearAcceptedDispatch(deps, sessionId);
328
348
  settleDiscarded(deps, sessionId);
329
349
  clearAnchors(deps, sessionId);
330
350
  clearPending(deps, sessionId);
@@ -647,25 +667,37 @@ function admittedFor(deps, sessionId, plan, overheadTokens) {
647
667
  *
648
668
  * A selector call is real spend, so this check runs before the selector is
649
669
  * 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.
670
+ * `undefined` from `sessionBudget` has two different meanings (row 21): no
671
+ * budget is wired at all (no cap), or one is wired but was not lent to this
672
+ * session (exhausted, fail closed). Shadow mode never calls this: it spends no
673
+ * step.
652
674
  */
653
675
  function budgetExhausted(deps, sessionId) {
654
676
  try {
655
677
  const budget = sessionBudget(deps, sessionId);
656
- if (budget == null || typeof budget.exhausted !== 'function')
678
+ if (budget == null)
679
+ return budgetWired(deps);
680
+ if (typeof budget.exhausted !== 'function')
657
681
  return false;
658
682
  return budget.exhausted() === true;
659
683
  }
660
684
  catch {
661
- return false;
685
+ return budgetWired(deps);
662
686
  }
663
687
  }
664
- /** Claim one budget step; no budget wired means no cap is applied. */
688
+ /**
689
+ * Claim one budget step.
690
+ *
691
+ * No budget wired means no cap is applied. A wired budget that this session may
692
+ * not borrow is a refusal, not "no cap": `take` fails and the caller records
693
+ * `steps-exhausted` without enqueueing (row 21).
694
+ */
665
695
  function takeBudget(deps, sessionId) {
666
696
  try {
667
697
  const budget = sessionBudget(deps, sessionId);
668
- if (budget == null || typeof budget.take !== 'function')
698
+ if (budget == null)
699
+ return !budgetWired(deps);
700
+ if (typeof budget.take !== 'function')
669
701
  return true;
670
702
  return budget.take();
671
703
  }
@@ -682,6 +714,135 @@ function markSubstituted(deps, sessionId, candidateId) {
682
714
  // A ledger miss costs a measurement, never this call.
683
715
  }
684
716
  }
717
+ /** The session's pending usage-mark candidate, or `undefined` for a foreign ledger. */
718
+ function pendingCandidateOf(deps, sessionId) {
719
+ try {
720
+ return sessionUsage(deps, sessionId)?.pendingCandidateId();
721
+ }
722
+ catch {
723
+ return undefined;
724
+ }
725
+ }
726
+ /**
727
+ * The last substitution dispatch `tools/execute` accepted for a session.
728
+ *
729
+ * `ReceiptSessionState` records the same callId -> candidate mapping, but the
730
+ * candidate's own `tools/post-execute` consumes it when it files the receipt.
731
+ * A turn rollover needs the fact *after* that consumption: a late parallel
732
+ * tool result can roll the turn before the next real request, and the usage
733
+ * mark must then be reported instead of discarded as if nothing ran. The
734
+ * accepted dispatch is mirrored here together with the evidence that would
735
+ * otherwise be parked for the next settlement.
736
+ *
737
+ * One record per session: a later accepted dispatch (or a later synthesis)
738
+ * replaces it, a session whose usage mark is already gone drops it, and a
739
+ * rollover consumes it. The `HookDeps` key keeps two assemblies in one process
740
+ * from reading each other's sessions. The record is small and per-session; it
741
+ * is never persisted. It is also written at synthesis time through
742
+ * {@link HookDeps.noteSynthesis}: a dispatch denied by `tools/pre-execute`
743
+ * never reaches `tools/execute`, and that skipped model round must still be
744
+ * reportable at a rollover (row 27).
745
+ */
746
+ const ACCEPTED_DISPATCH = new WeakMap();
747
+ /** Mirror an accepted dispatch for a possible rollover settlement. */
748
+ function noteAcceptedDispatch(deps, sessionId, turn, candidateId, evidence) {
749
+ let bySession = ACCEPTED_DISPATCH.get(deps);
750
+ if (bySession === undefined) {
751
+ bySession = new Map();
752
+ ACCEPTED_DISPATCH.set(deps, bySession);
753
+ }
754
+ bySession.set(sessionId, {
755
+ turn,
756
+ candidateId,
757
+ ...(evidence === undefined ? {} : { evidence }),
758
+ });
759
+ }
760
+ /**
761
+ * Consume the accepted dispatch that matches `candidateId`, if any.
762
+ *
763
+ * The turn check is a staleness guard: the record that a pending mark belongs
764
+ * to was written in the turn now rolling over. A record written in the new
765
+ * turn cannot belong to it. The record's own turn is returned so the settled
766
+ * receipt pairs with the dispatch, not with the rollover (row 26).
767
+ */
768
+ function takeAcceptedDispatch(deps, sessionId, candidateId, turn) {
769
+ const bySession = ACCEPTED_DISPATCH.get(deps);
770
+ const record = bySession?.get(sessionId);
771
+ bySession?.delete(sessionId);
772
+ if (record === undefined || record.candidateId !== candidateId || record.turn === turn) {
773
+ return undefined;
774
+ }
775
+ return record.evidence === undefined
776
+ ? { turn: record.turn }
777
+ : { turn: record.turn, evidence: record.evidence };
778
+ }
779
+ /** Drop the mirrored dispatch; no pending mark is waiting to settle it. */
780
+ export function clearAcceptedDispatch(deps, sessionId) {
781
+ ACCEPTED_DISPATCH.get(deps)?.delete(sessionId);
782
+ }
783
+ /**
784
+ * Settle the usage mark at a turn rollover, reporting a substitution that ran.
785
+ *
786
+ * The ordinary path settles at the first real request after synthesis. A late
787
+ * parallel tool result can roll the turn before that request; the mark must not
788
+ * survive into the new turn, where it would pair with a request that is not the
789
+ * substitution's next one. If `tools/execute` never accepted the synthesized
790
+ * dispatch, the substitution did not run and the mark is a discard. If it did
791
+ * — or if the synthesis itself was mirrored before a `tools/pre-execute`
792
+ * denial (row 27) — the model round really was skipped: the settlement line is
793
+ * written with whatever sample the ledger holds (`'unknown'` when no after-mark
794
+ * request has run yet), with the evidence captured at dispatch, and with the
795
+ * dispatch turn the mirror recorded rather than the rollover turn (row 26), so
796
+ * the substitution is reported instead of disappearing.
797
+ */
798
+ async function settleRollover(deps, sessionId, turn) {
799
+ const candidateId = pendingCandidateOf(deps, sessionId);
800
+ if (candidateId === undefined) {
801
+ settleDiscarded(deps, sessionId);
802
+ return;
803
+ }
804
+ const dispatched = takeAcceptedDispatch(deps, sessionId, candidateId, turn);
805
+ if (dispatched === undefined) {
806
+ settleDiscarded(deps, sessionId);
807
+ return;
808
+ }
809
+ let settled;
810
+ try {
811
+ const ledger = sessionUsage(deps, sessionId);
812
+ if (ledger === undefined) {
813
+ settleDiscarded(deps, sessionId);
814
+ return;
815
+ }
816
+ settled = ledger.settle();
817
+ }
818
+ catch {
819
+ settleDiscarded(deps, sessionId);
820
+ return;
821
+ }
822
+ // The parked evidence lives in `llm-stream`'s private map and would outlive
823
+ // the mark. `settleDiscarded` is the module's idempotent cleanup: the ledger
824
+ // was settled above, so this call only forgets that evidence. It runs before
825
+ // the receipt write so the `await` cannot let a new mark be created and then
826
+ // be consumed by this cleanup.
827
+ settleDiscarded(deps, sessionId);
828
+ await appendReceipt(deps, {
829
+ version: 1,
830
+ ts: new Date().toISOString(),
831
+ sessionId,
832
+ // Row 26: the substitution happened in the dispatch turn the mirror
833
+ // recorded. Stamping the rollover turn paired a turn-1 substitution with a
834
+ // turn-2 settled line, which reads as a saving from the wrong round.
835
+ turn: dispatched.turn,
836
+ stepId: 'root',
837
+ kind: 'substitute-settled',
838
+ code: 'substitute-settled',
839
+ candidateId,
840
+ ...(dispatched.evidence ?? {}),
841
+ saved_input_tokens: settled.saved_input_tokens,
842
+ cache_hit_delta: settled.cache_hit_delta,
843
+ output_tokens: settled.output_tokens,
844
+ });
845
+ }
685
846
  /**
686
847
  * The receipt ids a candidate's `$public` templates refer to, plus `'root'`.
687
848
  *
@@ -924,12 +1085,43 @@ async function chooseCandidate(deps, ctx, candidates, receiptText) {
924
1085
  return undefined;
925
1086
  }
926
1087
  }
1088
+ // ---------------------------------------------------------------------------
1089
+ // Row 7: the step's admitted tool set
1090
+ // ---------------------------------------------------------------------------
1091
+ /**
1092
+ * Read this step's admission predicate, or `undefined` when it cannot be
1093
+ * verified.
1094
+ *
1095
+ * `view(scope)` takes the exact requesting agent; the host admits no other
1096
+ * scope. A missing `toolSet`, a missing `view` and a throwing `view` are all
1097
+ * "no evidence" and take the documented `no-toolset` path: the substitution
1098
+ * proceeds and records that it ran without admission evidence. Refusing on
1099
+ * absence would silently disable the feature on paths we cannot enumerate,
1100
+ * while a real model step always carries one (row 7).
1101
+ */
1102
+ function admissionViewOf(exec) {
1103
+ const toolSet = exec?.toolSet;
1104
+ if (toolSet == null || typeof toolSet.view !== 'function')
1105
+ return undefined;
1106
+ try {
1107
+ const view = toolSet.view(exec?.agent);
1108
+ if (view == null || typeof view.has !== 'function')
1109
+ return undefined;
1110
+ return (tool) => view.has(tool) === true;
1111
+ }
1112
+ catch {
1113
+ return undefined;
1114
+ }
1115
+ }
927
1116
  /**
928
1117
  * The substitution decision and its side effects.
929
1118
  *
930
1119
  * 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.
1120
+ * `worthSubstituting`, then `budget.take()`. The step's admission filter
1121
+ * (row 7) runs inside `decide`, before the selector is priced and before the
1122
+ * budget is taken; when its evidence is unavailable the commit still happens
1123
+ * and a `substitute-skipped:no-toolset` line records that it did.
1124
+ * Nothing below spends budget on a decision that will not be dispatched.
933
1125
  *
934
1126
  * `ask-selector` is fulfilled here since Task 23c-2: the decision carries only
935
1127
  * already-bound candidates, so the selector's choice is committed from
@@ -986,6 +1178,12 @@ async function decideSubstitution(deps, ctx) {
986
1178
  }));
987
1179
  return;
988
1180
  }
1181
+ // Row 7: this step's `ResolvedToolSet` is the host's admission set, so
1182
+ // `decide` drops a candidate whose tool it does not admit before the selector
1183
+ // or the budget is touched. Shadow mode is record-only and measures potential
1184
+ // across the whole whitelist, so it passes no admission filter.
1185
+ const admission = ctx.doc.shadow ? undefined : admissionViewOf(ctx.exec);
1186
+ const noToolset = !ctx.doc.shadow && admission === undefined;
989
1187
  let decision;
990
1188
  try {
991
1189
  decision = decide({
@@ -994,6 +1192,7 @@ async function decideSubstitution(deps, ctx) {
994
1192
  receipts: ctx.state.receiptsFor(ctx.sessionId, ctx.turn),
995
1193
  whitelist: SUBSTITUTION_WHITELIST,
996
1194
  shadow: ctx.doc.shadow,
1195
+ ...(admission === undefined ? {} : { admitted: admission }),
997
1196
  });
998
1197
  }
999
1198
  catch {
@@ -1149,6 +1348,15 @@ async function decideSubstitution(deps, ctx) {
1149
1348
  }));
1150
1349
  return;
1151
1350
  }
1351
+ // Row 7: the commit is real but the admission evidence was not available.
1352
+ // Recording it here (not at the missing-evidence point above) means the note
1353
+ // names the candidate that actually committed and only exists when one did.
1354
+ if (noToolset) {
1355
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitute-skipped:no-toolset', {
1356
+ stepId: 'root',
1357
+ candidateId,
1358
+ }));
1359
+ }
1152
1360
  markSubstituted(deps, ctx.sessionId, candidateId);
1153
1361
  // Anchors name the templates the executed call was bound from: the decision's
1154
1362
  // args are already expanded, so only the plan copy still carries the
@@ -1424,12 +1632,26 @@ async function applyDecision(deps, decision, ctx) {
1424
1632
  // Projection below runs for a shadow commit too: the decision side never
1425
1633
  // suppresses the projection ledger.
1426
1634
  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).
1635
+ // Second-projection guard. Two host shapers are outer to this listener:
1636
+ //
1637
+ // - The spill policy registers with `{ prepend: true }`: it calls `next()`
1638
+ // and adds its footer to *that* decision after this listener returns. So
1639
+ // this check sees only a footer an inner listener already wrote, never the
1640
+ // host's own; it must not be read as full double-spill detection.
1641
+ // - For `glob`/`grep`, `@deepseek-ai/dsh-tool-fs-search` is outer too
1642
+ // (`dsh-base` loads it first) and would replace an over-cap result with its
1643
+ // own spill-backed preview. The plugin pre-empts it **deliberately**:
1644
+ // `acceptedDirectCallValue` does nothing as soon as the decision carries
1645
+ // `content` (`dsh-tool-fs-search/lib/index.js:490-493`), so the projection
1646
+ // accept below wins and the host preview never runs. That is the intended
1647
+ // trade for these two families: the plugin's window triggers at 700
1648
+ // characters, far below the host's 100-path / 250-match caps, and its own
1649
+ // footer keeps the spill locator, so the host preview has nothing to add
1650
+ // to a receipt this listener already clipped. A family the plugin does not
1651
+ // project leaves the host shaper untouched.
1652
+ //
1653
+ // Both the receiver as it arrived and the decision that will enter history
1654
+ // are checked (design §5.4).
1433
1655
  if (await isAlreadySpilled(deps, ctx.receipt.text))
1434
1656
  return decision;
1435
1657
  const downstreamText = decisionTextOf(decision) ?? ctx.receipt.text;
@@ -1458,6 +1680,13 @@ async function applyDecision(deps, decision, ctx) {
1458
1680
  */
1459
1681
  async function postExecute(deps, state, exec, result, next) {
1460
1682
  const decision = await next();
1683
+ // The host cancels a call by aborting `exec.signal`; an async listener must
1684
+ // observe it before doing work whose result the model will never receive.
1685
+ // `next()` still runs — the waterfall must not drop the listeners mounted
1686
+ // after this one, and the host only replaces a successful accepted outcome
1687
+ // after they settle — but nothing after it does.
1688
+ if (cancelled(exec))
1689
+ return decision;
1461
1690
  // A PTC inner call traverses this waterfall with `parent` set. Its result
1462
1691
  // belongs to the enclosing `run_code` step, not to a step of its own: it must
1463
1692
  // not become `root`, drive a decision, consume the outer plan or overwrite the
@@ -1480,6 +1709,11 @@ async function postExecute(deps, state, exec, result, next) {
1480
1709
  await appendSkipNoScope(deps.receipts, exec);
1481
1710
  return decision;
1482
1711
  }
1712
+ // The mirrored dispatch is only meaningful while its usage mark is pending.
1713
+ // Once the mark is gone (settled by the next real request, or discarded), the
1714
+ // record is stale and a later turn's mark could reuse the candidate id.
1715
+ if (pendingCandidateOf(deps, sessionId) === undefined)
1716
+ clearAcceptedDispatch(deps, sessionId);
1483
1717
  // A substituted call denied by `tools/pre-execute` (approval or sandbox)
1484
1718
  // returns a post-result without invoking `tools/execute`, while post-execute
1485
1719
  // still runs. Matching the call id here clears the pending entry even though
@@ -1512,13 +1746,14 @@ async function postExecute(deps, state, exec, result, next) {
1512
1746
  // A pending entry and its decision-time usage mark from the previous turn
1513
1747
  // can never match a call in this one, so both are dead weight; the reset
1514
1748
  // 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);
1749
+ // settlement receipt when no substitution ran, exactly like
1750
+ // `resetInvalidatedPending` and `applyAbandon`. This branch is reachable
1751
+ // with a live mark because a parallel tool result can land after the host
1752
+ // advanced the turn but before this turn's first `llm/stream`, so the old
1753
+ // "the stream always runs first" argument does not hold (D1). When the
1754
+ // synthesized dispatch *was* accepted, the skipped model round is real:
1755
+ // `settleRollover` reports it with the sample the ledger has (row 28).
1756
+ await settleRollover(deps, sessionId, turn);
1522
1757
  clearAnchors(deps, sessionId);
1523
1758
  clearPending(deps, sessionId);
1524
1759
  // The plan map is normally reconciled by `SessionRuntime.notePlanTurn` on
@@ -1650,6 +1885,11 @@ async function appendDispatchRejected(deps, exec, entry, sessionId) {
1650
1885
  * then fails open.
1651
1886
  */
1652
1887
  async function inspectDispatch(deps, exec) {
1888
+ // Row 30: a PTC inner call carries `parent` and belongs to the enclosing
1889
+ // `run_code` step. Its host-assigned call id is not the root decision's, so
1890
+ // even a collision must not be read as our dispatch.
1891
+ if (exec.parent !== undefined)
1892
+ return { kind: 'next' };
1653
1893
  const sessionId = sessionIdOf(exec);
1654
1894
  if (sessionId === undefined)
1655
1895
  return { kind: 'next' };
@@ -1674,7 +1914,13 @@ async function inspectDispatch(deps, exec) {
1674
1914
  }
1675
1915
  // Accept path: the entry has done its job, so drop it before dispatching.
1676
1916
  clearPending(deps, sessionId);
1677
- return { kind: 'accept', sessionId, callId: entry.callId, candidateId: entry.candidateId };
1917
+ return {
1918
+ kind: 'accept',
1919
+ sessionId,
1920
+ callId: entry.callId,
1921
+ candidateId: entry.candidateId,
1922
+ evidence: entry.evidence,
1923
+ };
1678
1924
  }
1679
1925
  /**
1680
1926
  * The `tools/execute` hook body: refuse a tampered substitution.
@@ -1694,6 +1940,10 @@ async function inspectDispatch(deps, exec) {
1694
1940
  * not block every tool call in the process.
1695
1941
  */
1696
1942
  async function executeHook(deps, state, exec, next) {
1943
+ // Row 30: a PTC inner dispatch is the enclosing `run_code` step's business,
1944
+ // not this hook's; `next()` runs untouched so the inner tool still executes.
1945
+ if (exec?.parent !== undefined)
1946
+ return next();
1697
1947
  let outcome;
1698
1948
  try {
1699
1949
  outcome = await inspectDispatch(deps, exec);
@@ -1704,12 +1954,16 @@ async function executeHook(deps, state, exec, next) {
1704
1954
  if (outcome.kind === 'reject')
1705
1955
  return dispatchFailure(outcome.message);
1706
1956
  if (outcome.kind === 'accept') {
1957
+ const turn = clockTurnOf(deps, outcome.sessionId) ?? 0;
1707
1958
  try {
1708
- state.recordDispatch(outcome.sessionId, clockTurnOf(deps, outcome.sessionId) ?? 0, outcome.callId, outcome.candidateId);
1959
+ state.recordDispatch(outcome.sessionId, turn, outcome.callId, outcome.candidateId);
1709
1960
  }
1710
1961
  catch {
1711
1962
  // Losing the mapping costs the candidate receipt, not this call.
1712
1963
  }
1964
+ // The same fact, kept outside `ReceiptSessionState` because the candidate's
1965
+ // post-execute consumes that mapping before a rollover can look at it.
1966
+ noteAcceptedDispatch(deps, outcome.sessionId, turn, outcome.candidateId, outcome.evidence);
1713
1967
  }
1714
1968
  return next();
1715
1969
  }
@@ -1768,6 +2022,9 @@ export function registerHooks(ctx, deps) {
1768
2022
  // keeps the degradation warnings reachable without widening every caller's
1769
2023
  // deps literal. A deps object that already names one keeps it.
1770
2024
  deps.logger ??= ctx.logger;
2025
+ // Row 27: `llm/stream` records the synthesis through this seam, because the
2026
+ // mirror lives here and a denied dispatch never reaches `tools/execute`.
2027
+ deps.noteSynthesis ??= (sessionId, turn, candidateId, evidence) => noteAcceptedDispatch(deps, sessionId, turn, candidateId, evidence);
1771
2028
  registerProtocolSection(ctx, deps.scope);
1772
2029
  registerPostExecute(ctx, deps, state);
1773
2030
  registerLlmStream(ctx, deps);