pi-condense 2.4.3 → 2.6.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 (44) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/PRUNING.md +96 -54
  3. package/README.md +6 -1
  4. package/index.ts +28 -42
  5. package/package.json +1 -1
  6. package/src/batch-capture.test.ts +75 -1
  7. package/src/batch-capture.ts +22 -13
  8. package/src/chain-compressor.test.ts +114 -0
  9. package/src/chain-compressor.ts +29 -4
  10. package/src/chain-detector.test.ts +49 -0
  11. package/src/chain-detector.ts +7 -0
  12. package/src/chain-range-prune.test.ts +342 -7
  13. package/src/chain-range-prune.ts +161 -48
  14. package/src/commands.test.ts +31 -2
  15. package/src/commands.ts +25 -35
  16. package/src/config.test.ts +27 -1
  17. package/src/diagnostics.test.ts +114 -0
  18. package/src/diagnostics.ts +46 -0
  19. package/src/frontier.test.ts +138 -16
  20. package/src/frontier.ts +0 -1
  21. package/src/id-collision.integration.test.ts +251 -0
  22. package/src/indexer.test.ts +336 -0
  23. package/src/indexer.ts +168 -55
  24. package/src/occurrence-key.test.ts +57 -0
  25. package/src/occurrence-key.ts +36 -0
  26. package/src/orphan-sweep.test.ts +67 -0
  27. package/src/orphan-sweep.ts +40 -0
  28. package/src/oversized-spill.integration.test.ts +7 -2
  29. package/src/pruner.test.ts +471 -64
  30. package/src/pruner.ts +84 -54
  31. package/src/query-tool.test.ts +117 -0
  32. package/src/query-tool.ts +47 -31
  33. package/src/range-compression.integration.test.ts +7 -44
  34. package/src/recovery-grace.test.ts +13 -0
  35. package/src/recovery-grace.ts +12 -3
  36. package/src/spill.test.ts +108 -1
  37. package/src/spill.ts +5 -3
  38. package/src/summary-refs.test.ts +51 -1
  39. package/src/summary-refs.ts +15 -4
  40. package/src/test-support.ts +54 -0
  41. package/src/tree-browser.ts +2 -1
  42. package/src/types.ts +56 -49
  43. package/src/thinking-strip.test.ts +0 -257
  44. package/src/thinking-strip.ts +0 -83
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ Published to npm as [`pi-condense`](https://www.npmjs.com/package/pi-condense) (
7
7
  Pushing a `vX.Y.Z` tag triggers `.github/workflows/release.yml`, which runs the tests and
8
8
  publishes via OIDC trusted publishing. See `.agents/skills/release/SKILL.md`.
9
9
 
10
+ ## [2.6.0] - 2026-08-12
11
+
12
+ - **Fix: reused provider tool-call ids could delete a live turn and produce a rejected request ([#8](https://github.com/jjuraszek/pi-condense/issues/8)).** Provider `toolCallId`s (e.g. `bash_23`) are unique only within one response - some providers restart a `${tool}_${n}` counter, so the same bare id recurs across a session denoting different tool calls. `applyChainCompressions` treated the id as session-durable identity: it unioned every persisted chain entry's `droppedToolCallIds` into one session-wide set and dropped any message matching it anywhere in the array, deleting a live assistant turn that happened to reuse a compressed chain's id and orphaning its tool result - rejected outright by Anthropic (`unexpected tool_use_id found in tool_result blocks`) and Kimi K3 (unresolvable tool name), unrecoverable without hand-editing the session JSONL. The same bare ids also mis-keyed the indexer, dedup, `isSummarized`, and batch capture.
13
+ - **Positional chain ranges.** `applyChainCompressions` now resolves each persisted `ChainCompressionEntry` to an index range via `resolveRange` (`src/chain-range-prune.ts`): exactly one `user`-role message at `startUserTimestamp`, exactly one `assistant`-role message at `finalAssistantTimestamp`, `start < end` - any other outcome (including `finalAssistantTimestamp === null`) drops nothing and inserts no synthetic, fail-closed. Drops are role-restricted to `assistant` / `toolResult` / per-batch-summary messages inside the range, so `user`-role messages - including the user-role `<compressed-chain>` synthetic, which keeps re-application idempotent - and third-party `custom_message` entries survive. Per-batch summary suppression stays coverage-based (`toolCallRefs` overlap), not index-membership, because under `batchingMode: "agent-message"` the summary lands after the range. `droppedToolCallIds` is retained only as a diagnostic cross-check against the range's actual contents; the range always wins.
14
+ - **Occurrence-keyed identity.** Records are now keyed `id@resultTimestamp` (`src/occurrence-key.ts`), the discriminant being the `ToolResultMessage`'s own timestamp (not `ToolCallRecord.timestamp`, which is a batch-level timestamp computed inconsistently between the live-capture and session-rescan paths). Persisted shapes gained optional `resultTimestamp` (index records, summary refs), `newResultTimestamp` / `originalResultTimestamp` (dedup aliases), and `droppedOccurrenceKeys` (chain entries) - all optional, so pre-upgrade entries keep bare-id keying and a session spanning the upgrade retains today's behavior for its pre-upgrade half. `isSummarized` is now a strict occurrence-key lookup; the sole sanctioned bare-id fallback is `hasLegacyBareRecord`, true only for a bare id with no occurrence-keyed siblings (a mixed id fails closed on both). Spill sidecars are named from the occurrence key going forward; recovery still reads the persisted `spillPath`, so pre-upgrade blobs keep resolving.
15
+ - **Orphan sweep.** `pruneMessages` now ends with a structural post-condition, `sweepOrphanToolResults` (`src/orphan-sweep.ts`): one forward pass with **per-turn** open-call tracking (each assistant message replaces the open set rather than accumulating into it, so an id used validly early cannot license a later genuine orphan under the same reused id) removes any `toolResult` no surviving assistant opened. Provider-agnostic and structural rather than keyed to any provider's error string; reference-preserving when nothing is swept, so the no-op / prompt-cache-prefix invariant (`doc/specs/2026-08-04-pruner-noop-serialization.md`) holds.
16
+ - **Diagnostics.** New `context-prune-diagnostic` session entry (`{ kind, detail }`, kinds `unresolved-range` / `range-id-mismatch` / `orphan-sweep`) surfaces these degradations without ever entering LLM context - zero tokens, zero cache-prefix change. Deduped per `(kind, dedupKey)`, reset on `session_start` / `session_tree`. The `/pruner` status line grows a self-hiding ` · diag u<N>/m<N>/o<N>` segment (u/m/o map to the three kinds above in that order); each zero counter is omitted and the whole segment disappears when all three are zero.
17
+ - **`context_tree_query` multi-occurrence recovery.** A raw provider id that was reused now returns every matching occurrence (not just one), each labelled `id@timestamp`, chronologically; a legacy record with no `resultTimestamp` is labelled with the bare id plus an explicit `Occurrence: legacy (no resultTimestamp)` line. Short refs (`tN`) are unaffected - still 1:1 and the primary recovery path.
18
+ - **Accepted limitation:** a session that spans the upgrade keeps bare-id keying for everything captured before it landed; only the post-upgrade half of such a session gets occurrence-keyed identity. No migration runs on load. Concretely, within such a session a live tool result whose provider id collides with a pre-upgrade summarized record can still be stub-replaced with that record's stale content (`hasLegacyBareRecord`'s bare-id fallback in `src/pruner.ts` cannot distinguish the two once both denote the same bare id with no occurrence-keyed siblings); new records are unaffected, and the exposure disappears once a session contains no legacy records.
19
+
20
+ ## [2.5.0] - 2026-08-05
21
+
22
+ - **Removed the main-loop thinking strip (breaking: `contextPrune.thinkingStrip.*` no longer read).** The feature assumed thinking blocks we send are thinking blocks we are billed for. Verified against the live Anthropic API (`count_tokens` and real billed usage agree to the token), the actual rule is: thinking in a *closed* cycle bills 0 input tokens, and thinking in an *open* cycle survives only as an unbroken run starting at the cycle's first assistant turn — any gap discards everything after it. `keepLastTurns` kept the **last** K, so firing it punched a gap at the front and the API dropped all of it: the model received no thinking either way, and the no-gap → gap transition cost a full cache invalidation (measured +33% in a controlled 24-tool-call A/B, $0.6430 → $0.8531, with turn 17 rewriting 63113 tokens at 0% reuse). Across 58 sessions / 1233 open cycles the strip fired 253 times and reached its ~130-turn break-even twice. It was also redundant: chain compression's synthetic block is a `role: "user"` text message, which closes the cycle and frees all prior thinking server-side at zero cache cost. `pruneMessages` drops to three phases (`stub-replace → error-purge → chain-range-prune`); `src/thinking-strip.ts`, `ThinkingStripConfig`, `KEEP_LAST_TURNS_PRESETS`, the two `/pruner` settings entries, and `PruneFrontier.thinkingStripBoundaryTimestamp` are gone. A leftover `thinkingStrip` block in `settings.json` is inert and round-trips untouched (`normalize()` never filters unknown keys); a persisted `context-prune-frontier` entry carrying the old boundary field loads and is ignored. Rationale and measurements: `doc/specs/2026-08-05-remove-thinking-strip.md`.
23
+
10
24
  ## [2.4.3] - 2026-08-04
11
25
 
12
26
  - **Flush-gated, timestamp-keyed thinking strip ([#3](https://github.com/jjuraszek/pi-condense/issues/3)).** Phase 4 (`stripOldThinking`, `src/thinking-strip.ts`) recomputed its keep-window from the *live assistant count on every `context` render*, so each turn the `(count - keepLastTurns)`-th assistant slid forward and its thinking was stripped **deep in history**. pi-ai sets prompt-cache breakpoints only at `tools + system + last message` (verified in `@earendil-works/pi-ai` `api/anthropic-messages.js` `convertMessages` - no in-history breakpoint), so every deep mutation busted the cached suffix - roughly every render inside a tool loop. The strip boundary is now a **flush-computed, persisted assistant-message timestamp** (`thinkingStripBoundaryTimestamp`, added to the `PruneFrontier` snapshot on the existing `context-prune-frontier` entry): fixed between flushes so consecutive renders are byte-stable in their historical prefix (the cache survives a whole tool loop), advancing only on a non-empty flush (piggybacking summarization's own cache bust - zero marginal busts), monotonically clamped (never re-adds thinking to an already-stripped message, even when `keepLastTurns` is increased mid-session), and keyed by timestamp rather than array index so it is robust to phase-3 chain-range middle drops. An absent boundary (pre-feature sessions, pre-first-flush) falls back to the original live-count window verbatim. Additive optional field, fully backward-compatible; **no new config key**, `keepLastTurns` presets unchanged. `PRUNING.md` cache-impact model corrected. Turns the old k-busts-per-render into ~1-per-request.
package/PRUNING.md CHANGED
@@ -27,13 +27,15 @@
27
27
  - [Budget-delta flush](#budget-delta-flush)
28
28
  10. [Chain Compression](#chain-compression)
29
29
  - [Protected-output relocation](#protected-output-relocation)
30
- 11. [Error Purge](#error-purge)
31
- 12. [Main-loop Thinking Strip](#main-loop-thinking-strip)
32
- 13. [Why Summarization Works: Research Evidence](#why-summarization-works-research-evidence)
30
+ 11. [Occurrence Identity](#occurrence-identity)
31
+ 12. [Error Purge](#error-purge)
32
+ 13. [Orphan Sweep](#orphan-sweep)
33
+ 14. [Diagnostics](#diagnostics)
34
+ 15. [Why Summarization Works: Research Evidence](#why-summarization-works-research-evidence)
33
35
  - [SUPO — Summarization augmented Policy Optimization](#supo--summarization-augmented-policy-optimization)
34
36
  - [ReSum — Recursive Summarization for Long-Horizon Agents](#resum--recursive-summarization-for-long-horizon-agents)
35
37
  - [ACON — Agent Context Optimization](#acon--agent-context-optimization)
36
- 14. [Summary](#summary)
38
+ 16. [Summary](#summary)
37
39
 
38
40
  ---
39
41
 
@@ -198,7 +200,7 @@ Pruning does **not** delete data. It moves raw tool results out of the hot path
198
200
  There are two separate things happening during pruning:
199
201
 
200
202
  1. **Context filtering:** future requests stop including the old `toolResult` messages.
201
- 2. **Index preservation:** the extension stores each summarized tool call in the pruner index, keyed by `toolCallId`.
203
+ 2. **Index preservation:** the extension stores each summarized tool call in the pruner index, keyed by its occurrence key (`id@resultTimestamp`, or the bare id for legacy records - see [Occurrence Identity](#occurrence-identity)).
202
204
 
203
205
  That distinction is the core idea:
204
206
 
@@ -311,7 +313,7 @@ batch gets summarized
311
313
  ├─► summary message added to context
312
314
  │ └─► includes short refs (`t1`, `t2`, …)
313
315
 
314
- ├─► tool results indexed by toolCallId
316
+ ├─► tool results indexed by occurrence key (id@resultTimestamp)
315
317
  │ └─► full raw resultText stored in index/session
316
318
 
317
319
  └─► old toolResult messages removed from future context
@@ -606,7 +608,7 @@ Properties:
606
608
  - `role: "toolResult"` and the original `toolCallId` / `toolName` / `timestamp` are preserved — role alternation is intact; no synthetic-result injection.
607
609
  - `isError: false`, so the model does not interpret the stub as a tool failure.
608
610
  - The stub references the **short ref** (`t1`, `t2`, …) the indexer assigned at summary time. Legacy entries from before short-refs landed fall back to the raw `toolCallId`.
609
- - Deterministic per `toolCallId` — the stub text never changes across calls, so the prefix cache continues to hit on the pruned range.
611
+ - Deterministic per occurrence key — the stub text never changes across renders of the same `toolResult`, so the prefix cache continues to hit on the pruned range. A reused `toolCallId` is a *different* occurrence (different `resultTimestamp`) and gets its own stub and its own short ref.
610
612
 
611
613
  Implementation: `src/pruner.ts` `pruneMessages(messages, indexer)` returns `{ messages, pruned }`. When `pruned === false`, the original array reference is returned and the `context` handler skips reconstruction entirely.
612
614
 
@@ -660,9 +662,10 @@ Mechanism:
660
662
 
661
663
  1. When a batch enters `flushPending`, each tool call is hashed by `SHA-1(toolName + "\0" + normalize(resultText))`.
662
664
  2. The indexer's `contentHashToOriginal` map (populated by every earlier `addBatch` / `reconstructFromSession`) is consulted.
663
- 3. A hit means an earlier prune already covered identical content. The duplicate is registered as an alias of the original via `indexer.registerDuplicate(newId, originalId, appendEntry)`:
664
- - `dedupAliasToOriginal[newId] = originalId` (so `isSummarized(newId) === true` and `resolveToolCallId(newId) === originalId`).
665
- - `toolCallIdToAlias[newId] = toolCallIdToAlias[originalId]` (so `getShortRefForToolCallId(newId)` returns the **same** `tN` as the original).
665
+ 3. A hit means an earlier prune already covered identical content. The duplicate is registered as an alias of the original via `indexer.registerDuplicate(newKey, originalKey, appendEntry)`, where both are occurrence keys (or legacy bare ids):
666
+ - `dedupAliasToOriginal[newKey] = originalKey` (so `isSummarized(newKey) === true` and `resolveToolCallId(newKey) === originalKey`).
667
+ - `toolCallIdToAlias[newKey] = toolCallIdToAlias[originalKey]` (so `getShortRefForToolCallId(newKey)` returns the **same** `tN` as the original).
668
+ - Keying by occurrence key, not bare id, means a duplicate is only ever aliased to the specific earlier *occurrence* it matches byte-for-byte - a reused id whose later occurrence has different content is not conflated with the stale one.
666
669
  - A `context-prune-dedup-alias` custom entry is persisted so `reconstructFromSession` rebuilds the maps after a restart.
667
670
  4. The duplicate is removed from the batch — no summarizer call, no new index entry.
668
671
  5. Later, `pruneMessages` stub-replaces the duplicate's `ToolResultMessage` using the original's short ref, and `context_tree_query` returns the original's record whether the model passes the duplicate's id or the original's.
@@ -688,7 +691,7 @@ The last attempted prune boundary is persisted as `context-prune-frontier` so `f
688
691
  - **Tree browser (`/pruner tree`):** interactive, foldable tree of pruned tool calls grouped under their summaries. `Ctrl-O` on a summary node opens the full markdown summary in a bordered overlay.
689
692
  - **Configurable summarizer thinking (`summarizerThinking`):** trade summary cost / latency for quality (`off` / `minimal` / `low` / `medium` / `high` / `xhigh`). `default` omits the option entirely so the provider chooses.
690
693
  - **Cumulative stats:** `context-prune-stats` entries track input/output tokens and cost of every summarizer call; full detail surfaces in `/pruner stats`. Cost is also emitted on the `cost:external` pi.events channel for external aggregators (cumulative per session, live only).
691
- - **Live reclaim ratio:** measured once per `pruneMessages` call via `sizeMessages(messages) = JSON.stringify(messages).length`, comparing the input array before pruning to the result after. Estimated tokens = chars / 4. The measurement covers all four reclaim mechanisms in a single point (stub-replace, error-purge, chain-range-prune, thinking-strip); appears on the status line as `│ prune: ON · 92k->14k (-85%) │` once at least one prune has occurred (the `│ │` wrapper keeps the segment visually isolated in the shared footer, load-order independent).
694
+ - **Live reclaim ratio:** measured once per `pruneMessages` call via `sizeMessages(messages) = JSON.stringify(messages).length`, comparing the input array before pruning to the result after. Estimated tokens = chars / 4. The measurement covers all four phases in a single point (stub-replace, error-purge, chain-range-prune, orphan-sweep); appears on the status line as `│ prune: ON · 92.0k->14.0k (-85%)` once at least one prune has occurred (the leading `│` keeps the segment visually isolated in the shared footer, load-order independent - there is no trailing divider, since the footer's own space-join between segments already provides one).
692
695
  - **Live progress for `/pruner now`:** an `aboveEditor` widget shows one row per pending batch with braille spinner, streamed summary-char count, and ✓ / ⚠ status.
693
696
 
694
697
  ### Summarizer outage fallback
@@ -863,6 +866,8 @@ A **closed chain** is a span of messages from one user message through any numbe
863
866
  | Final text-only assistant | **Kept**, thinking blocks stripped (safe — no following tool cycle depends on the signature) |
864
867
  | Synthetic `<compressed-chain>` user message | **Injected** immediately after the start user message |
865
868
 
869
+ **Why there is no separate thinking strip.** The synthetic `<compressed-chain>` block is injected as a `role: "user"` text message, which Anthropic reads as a genuine user turn. That closes the assistant cycle, and the API drops every prior thinking block from the context window server-side - verified against the live API: the same 8-turn loop bills 3152 thinking tokens with a full `toolResult` history and 0 once a user text block precedes the final assistant. So chain compression already reclaims thinking mass for free, as a side effect of the range drop that was rewriting that region anyway. Stub replacement does not have this effect: it preserves `role: "toolResult"`, so the cycle stays open. A dedicated strip phase shipped through v2.4.3; removed in v2.5.0 - see `doc/specs/2026-08-05-remove-thinking-strip.md`.
870
+
866
871
  ### Transform composition order
867
872
 
868
873
  ```
@@ -871,23 +876,30 @@ raw messages from session
871
876
  ├─ [1] tool-result stub-replace (per-batch; existing)
872
877
  ├─ [2] error-purge (phase 2)
873
878
  ├─ [3] chain-range-prune (runs AFTER stubs)
874
- for each compressed chain:
875
- drop middle assistants (by toolCallId overlap)
876
- drop middle toolResults (by toolCallId)
877
- suppress per-batch summaries (by toolCallRefs overlap)
878
- │ inject <compressed-chain> after start user
879
- │ strip thinking from final assistant
880
- └─ [4] thinking-strip (keep thinking on last K assistant turns)
879
+ resolve each entry to a positional index range
880
+ drop assistant / toolResult / per-batch-summary inside the range
881
+ inject <compressed-chain> after start user
882
+ strip thinking from final assistant
883
+ └─ [4] orphan sweep (structural post-condition, see below)
881
884
  ```
882
885
 
883
- ### Identification model
886
+ ### Identification model: positional ranges, not ids
887
+
888
+ Pi-ai's `Message` union (`UserMessage | AssistantMessage | ToolResultMessage`) has no `.id` field, and provider `toolCallId`s are not session-durable (see [Occurrence Identity](#occurrence-identity) below). Chain compression therefore decides **what to drop** by message position, not by id membership.
889
+
890
+ `resolveRange` (`src/chain-range-prune.ts`) maps a persisted `ChainCompressionEntry` to an index range in the current message array:
884
891
 
885
- Pi-ai's `Message` union (`UserMessage | AssistantMessage | ToolResultMessage`) has no `.id` field. Chain compression uses:
892
+ - exactly one `user`-role message at `entry.startUserTimestamp`
893
+ - exactly one `assistant`-role message at `entry.finalAssistantTimestamp`
894
+ - `startIndex < endIndex`
886
895
 
887
- - `timestamp: number` to identify user / final-assistant boundary messages
888
- - `toolCallId` sets to identify middle assistant turns and their tool results
896
+ Any other outcome - zero or multiple matches on either boundary, `finalAssistantTimestamp === null`, or a non-ordered pair - resolves to `null` and the entry drops **nothing** and inserts **no synthetic** for that range. This is fail-closed on purpose: an id-set or timestamp-window fallback (accepting a match even when it's ambiguous) risks deleting a live assistant turn that reuses a compressed chain's provider id, orphaning its tool result and producing a rejected request. A resolution failure is invisible in context - it is recorded as an `unresolved-range` diagnostic (see [Diagnostics](#diagnostics) below) and the affected range simply stays raw in context instead of being silently mis-compressed.
889
897
 
890
- This is why the persisted `ChainCompressionEntry` stores `startUserTimestamp` + `droppedToolCallIds` rather than message IDs.
898
+ **Drops are role-restricted**, not index-membership-restricted: inside an accepted range, only `assistant`, `toolResult`, and per-batch-summary (`custom`, `context-prune-summary`) messages are removed. `user`-role messages inside the range - including the already-inserted `<compressed-chain>` synthetic, which is itself `role: "user"` - and any third-party `custom_message` entries survive untouched. Preserving the synthetic is what makes re-application idempotent: calling `applyChainCompressions` a second time with the same entries sees its own synthetic already present (matched by `blockId`) and skips re-inserting it.
899
+
900
+ **Per-batch summary suppression is coverage-based, not index-membership-based.** Under `batchingMode: "agent-message"` a per-batch summary is appended *after* `finalAssistantTimestamp`, i.e. outside the resolved range. Suppressing it by index membership would miss it entirely, so suppression instead checks whether the summary's own `toolCallRefs` overlap the set of ids actually dropped in this pass (`perBatchSummaryOverlapsDropped`).
901
+
902
+ **Diagnostic cross-check.** Each accepted entry also carries `droppedToolCallIds` from detection time. At render time the ids actually inside the resolved range are compared against that recorded set purely as a health check - a mismatch never changes what gets dropped (the range always wins) but emits a `range-id-mismatch` diagnostic, surfacing drift between detection-time and render-time state without ever acting on it.
891
903
 
892
904
  ### Rolling window
893
905
 
@@ -955,6 +967,48 @@ The `context-prune-chain` session entry carries the matching `protectedToolCallI
955
967
 
956
968
  ---
957
969
 
970
+ ## Occurrence Identity
971
+
972
+ Every lookup keyed on a tool call - the indexer's record map, dedup aliases, `isSummarized`, batch capture - needs a string that uniquely names one *occurrence* of a tool call for the lifetime of a session.
973
+
974
+ ### Why the provider `toolCallId` cannot be that string
975
+
976
+ A provider's `toolCallId` (e.g. `bash_23`) is unique only within the single response that produced it. Some providers restart a `${tool}_${n}` counter, so the same bare id recurs across turns and across a session, denoting a different tool call each time. The indexer cannot treat it as session-durable identity by itself - see [Identification model](#identification-model-positional-ranges-not-ids) for how chain compression sidesteps the same problem by keying on position instead of id.
977
+
978
+ ### Why `ToolCallRecord.timestamp` cannot serve as the discriminant either
979
+
980
+ `ToolCallRecord.timestamp` is the *batch's* timestamp, computed once per captured batch (`src/batch-capture.ts`) and shared by every tool call inside that batch - it cannot discriminate between two calls captured together, let alone across a reused id. It is also not computed the way this discriminant would need: the live `turn_end` path stamps it unconditionally with `Date.now()` (`index.ts`'s `turn_end` handler), not from the assistant message's own timestamp. This is exactly why a separate per-tool-call field was needed - `resultTimestamp`, sourced from the `ToolResultMessage`'s own `timestamp` instead of the batch. On reconstruction, `reconstructFromSession` replays whatever value was persisted on the record verbatim; it does not recompute it.
981
+
982
+ ### The key: `id@resultTimestamp`
983
+
984
+ The one value read identically at capture time and at every later render or rescan is the `ToolResultMessage`'s own `timestamp` field, stamped once by the message itself. `src/occurrence-key.ts` combines it with the bare id:
985
+
986
+ ```
987
+ occKey(toolCallId, resultTimestamp) = `${toolCallId}@${resultTimestamp}`
988
+ ```
989
+
990
+ A record with no `resultTimestamp` is keyed by its bare id - the shape for any record that predates this field, not a separate code path.
991
+
992
+ **Where the key lives:** `ToolCallRecord.resultTimestamp` and `SummaryToolCallRef.resultTimestamp` (both optional), the dedup-alias pair `newResultTimestamp` / `originalResultTimestamp`, and `ChainCompressionEntry.droppedOccurrenceKeys`. Bare-id and occurrence keys coexist in the same maps: `getRecord` / `isSummarized` compare keys as opaque strings, with no casting between the two shapes.
993
+
994
+ **`isSummarized` is strict.** It does an exact lookup on the occurrence key (or dedup-alias map) and never falls back to the bare id on a miss. The sole sanctioned bare-id path is `hasLegacyBareRecord(toolCallId)`, true only when the bare id is indexed **and** has no occurrence-keyed siblings (`bareIdToKeys`). A bare id with mixed legacy and occurrence-keyed entries fails closed on both checks - a permissive fallback would stub or recover the wrong occurrence whenever an id was reused.
995
+
996
+ **Spill sidecars** are named from the occurrence key, so a reused id spills to distinct files per occurrence. Recovery reads the `spillPath` persisted on the record rather than re-deriving it from the id, so bare-id-named sidecars still resolve.
997
+
998
+ **Render-time (`src/pruner.ts` stub-replace) gates the bare-id fallback on `hasLegacyBareRecord`, not on "message has no timestamp".** The first lookup key is `occKey(msg.toolCallId, msg.timestamp)` when the message carries a `timestamp` (a live `ToolResultMessage` almost always does) or the bare id otherwise. If that first key misses `isSummarized`, the bare id is tried as a second rung - but **only** when `indexer.hasLegacyBareRecord(msg.toolCallId)` is true (bare id indexed, no occurrence-keyed siblings), regardless of whether the message itself carried a timestamp. Gating that second rung on "the message has no timestamp" instead would mean a pure-legacy session (every record captured before `resultTimestamp` existed, so every occurrence-key lookup misses) never stubs at all, since a timestamped message would never even attempt the bare-id rung. A mixed bare+occurrence id still fails closed on both lookups.
999
+
1000
+ ### No migration, and the limitation that leaves
1001
+
1002
+ A record persisted before `resultTimestamp` existed is bare-keyed and stays that way - `reconstructFromSession` does not scan the branch to retroactively assign it one. No migration runs on load; `hasLegacyBareRecord` is the only accommodation, and it is a derivation (single-key check on `bareIdToKeys`), not a rewrite.
1003
+
1004
+ This leaves one accepted, documented exposure: within a session that spans the upgrade, a live tool result whose provider id collides with a pre-upgrade summarized record can be stub-replaced with that record's stale content - the render-time bare-id fallback in `src/pruner.ts` cannot tell the two apart once both denote the same bare `toolCallId` with no occurrence-keyed siblings. New records (both sides occurrence-keyed) are unaffected; the exposure is confined to the pre-upgrade half of a spanning session and disappears entirely once a session contains no legacy records.
1005
+
1006
+ ### Multi-occurrence recovery via `context_tree_query`
1007
+
1008
+ Short refs (`tN`) always resolve 1:1 - one ref, one record - and are the primary, recommended recovery path. A raw provider `toolCallId` passed to `context_tree_query` is looked up against every record that shares it via `getRecordsForId` (`src/indexer.ts`): if the id was reused, the tool returns **every** matching occurrence instead of silently picking one, one block each, chronologically, each labelled `id@timestamp`. This includes occurrences that were content-deduplicated to an earlier record: `getRecordsForId` also scans the dedup-alias map for aliases sharing the queried bare id and returns each aliased occurrence too, labelled with **its own** occurrence timestamp rather than the original's, so a reader can tell the two apart. A record with no `resultTimestamp` caught up in such a set is labelled with the bare id plus an explicit `Occurrence: legacy (no resultTimestamp)` line.
1009
+
1010
+ ---
1011
+
958
1012
  ## Error Purge
959
1013
 
960
1014
  Failed tool calls often embed large argument bodies in the assistant message — a `write` call with a 30 KB file body, an `edit` call with a multiline diff. The error result is small (e.g. `"Error: file not found"`), but the original `arguments` stay in the assistant turn indefinitely.
@@ -981,7 +1035,7 @@ Error purge replaces those arg bodies with compact stubs after the error has coo
981
1035
  **Transform position:** Error purge runs in Phase 2, after stub-replace and before chain range prune.
982
1036
 
983
1037
  ```
984
- [stub-replace] → [error-purge] → [chain-range-prune] → [thinking-strip]
1038
+ [stub-replace] → [error-purge] → [chain-range-prune] → [orphan-sweep]
985
1039
  ```
986
1040
 
987
1041
  **Config keys:**
@@ -994,49 +1048,37 @@ Error purge replaces those arg bodies with compact stubs after the error has coo
994
1048
 
995
1049
  ---
996
1050
 
997
- ## Main-loop Thinking Strip
998
-
999
- Chain compression and the summarizer target *tool* mass. But in long single-agent sessions the dominant cost is often **assistant `thinking` blocks**: on Opus 4.5+/Sonnet 4.6+ the API retains every prior-turn thinking block by default, and pi-ai replays them all (with signatures) on every request. One autonomous ops session held ~405 K tokens (~80% of a 500 K window) in thinking alone, untouched by every other strategy — chain compression only fires on *closed* spans, and that session was one long open span.
1000
-
1001
- Thinking strip is a deterministic, zero-LLM transform (Phase 4) that keeps `thinking` blocks only on the last `keepLastTurns` **assistant turns** and strips them from older assistant messages, leaving each message's `text` and `toolCall` blocks intact.
1002
-
1003
- ### Turn unit
1051
+ ## Orphan Sweep
1004
1052
 
1005
- `keepLastTurns` counts **assistant messages**, not user-bounded spans. The target failure mode is a single long open chain (zero subagents, near-zero user turns) where a span-based window would keep everything. Counting assistant turns directly bounds thinking accumulation regardless of whether any chain closes.
1053
+ `pruneMessages` ends with an unconditional structural pass, `sweepOrphanToolResults` (`src/orphan-sweep.ts`): a `toolResult` message whose id was not opened by the immediately preceding assistant turn is removed. It runs after every other phase, over whatever the previous three produced, as a final post-condition rather than a targeted fix for one code path.
1006
1054
 
1007
- ### Provider safety
1055
+ **Why it exists.** pi-ai's auto-repair (`insertSyntheticToolResults`) only fills in a missing `toolResult` for an orphaned `toolCall` - it has no equivalent repair for the opposite shape, an orphaned `toolResult` with no matching `toolCall`. Providers reject that shape outright (Anthropic: `unexpected tool_use_id found in tool_result blocks`; Kimi K3: a tool message needs a resolvable preceding tool_call). An orphaned `toolResult` can appear from any combination of id reuse, an unresolved chain range, or a bug in an upstream phase; the sweep is the last line of defense regardless of cause, and it is intentionally not keyed to any provider's specific error string - the fix is structural ("does this id have an open call"), not reactive to how one provider happens to phrase rejection.
1008
1056
 
1009
- Anthropic's extended-thinking contract during tool use:
1057
+ **Per-turn, not cumulative, open-call tracking.** The sweep does one forward pass over the message array. Each `assistant` message **replaces** the current "open" id set with its own `toolCall` ids; each `toolResult` message either consumes (removes) a matching id from that set or, if its id is not open, is swept. A cumulative seen-set across the whole array would be wrong here: it would let an id used validly by an early turn license a *later* genuine orphan under the same reused id - exactly the collision scenario this exists to catch. Per-turn tracking means only the immediately preceding assistant turn can vouch for a `toolResult`'s id.
1010
1058
 
1011
- - Only the **last assistant turn's** thinking is required; "you can omit thinking blocks from prior assistant role turns" and the API auto-filters them.
1012
- - A message's thinking blocks must be dropped **all-or-nothing** ("the entire sequence of consecutive thinking blocks must match the outputs … you can't rearrange or modify the sequence"). The strip reuses `withoutThinkingBlocks`, which removes every thinking block (and its signature) from a message.
1059
+ **Provider-agnostic and reference-preserving.** The sweep has no knowledge of which provider is in play; it operates purely on message shape. When nothing is swept it returns the **same array reference** it was given, so a clean render is a true no-op and the no-op / prompt-cache-prefix invariant of `doc/specs/2026-08-04-pruner-noop-serialization.md` holds - the sweep never forces a cache bust on a session where nothing is actually orphaned.
1013
1060
 
1014
- `keepLastTurns` is clamped to `>= 1`, so the most-recent assistant turn — the one that may be awaiting tool results — always keeps its thinking. This is the minimum safe window; the default of 16 is far above the floor and preserves recent reasoning continuity.
1061
+ Every swept id is reported once (hashed batch, not per-id) as an `orphan-sweep` diagnostic.
1015
1062
 
1016
- ### Transform position
1017
-
1018
- Thinking strip runs **last**, after chain-range-prune, at render time:
1019
-
1020
- ```
1021
- [stub-replace] → [error-purge] → [chain-range-prune] → [thinking-strip]
1022
- ```
1063
+ ---
1023
1064
 
1024
- The keep-window is a flush-computed assistant-message timestamp (the `keepLastTurns`-back boundary over the **raw** session branch — see the **Cache impact** note below), not a render-time recount over the post-phase-3 survivors. So when chain compression drops closed middle turns inside the window, fewer than `keepLastTurns` *surviving* turns may retain thinking — deliberate, and it only ever strips more, never re-adds. In a session with no closed chains, Phases 1–3 may be no-ops and thinking strip does all the work. Where chain compression *does* fire, the two cooperate: chain compression drops whole old middle turns (including their thinking); thinking strip mops up thinking in the surviving recent / in-flight turns beyond the boundary.
1065
+ ## Diagnostics
1025
1066
 
1026
- ### Cache impact
1067
+ Prune-time degradations - an unresolvable chain range, a detection/render id mismatch, a swept orphan - are recorded on an out-of-band channel instead of surfacing in the model's context. `DiagnosticSink` (`src/diagnostics.ts`) writes a `context-prune-diagnostic` session entry (`{ kind, detail }`) for each of three kinds:
1027
1068
 
1028
- pi-ai serializes prompt-cache breakpoints only at `tools`, `system`, and the last conversation message (verified in `@earendil-works/pi-ai` `api/anthropic-messages.js` `convertMessages`) - there is **no in-history breakpoint**. So the strip boundary is flush-gated, not per-render: it is a persisted assistant-message timestamp on the `context-prune-frontier` entry that stays fixed between flushes and advances only on a non-empty flush. Between flushes every render is byte-stable in its historical prefix, so the cache holds through a whole tool loop; the boundary moves at most once per flush (~once per request), turning the old k-busts-per-render into ~1-per-request. That residual bust is not always free: for a request shorter than `keepLastTurns` turns the boundary (tail-K) sits deeper than the current request's just-summarized tool results, so thinking-strip is the dominant invalidator, ~1 deep reprocess per request; for a request longer than `keepLastTurns` turns summarization's stub-replace reaches deeper and subsumes it (~0 marginal). Retained thinking is bounded to `keepLastTurns` raw-session turns, drifting up to `keepLastTurns + turns-since-flush` between flushes (deliberate: the frozen boundary is what buys cache stability). Note `error-purge` still mutates old history off a live per-render count, an independent cache-bust source not addressed here.
1069
+ | Kind | Emitted from | Meaning |
1070
+ |---|---|---|
1071
+ | `unresolved-range` | `applyChainCompressions` | A persisted chain entry's boundaries didn't resolve to a unique range (or the range was rejected as nested/duplicate) - the entry compressed nothing |
1072
+ | `range-id-mismatch` | `applyChainCompressions` | The ids actually inside a resolved range don't match the entry's recorded `droppedToolCallIds` - informational only, the range still wins |
1073
+ | `orphan-sweep` | `pruneMessages` (Phase 4) | One or more `toolResult` messages were removed for having no open matching `toolCall` |
1029
1074
 
1030
- ### Recovery
1075
+ **Never in LLM context.** These are session entries only - zero tokens added, zero cache-prefix change, never read back into the message array the model sees.
1031
1076
 
1032
- Stripped thinking is **not** recoverable via `context_tree_query` unlike tool outputs, thinking blocks are not indexed. The raw thinking remains in the session JSONL on disk (the `context` hook never mutates storage); reloading the session without the extension, or reading the file directly, shows the original blocks. Thinking is transient model-internal reasoning, so drop-without-recovery is intentional.
1077
+ **Deduped per `(kind, dedupKey)`**, so a permanently degraded condition (e.g. the same chain entry failing to resolve on every render) writes one entry, not one per render. The dedup key is entry-specific: a chain `blockId` for `range-id-mismatch` and for a genuinely unresolvable `unresolved-range`; `overlap:<blockId>` for the same `unresolved-range` kind when the entry was instead skipped as nested inside or duplicating another range's start (a distinct dedup-key prefix keeps the two cases greppable under one kind); and a short hash of the sorted swept-id list for `orphan-sweep` (hashing rather than joining the raw list avoids `DiagnosticSink`'s dedup set retaining an ever-longer key per additional orphan over a session's lifetime). A write is only marked seen after the `appendEntry` call succeeds, so a failed write is retried on the next render instead of being silently dropped.
1033
1078
 
1034
- ### Config keys
1079
+ **Reset on `session_start` and `session_tree`**, matching every other in-memory, non-persisted piece of prune state.
1035
1080
 
1036
- | Key | Default | Description |
1037
- |---|---|---|
1038
- | `thinkingStrip.enabled` | `true` | Master toggle (gated behind the top-level `enabled`) |
1039
- | `thinkingStrip.keepLastTurns` | `16` | Keep thinking on the last N assistant turns; strip older. Clamped to `>= 1` |
1081
+ **Surfaced on the status line.** The footer status widget (`setPruneStatusWidget`, gated by `showPruneStatusLine`) appends a self-hiding ` · diag u<N>/m<N>/o<N>` segment (u = `unresolved-range`, m = `range-id-mismatch`, o = `orphan-sweep`) built from the sink's live counters via `pruneStatusText`. Each letter is omitted when its counter is zero, and the whole segment is absent when all three are zero. `/pruner status` (the slash command) prints a separate settings/stats block and does not include this segment.
1040
1082
 
1041
1083
  ---
1042
1084
 
package/README.md CHANGED
@@ -80,12 +80,17 @@ Every summarizer cost update is emitted on the shared `pi.events` channel `cost:
80
80
  | Term | Meaning |
81
81
  |---|---|
82
82
  | Stub | The short breadcrumb (`[Summarized in pruner summary, ref \`t1\`...]`) that replaces a pruned tool result in context |
83
- | `context_tree_query` | The tool the model calls to recover a stubbed original by ref |
83
+ | `context_tree_query` | The tool the model calls to recover a stubbed original by ref (`tN`) or `toolCallId`. A reused id returns every matching occurrence, not just one, including any that were content-deduplicated to an earlier record - see [PRUNING.md § Occurrence Identity](PRUNING.md#occurrence-identity) |
84
84
  | Batch vs chain | A batch is one flush's worth of tool calls; a chain is a longer closed sequence eligible for range compression |
85
85
  | Prune frontier | The last attempted prune boundary - advances even on a skip, so nothing is reconsidered twice |
86
+ | Diagnostics (`diag u/m/o`) | A self-hiding status-line segment surfacing prune-time degradations: `u` = unresolved chain range, `m` = detection/render id mismatch (informational, does not change what's dropped), `o` = orphan tool-result sweep. Each letter's count is omitted when zero; the whole segment disappears when all three are zero. Backing session entries are `context-prune-diagnostic` - see below |
86
87
  | Prompt-cache interaction | Why batching (not per-turn pruning) is the default - see [PRUNING.md](PRUNING.md#how-prefix-caching-works) |
87
88
  | `cost:external` | The shared cost-reporting channel pi-condense emits on (see above) |
88
89
 
90
+ ### Diagnostic entries (`context-prune-diagnostic`)
91
+
92
+ The status-line `diag u<N>/m<N>/o<N>` segment above is backed by `context-prune-diagnostic` session entries - session-log-only, never added to what the model sees. Full mechanics: [PRUNING.md § Diagnostics](PRUNING.md#diagnostics).
93
+
89
94
  ## When to use / when NOT to use
90
95
 
91
96
  **Use it for:** long coding or research sessions where tool output dominates the prompt; setups deliberately running a smaller/cheaper driver model; pi-cohort fan-outs or pi-gauntlet runs where cost compounds across many turns or many children.
package/index.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * config — load/save <agent-dir>/settings.json `contextPrune` namespace (honors PI_CODING_AGENT_DIR)
6
6
  * batch-capture — serialize turn_end event into CapturedBatch
7
7
  * summarizer — call LLM to summarize a CapturedBatch
8
- * indexer — maintain Map<toolCallId, ToolCallRecord> + session persistence
8
+ * indexer — maintain Map<occurrenceKey, ToolCallRecord> + session persistence
9
9
  * pruner — filter context event messages
10
10
  * query-tool — register context_tree_query tool
11
11
  * commands — register /pruner command + message renderer
@@ -36,10 +36,11 @@ import { PruneFrontierTracker } from "./src/frontier.js";
36
36
  import { BlockRefIssuer } from "./src/block-refs.js";
37
37
  import { compressEligible } from "./src/chain-compressor.js";
38
38
  import { detectChains, withClosingMessage } from "./src/chain-detector.js";
39
- import { computeThinkingBoundary } from "./src/thinking-strip.js";
40
39
  import { inGraceRecoveryToolCallIds } from "./src/recovery-grace.js";
41
40
  import { shouldBudgetFlush, shouldDeltaFlush, usageFraction } from "./src/budget.js";
42
41
  import { spillOversizedBatch } from "./src/spill.js";
42
+ import { occKey } from "./src/occurrence-key.js";
43
+ import { DiagnosticSink } from "./src/diagnostics.js";
43
44
 
44
45
  export default function (pi: ExtensionAPI) {
45
46
  // Shared mutable config reference — updated by /pruner commands
@@ -65,6 +66,10 @@ export default function (pi: ExtensionAPI) {
65
66
  // rebuilt from session on session_start / session_tree
66
67
  const blockRefs = new BlockRefIssuer();
67
68
 
69
+ // Session-scoped diagnostic sink — tracks recovery-path anomaly counters
70
+ // (dedup'd across the session's lifetime, not per-render).
71
+ const diagnostics = new DiagnosticSink((type, data) => pi.appendEntry(type, data));
72
+
68
73
  // Pending batches — accumulated until the prune trigger fires
69
74
  const pendingBatches: CapturedBatch[] = [];
70
75
  let isFlushing = false;
@@ -104,7 +109,7 @@ export default function (pi: ExtensionAPI) {
104
109
  let toolCalls = batch.toolCalls;
105
110
 
106
111
  // The indexer tells us what was successfully summarized earlier.
107
- toolCalls = toolCalls.filter((tc) => !indexer.isSummarized(tc.toolCallId));
112
+ toolCalls = toolCalls.filter((tc) => !indexer.isSummarized(occKey(tc.toolCallId, tc.resultTimestamp)));
108
113
  if (toolCalls.length === 0) return null;
109
114
 
110
115
  // The frontier tells us the last attempted boundary even when the attempt did
@@ -234,8 +239,9 @@ export default function (pi: ExtensionAPI) {
234
239
  const remaining: typeof batch.toolCalls = [];
235
240
  for (const tc of batch.toolCalls) {
236
241
  const originalId = indexer.lookupByContent(tc.toolName, tc.resultText);
237
- if (originalId && originalId !== tc.toolCallId) {
238
- indexer.registerDuplicate(tc.toolCallId, originalId, persistAlias);
242
+ const key = occKey(tc.toolCallId, tc.resultTimestamp);
243
+ if (originalId && originalId !== key) {
244
+ indexer.registerDuplicate(key, originalId, persistAlias);
239
245
  dedupedPerBatch[i].toolCalls.push(tc);
240
246
  dedupedPerBatch[i].rawChars += tc.resultText.length;
241
247
  } else {
@@ -414,7 +420,7 @@ export default function (pi: ExtensionAPI) {
414
420
  // `display: false` keeps the summary in future LLM context (convertToLlm
415
421
  // ignores `display`) while suppressing the full markdown block from Pi's
416
422
  // main window; rebuild keys on customType, not display.
417
- const batchToolCallIds = batch.toolCalls.map((tc) => tc.toolCallId);
423
+ const batchOccurrenceKeys = batch.toolCalls.map((tc) => occKey(tc.toolCallId, tc.resultTimestamp));
418
424
  if (delivery === "runtime") {
419
425
  pi.sendMessage(
420
426
  { customType: CUSTOM_TYPE_SUMMARY, content: summaryText, display: false, details: batchDetails },
@@ -429,7 +435,7 @@ export default function (pi: ExtensionAPI) {
429
435
  }
430
436
  // Keep the in-memory summary-body registry current so chain compression
431
437
  // can build synthetic chain messages without rescanning session entries.
432
- indexer.registerSummaryBody(batchToolCallIds, summaryText);
438
+ indexer.registerSummaryBody(batchOccurrenceKeys, summaryText);
433
439
  } else {
434
440
  oversizedBatches.push(batch);
435
441
  }
@@ -453,7 +459,7 @@ export default function (pi: ExtensionAPI) {
453
459
 
454
460
  if (processedBatches.length === 0) {
455
461
  // Nothing was persisted (all calls failed or first call failed)
456
- setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim());
462
+ setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim(), diagnostics.counts());
457
463
  return { ok: false, reason: "summarizer-failed" };
458
464
  }
459
465
 
@@ -487,34 +493,15 @@ export default function (pi: ExtensionAPI) {
487
493
  ? "skipped-deduped"
488
494
  : "skipped-trivial";
489
495
 
490
- // Raw session branch, unwrapped once and shared by the thinking-strip boundary
491
- // computation and the chain-compression block below - both walk it, so avoid a
492
- // second O(session-size) pass on every flush. Only materialized when at least
493
- // one consumer is enabled.
496
+ // Raw session branch, unwrapped once for the chain-compression block below.
497
+ // Only materialized when chain compression is enabled.
494
498
  let branchMessages: any[] | undefined;
495
- if (currentConfig.value.thinkingStrip.enabled || currentConfig.value.chainCompression.enabled) {
499
+ if (currentConfig.value.chainCompression.enabled) {
496
500
  branchMessages = ctx.sessionManager.getBranch()
497
501
  .filter((e: any) => e.type === "message" && e.message)
498
502
  .map((e: any) => e.message);
499
503
  }
500
504
 
501
- // Flush-gated thinking-strip boundary: recompute the (count - keepLastTurns)-th
502
- // assistant timestamp over the RAW branch (+ the not-yet-persisted closing
503
- // assistant), monotonically clamped. Stays on the frontier snapshot so renders
504
- // between flushes read a fixed value and keep the cache prefix. Carries prev
505
- // through when disabled. Must run regardless of chainCompression.enabled.
506
- let thinkingBoundary = frontier.get()?.thinkingStripBoundaryTimestamp;
507
- if (currentConfig.value.thinkingStrip.enabled) {
508
- const assistantTimestamps = withClosingMessage(branchMessages!, options.closingMessage)
509
- .filter((m: any) => m?.role === "assistant" && typeof m.timestamp === "number")
510
- .map((m: any) => m.timestamp);
511
- thinkingBoundary = computeThinkingBoundary(
512
- assistantTimestamps,
513
- currentConfig.value.thinkingStrip.keepLastTurns,
514
- thinkingBoundary,
515
- );
516
- }
517
-
518
505
  const frontierSnapshot: PruneFrontier = {
519
506
  lastAttemptedToolCallId: lastTC.toolCallId,
520
507
  lastAttemptedToolName: lastTC.toolName,
@@ -525,7 +512,6 @@ export default function (pi: ExtensionAPI) {
525
512
  rawCharCount: totalRawCharCount,
526
513
  summaryCharCount: totalSummaryCharCount,
527
514
  outcome: flushOutcome,
528
- thinkingStripBoundaryTimestamp: thinkingBoundary,
529
515
  };
530
516
 
531
517
  try {
@@ -546,7 +532,7 @@ export default function (pi: ExtensionAPI) {
546
532
  return { ok: false, reason: isStaleContextError(err) ? "stale-context" : "failed", error: errorMessage(err) };
547
533
  }
548
534
 
549
- setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim());
535
+ setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim(), diagnostics.counts());
550
536
  emitExternalCost(pi, statsAccum);
551
537
 
552
538
  // Chain compression — compress closed chains beyond the rolling window.
@@ -556,7 +542,7 @@ export default function (pi: ExtensionAPI) {
556
542
  try {
557
543
  // message_end fires before pi persists the closing assistant, so thread it
558
544
  // in here; otherwise the newest chain reads as open and K over-retains by 1.
559
- // branchMessages was unwrapped once above (shared with the boundary block).
545
+ // branchMessages was unwrapped once above, gated on chainCompression.enabled.
560
546
  const chains = detectChains(withClosingMessage(branchMessages!, options.closingMessage), protectionPredicate);
561
547
  const inGrace = inGraceRecoveryToolCallIds(branchMessages!, currentConfig.value.recoveryGraceTurns);
562
548
  const { compressedEntries } = await compressEligible(
@@ -657,7 +643,7 @@ export default function (pi: ExtensionAPI) {
657
643
  // When the abort signal fired, summarizeBatch rethrows rather than
658
644
  // swallowing the error. Don't show a UI error — the user intended this.
659
645
  if (options.signal?.aborted) {
660
- setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim());
646
+ setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim(), diagnostics.counts());
661
647
  return { ok: false, reason: "aborted" };
662
648
  }
663
649
  if (isStaleContextError(err)) {
@@ -684,6 +670,7 @@ export default function (pi: ExtensionAPI) {
684
670
  // Rebuild stats accumulator from persisted session entries
685
671
  statsAccum.reconstructFromSession(ctx);
686
672
  fallbackController.reset();
673
+ diagnostics.reset();
687
674
 
688
675
  // Rebuild prune frontier from persisted session entries
689
676
  frontier.reconstructFromSession(ctx);
@@ -693,7 +680,7 @@ export default function (pi: ExtensionAPI) {
693
680
  previousFraction = null;
694
681
 
695
682
  // Update footer status
696
- setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim());
683
+ setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim(), diagnostics.counts());
697
684
 
698
685
  ctx.ui.setWidget(
699
686
  "pruner-boot",
@@ -716,6 +703,7 @@ export default function (pi: ExtensionAPI) {
716
703
  indexer.reconstructFromSession(ctx);
717
704
  blockRefs.rebuildFrom(indexer.getChainEntries().map((e) => e.blockId));
718
705
  statsAccum.reconstructFromSession(ctx);
706
+ diagnostics.reset();
719
707
  frontier.reconstructFromSession(ctx);
720
708
  // Pending batches belong to the old branch — discard them
721
709
  pendingBatches.length = 0;
@@ -847,25 +835,23 @@ export default function (pi: ExtensionAPI) {
847
835
  // pruneMessages is the single source of truth for "is there work to do".
848
836
  // It returns the original array reference (pruned: false) only when none of
849
837
  // the four phases changed anything; index/registry emptiness alone does not
850
- // imply a no-op, since error-purge (phase 2) and thinking-strip (phase 4)
851
- // prune independently of them. Calling it unconditionally is safe and avoids
852
- // a split gate here.
838
+ // imply a no-op, since error-purge (phase 2) prunes independently of them.
839
+ // Calling it unconditionally is safe and avoids a split gate here.
853
840
  const result = pruneMessages(
854
841
  messages,
855
842
  indexer,
856
843
  currentConfig.value.chainCompression,
857
844
  currentConfig.value.purgeErrors,
858
- currentConfig.value.thinkingStrip,
859
845
  currentConfig.value,
860
846
  currentConfig.value.recoveryGraceTurns,
861
- frontier.get()?.thinkingStripBoundaryTimestamp,
847
+ diagnostics,
862
848
  );
863
849
  if (result.pruned) {
864
850
  messages = result.messages;
865
851
  changed = true;
866
852
  statsAccum.setLiveReclaim(result.beforeChars, result.afterChars);
867
853
  }
868
- setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim());
854
+ setPruneStatusWidget(ctx, currentConfig.value, statsAccum.getLiveReclaim(), diagnostics.counts());
869
855
 
870
856
  if (!changed) return undefined;
871
857
  return { messages };
@@ -902,5 +888,5 @@ export default function (pi: ExtensionAPI) {
902
888
  return { compressedEntries: result.compressedEntries, skipped: result.skipped.filter((s) => s.reason === "no-summary").length };
903
889
  };
904
890
 
905
- registerCommands(pi, currentConfig, flushPending, capturePendingBatches, () => statsAccum.getStats(), () => statsAccum.getLiveReclaim(), indexer, compactChains);
891
+ registerCommands(pi, currentConfig, flushPending, capturePendingBatches, () => statsAccum.getStats(), () => statsAccum.getLiveReclaim(), indexer, compactChains, () => diagnostics.counts());
906
892
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-condense",
3
- "version": "2.4.3",
3
+ "version": "2.6.0",
4
4
  "description": "Pi coding-agent extension that summarizes completed tool-call batches, replaces raw outputs with short stubs, compresses closed tool-call chains, and recovers any original on demand via context_tree_query.",
5
5
  "author": "Jacek Juraszek",
6
6
  "license": "MIT",