pi-dynamic-context-pruning 0.1.9 → 0.1.10

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 (3) hide show
  1. package/README.md +1 -1
  2. package/index.ts +120 -18
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -154,7 +154,7 @@ Gate modes (`/context-pruning gate <mode>`):
154
154
  ### `/prune`
155
155
 
156
156
  Interactive picker (TUI/RPC) over every prunable tool result in the current
157
- branch:
157
+ model context:
158
158
 
159
159
  ```text
160
160
  /prune
package/index.ts CHANGED
@@ -75,6 +75,54 @@ export interface MinimalSessionEntry {
75
75
  [key: string]: unknown;
76
76
  }
77
77
 
78
+ export interface MinimalProjectedSessionEntry {
79
+ sourceEntry: MinimalSessionEntry;
80
+ messages: MinimalMessage[];
81
+ }
82
+
83
+ export interface MinimalSessionProjection {
84
+ entries: MinimalProjectedSessionEntry[];
85
+ messages?: MinimalMessage[];
86
+ }
87
+
88
+ function isRecord(value: unknown): value is Record<string, unknown> {
89
+ return typeof value === "object" && value !== null;
90
+ }
91
+
92
+ function isMinimalMessage(value: unknown): value is MinimalMessage {
93
+ return isRecord(value) && typeof value.role === "string" && value.role.length > 0;
94
+ }
95
+
96
+ function isProjectionSourceEntry(value: unknown): value is MinimalSessionEntry {
97
+ return isRecord(value)
98
+ && typeof value.type === "string"
99
+ && value.type.length > 0
100
+ && typeof value.id === "string"
101
+ && value.id.length > 0;
102
+ }
103
+
104
+ export function normalizeSessionProjection(value: unknown): MinimalSessionProjection | undefined {
105
+ if (!isRecord(value) || !Array.isArray(value.entries)) return undefined;
106
+
107
+ const entries: MinimalProjectedSessionEntry[] = [];
108
+ for (const candidate of value.entries) {
109
+ if (!isRecord(candidate) || !isProjectionSourceEntry(candidate.sourceEntry) || !Array.isArray(candidate.messages)) return undefined;
110
+ if (!candidate.messages.every(isMinimalMessage)) return undefined;
111
+ entries.push({
112
+ sourceEntry: candidate.sourceEntry,
113
+ messages: candidate.messages,
114
+ });
115
+ }
116
+
117
+ if ("messages" in value && (!Array.isArray(value.messages) || !value.messages.every(isMinimalMessage))) return undefined;
118
+ const messages = Array.isArray(value.messages) ? value.messages : entries.flatMap((entry) => entry.messages);
119
+ return { entries, messages };
120
+ }
121
+
122
+ export function sessionProjectionToMessages(projection: MinimalSessionProjection): MinimalMessage[] {
123
+ return projection.messages ?? projection.entries.flatMap((entry) => entry.messages);
124
+ }
125
+
78
126
  // ============================================================================
79
127
  // Constants
80
128
  // ============================================================================
@@ -699,13 +747,7 @@ export function findToolCallPairIndices(
699
747
  return pair;
700
748
  }
701
749
 
702
- /**
703
- * Fallback correlation for decisions that reference a session entry rather
704
- * than a toolCallId (reserved for future non-tool-call strategies). Zips
705
- * message-producing session entries against the current context projection
706
- * by position; entry/message counts are expected to match in the common
707
- * case, but this degrades gracefully otherwise.
708
- */
750
+ /** Map raw session-entry provenance to projected message positions when Pi exposes it. */
709
751
  function expectedRoleForEntry(entry: MinimalSessionEntry): string | undefined {
710
752
  if (entry.type === "message") return entry.message?.role;
711
753
  if (entry.type === "custom_message") return "custom";
@@ -714,15 +756,53 @@ function expectedRoleForEntry(entry: MinimalSessionEntry): string | undefined {
714
756
  return undefined;
715
757
  }
716
758
 
717
- export function buildEntryIdToMessageIndexMap(
759
+ function buildProjectedEntryIdToMessageIndexMap(
718
760
  entries: MinimalSessionEntry[],
719
761
  messages: MinimalMessage[],
762
+ projection: MinimalSessionProjection,
720
763
  ): Map<string, number> {
721
764
  const map = new Map<string, number>();
765
+ const entryIds = new Set(entries.map((entry) => entry.id));
766
+ let cursor = 0;
767
+
768
+ for (const projectedEntry of projection.entries) {
769
+ let firstMessageIndex: number | undefined;
770
+ for (const projectedMessage of projectedEntry.messages) {
771
+ let messageIndex = messages.indexOf(projectedMessage, cursor);
772
+ if (messageIndex < cursor) messageIndex = -1;
773
+
774
+ if (messageIndex < 0 && typeof projectedMessage.timestamp === "number") {
775
+ messageIndex = messages.findIndex(
776
+ (candidate, index) =>
777
+ index >= cursor && candidate.role === projectedMessage.role && candidate.timestamp === projectedMessage.timestamp,
778
+ );
779
+ }
780
+ if (messageIndex < 0) continue;
781
+ firstMessageIndex ??= messageIndex;
782
+ cursor = messageIndex + 1;
783
+ }
784
+
785
+ if (firstMessageIndex !== undefined && entryIds.has(projectedEntry.sourceEntry.id)) {
786
+ map.set(projectedEntry.sourceEntry.id, firstMessageIndex);
787
+ }
788
+ }
789
+ return map;
790
+ }
791
+
792
+ export function buildEntryIdToMessageIndexMap(
793
+ entries: MinimalSessionEntry[],
794
+ messages: MinimalMessage[],
795
+ projection?: MinimalSessionProjection,
796
+ ): Map<string, number> {
797
+ if (projection) return buildProjectedEntryIdToMessageIndexMap(entries, messages, projection);
798
+
799
+ // Older runtimes expose only raw branch entries; preserve their positional
800
+ // correlation and use role/timestamp only when the counts diverge.
722
801
  const producing = entries.filter((entry) =>
723
802
  entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary" || entry.type === "compaction",
724
803
  );
725
804
  const length = Math.min(producing.length, messages.length);
805
+ const map = new Map<string, number>();
726
806
  for (let i = 0; i < length; i++) {
727
807
  const entry = producing[i];
728
808
  const expectedRole = expectedRoleForEntry(entry);
@@ -747,15 +827,21 @@ export function findMessageIndexByRoleAndTimestamp(
747
827
  return index >= 0 ? index : undefined;
748
828
  }
749
829
 
750
- /** Resolve a session entry id to a message index using order-zip, then role+timestamp fallback. */
830
+ /** Resolve a session entry id using projection provenance, then legacy role+timestamp fallback. */
751
831
  export function resolveMessageIndexForEntry(
752
832
  entryId: string,
753
833
  entries: MinimalSessionEntry[],
754
834
  messages: MinimalMessage[],
835
+ projection?: MinimalSessionProjection,
755
836
  ): number | undefined {
756
- const zipMap = buildEntryIdToMessageIndexMap(entries, messages);
837
+ const zipMap = buildEntryIdToMessageIndexMap(entries, messages, projection);
757
838
  const zipped = zipMap.get(entryId);
758
839
  if (zipped !== undefined) return zipped;
840
+
841
+ // An empty projected contribution is an explicit omission/replacement state;
842
+ // only a validated projection may make that context-edit-aware decision.
843
+ if (projection?.entries.some((entry) => entry.sourceEntry.id === entryId && entry.messages.length === 0)) return undefined;
844
+
759
845
  const entry = entries.find((candidate) => candidate.id === entryId);
760
846
  if (!entry) return undefined;
761
847
  return findMessageIndexByRoleAndTimestamp(entry, messages);
@@ -2172,8 +2258,22 @@ export function rebuildDecisionStateFromEntries(entries: MinimalSessionEntry[]):
2172
2258
  // /prune picker helpers (pe-8re9)
2173
2259
  // ============================================================================
2174
2260
 
2175
- /** Convert branch entries into the plain message array the pipeline/pickers correlate against. */
2176
- export function sessionEntriesToMessages(entries: MinimalSessionEntry[]): MinimalMessage[] {
2261
+ function resolveSessionProjection(ctx: ExtensionContext): MinimalSessionProjection | undefined {
2262
+ try {
2263
+ const sessionManager = ctx.sessionManager as unknown as { buildSessionProjection?: () => unknown };
2264
+ const buildProjection = sessionManager.buildSessionProjection;
2265
+ if (typeof buildProjection !== "function") return undefined;
2266
+ return normalizeSessionProjection(buildProjection.call(sessionManager));
2267
+ } catch {
2268
+ return undefined;
2269
+ }
2270
+ }
2271
+
2272
+ export function sessionEntriesToMessages(
2273
+ entries: MinimalSessionEntry[],
2274
+ projection?: MinimalSessionProjection,
2275
+ ): MinimalMessage[] {
2276
+ if (projection) return sessionProjectionToMessages(projection);
2177
2277
  const messages: MinimalMessage[] = [];
2178
2278
  for (const entry of entries) {
2179
2279
  if (entry.type === "message" && entry.message) messages.push(entry.message);
@@ -2288,7 +2388,7 @@ export function formatPrunableItemDetail(item: PrunableItem, cost?: CacheCostMod
2288
2388
 
2289
2389
  /** Plain-text report used both by the non-UI /prune fallback and as a debugging aid. */
2290
2390
  export function formatPrunableItemsReport(items: PrunableItem[]): string[] {
2291
- if (items.length === 0) return ["No prunable tool results found in this session."];
2391
+ if (items.length === 0) return ["No prunable tool results found in the current model context."];
2292
2392
  return items.map((item, index) => `${index + 1}. ${formatPrunableItemOption(item)}`);
2293
2393
  }
2294
2394
 
@@ -2596,7 +2696,8 @@ export default function dynamicContextPruningExtension(pi: ExtensionAPI) {
2596
2696
  description: "Review, manually prune, and restore prunable tool results (interactive picker in TUI/RPC)",
2597
2697
  handler: async (_args, ctx) => {
2598
2698
  const branchEntries = ctx.sessionManager.getBranch() as unknown as MinimalSessionEntry[];
2599
- const messages = sessionEntriesToMessages(branchEntries);
2699
+ const projection = resolveSessionProjection(ctx);
2700
+ const messages = sessionEntriesToMessages(branchEntries, projection);
2600
2701
  const activeByToolCallId = buildActiveResultDecisionMap(persistedDecisions);
2601
2702
  const restoredToolCallIds = new Set(
2602
2703
  Array.from(lastDecisionByKey.values())
@@ -2606,19 +2707,20 @@ export default function dynamicContextPruningExtension(pi: ExtensionAPI) {
2606
2707
  const items = buildPrunableItems(messages, activeByToolCallId, restoredToolCallIds);
2607
2708
 
2608
2709
  if (!ctx.hasUI) {
2609
- notify(ctx, ["/prune: no interactive UI available. Prunable tool results in this session:", "", ...formatPrunableItemsReport(items)].join("\n"), "info");
2710
+ notify(ctx, ["/prune: no interactive UI available. Prunable tool results in the current model context:", "", ...formatPrunableItemsReport(items)].join("\n"), "info");
2610
2711
  return;
2611
2712
  }
2612
2713
 
2613
2714
  if (items.length === 0) {
2614
- notify(ctx, "No prunable tool results found in this session.", "info");
2715
+ notify(ctx, "No prunable tool results found in the current model context.", "info");
2615
2716
  return;
2616
2717
  }
2617
2718
 
2618
2719
  const doneLabel = "Done";
2619
2720
  while (true) {
2620
2721
  const latestBranch = ctx.sessionManager.getBranch() as unknown as MinimalSessionEntry[];
2621
- const latestMessages = sessionEntriesToMessages(latestBranch);
2722
+ const latestProjection = resolveSessionProjection(ctx);
2723
+ const latestMessages = sessionEntriesToMessages(latestBranch, latestProjection);
2622
2724
  const latestActive = buildActiveResultDecisionMap(persistedDecisions);
2623
2725
  const latestRestoredToolCallIds = new Set(
2624
2726
  Array.from(lastDecisionByKey.values())
@@ -2627,7 +2729,7 @@ export default function dynamicContextPruningExtension(pi: ExtensionAPI) {
2627
2729
  );
2628
2730
  const latestItems = buildPrunableItems(latestMessages, latestActive, latestRestoredToolCallIds);
2629
2731
  if (latestItems.length === 0) {
2630
- notify(ctx, "No prunable tool results found in this session.", "info");
2732
+ notify(ctx, "No prunable tool results found in the current model context.", "info");
2631
2733
  return;
2632
2734
  }
2633
2735
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dynamic-context-pruning",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "type": "module",
5
5
  "description": "A pi extension that dynamically prunes stale context to keep sessions lean.",
6
6
  "keywords": [