@foliox/transparent-compact-pi 0.9.3 → 0.10.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.
@@ -34,7 +34,13 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
34
34
  import { buildSessionProjection, SessionManager } from "@earendil-works/pi-coding-agent";
35
35
  import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
36
36
  import { capSpans, commandPreview, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
37
- import type { SpanContent, ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
37
+ import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
38
+ import { FILTER_EXPLANATION, PREFLAG_ENTRY, AUTO_FILTER_ENTRY, FILTER_REVISION_ENTRY, autoFilterEnabled, preflaggedTurns,
39
+ filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
40
+ import type { FilterTurn, TurnSpan } from "./lib/turn-filter.js";
41
+ import { FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint,
42
+ messageTokens, previewMessages, checkCheckpointBudget, checkContextBudget, isExpandedCheckpoint, checkpointContextMessages, retainedTailMessages, estimateContext } from "./lib/turn-context.js";
43
+ import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, TurnSlot } from "./lib/turn-context.js";
38
44
 
39
45
  // ============================================================================
40
46
  // Configuration
@@ -149,7 +155,7 @@ function persistCap(pi: ExtensionAPI, previous: CapSettings, next: CapSettings):
149
155
 
150
156
  // undefined means uncapped; null means cancel (never fall through to summary).
151
157
  async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal: AbortSignal | undefined,
152
- reason: string, size: { overhead: number; lineChars: number }): Promise<number | undefined | null> {
158
+ reason: string, size: { overhead: number; lineChars: number }, operation = "compaction"): Promise<number | undefined | null> {
153
159
  try {
154
160
  let state = capSettings(ctx.sessionManager.getBranch());
155
161
  for (;;) {
@@ -163,7 +169,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
163
169
  // Exactly the existing cap's test, including its minimum 500-char line budget.
164
170
  const needsTrim = size.lineChars > Math.max(500, limit - size.overhead);
165
171
  if (state.mode !== "warn" || !needsTrim) return limit;
166
- const warning = `Verbatim compaction would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
172
+ const warning = `Verbatim ${operation} would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
167
173
  if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
168
174
  ctx.ui.notify(`${warning} Applying the cap because no interactive UI is available.`, "warning");
169
175
  return limit;
@@ -172,7 +178,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
172
178
  ? "Overflow recovery: disabling the cap may leave too much context for the retry."
173
179
  : "Disabling the cap may leave too much context for the model.";
174
180
  const choice = await ctx.ui.select(`${warning}\n${risk}`, [
175
- "Apply trimming", "Disable cap for this session", "Change budget", "Cancel compaction",
181
+ "Apply trimming", "Disable cap for this session", "Change budget", `Cancel ${operation}`,
176
182
  ], { signal });
177
183
  if (signal?.aborted) return null;
178
184
  if (choice === "Apply trimming") return limit;
@@ -200,7 +206,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
200
206
  }
201
207
  }
202
208
  } catch (err) {
203
- if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); compaction cancelled`, "error");
209
+ if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); ${operation} cancelled`, "error");
204
210
  return null;
205
211
  }
206
212
  }
@@ -607,11 +613,12 @@ function bashOutputLabel(command: string, result: Record<string, any>): string {
607
613
  return labels.join("; ");
608
614
  }
609
615
 
610
- function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
616
+ function summarizeMessages(messages: AgentMessage[], cwd: string, owners?: (string | null)[]): TurnSpan {
611
617
  const results = pairedToolResults(messages);
612
- const lines: string[] = [];
618
+ const lines: string[] = [], turnIds: (string | null)[] = [];
613
619
  const tools: ToolLines = { version: 2, lines: [] };
614
- for (const msg of messages) {
620
+ for (const [messageIndex, msg] of messages.entries()) {
621
+ const start = lines.length;
615
622
  const m = msg as unknown as Record<string, any>;
616
623
  switch (msg.role) {
617
624
  case "user": {
@@ -662,8 +669,9 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
662
669
  default:
663
670
  break;
664
671
  }
672
+ for (let i = start; i < lines.length; i++) turnIds.push(owners?.[messageIndex] ?? null);
665
673
  }
666
- return { lines, ...(tools.lines.length ? { tools } : {}) };
674
+ return { lines, ...(owners ? { turnIds } : {}), ...(tools.lines.length ? { tools } : {}) };
667
675
  }
668
676
 
669
677
  // Startup reference retention is a lexical heuristic, not an interpretation of
@@ -907,7 +915,7 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
907
915
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
908
916
  * (the base is opaque; the session holds the raw history).
909
917
  */
910
- type StoredSpan = SpanContent & { at: string; reason: string; from?: string; to?: string };
918
+ type StoredSpan = TurnSpan & { at: string; reason: string; from?: string; to?: string };
911
919
 
912
920
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
913
921
  base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
@@ -917,7 +925,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
917
925
  if (e.type !== "compaction") return undefined;
918
926
  const d = (e as { details?: Record<string, any> }).details;
919
927
  if (!d || d.kind !== MECH_KIND || !Array.isArray(d.span?.lines)) return undefined;
920
- return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[]; tools?: ToolLines };
928
+ return d.span as TurnSpan & { at?: unknown; reason?: unknown; from?: unknown; to?: unknown };
921
929
  };
922
930
  let baseIdx = -1;
923
931
  for (let i = branchEntries.length - 1; i >= 0; i--) {
@@ -950,11 +958,159 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
950
958
  to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
951
959
  lines: sd.lines,
952
960
  tools: sd.tools,
961
+ turnIds: sd.turnIds,
953
962
  });
954
963
  }
955
964
  return { base, spans };
956
965
  }
957
966
 
967
+ interface FilterRevision {
968
+ compactionId: string;
969
+ summary: string;
970
+ filteredTurnIds: string[];
971
+ keptAsideTurnIds: string[];
972
+ fidelity?: TurnFidelities;
973
+ slots?: TurnSlot[];
974
+ }
975
+
976
+ function latestFilterRevision(entries: SessionEntry[]) {
977
+ const compaction = latestVerbatimCompaction(entries);
978
+ if (!compaction) return;
979
+ const entry = entries.slice(entries.indexOf(compaction) + 1).findLast((entry) =>
980
+ entry.type === "custom" && entry.customType === FILTER_REVISION_ENTRY &&
981
+ (entry.data as FilterRevision)?.compactionId === compaction.id);
982
+ return entry?.type === "custom" ? entry as typeof entry & { data: FilterRevision } : undefined;
983
+ }
984
+
985
+ function filteredTurns(entries: SessionEntry[]): string[] {
986
+ return latestFilterRevision(entries)?.data.filteredTurnIds ??
987
+ (latestVerbatimCompaction(entries)?.details as { filteredTurnIds?: string[] } | undefined)?.filteredTurnIds ?? [];
988
+ }
989
+
990
+ function keptAsideTurns(entries: SessionEntry[]): string[] {
991
+ return latestFilterRevision(entries)?.data.keptAsideTurnIds ??
992
+ (latestVerbatimCompaction(entries)?.details as { keptAsideTurnIds?: string[] } | undefined)?.keptAsideTurnIds ?? [];
993
+ }
994
+
995
+ function turnFidelities(entries: SessionEntry[]): TurnFidelities {
996
+ const revision = latestFilterRevision(entries);
997
+ return revision ? revision.data.fidelity ?? {} :
998
+ (latestVerbatimCompaction(entries)?.details as { fidelity?: TurnFidelities } | undefined)?.fidelity ?? {};
999
+ }
1000
+
1001
+ function projectCheckpoint(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
1002
+ const compaction = latestVerbatimCompaction(entries), revision = latestFilterRevision(entries);
1003
+ const fidelity = turnFidelities(entries);
1004
+ if (!compaction || (!revision && !Object.keys(fidelity).length)) return messages;
1005
+ const saved = revision?.data ?? compaction.details as { slots?: TurnSlot[] };
1006
+ if (messages.some((message) => isExpandedCheckpoint(message, revision?.data.summary ?? compaction.summary))) return messages;
1007
+ // Expand only the active checkpoint using generated offsets, not historical
1008
+ // text patterns. Original records and the retained tail remain untouched.
1009
+ return messages.flatMap((message) => message.role === "compactionSummary"
1010
+ ? expandCheckpoint(message, revision?.data.summary ?? message.summary, saved.slots ?? [], fidelity, entries, compaction.firstKeptEntryId)
1011
+ : [message]);
1012
+ }
1013
+
1014
+ // Match Pi's prepared messages to their source entries, including explicit
1015
+ // context replacements and generated custom messages. No raw bodies are stored.
1016
+ function preparedTurnOwners(entries: SessionEntry[], messages: AgentMessage[]): (string | null)[] {
1017
+ const owners = turnOwners(entries);
1018
+ const queues = new Map<string, (string | null)[]>();
1019
+ for (const projected of buildSessionProjection(entries).entries) {
1020
+ if (projected.sourceEntry.type === "compaction") continue;
1021
+ for (const message of projected.messages) {
1022
+ const key = JSON.stringify(message);
1023
+ const queue = queues.get(key) ?? [];
1024
+ queue.push(owners.get(projected.sourceEntry.id) ?? null);
1025
+ queues.set(key, queue);
1026
+ }
1027
+ }
1028
+ return messages.map((message) => queues.get(JSON.stringify(message))?.shift() ?? null);
1029
+ }
1030
+
1031
+ function filterChoices(entries: SessionEntry[], spans: TurnSpan[], excluded: Set<string>, firstKeptEntryId: string,
1032
+ retained: StartupReads, selected = excluded, fidelity: TurnFidelities = turnFidelities(entries)): FilterTurn[] {
1033
+ const owners = turnOwners(entries), flagged = preflaggedTurns(entries);
1034
+ const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
1035
+ const tailOwners = new Set(entries.slice(cut).filter((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary")
1036
+ .map((entry) => owners.get(entry.id)));
1037
+ const lines = new Map<string, string[]>();
1038
+ for (const span of spans) span.lines.forEach((line, index) => {
1039
+ const owner = span.turnIds?.[index];
1040
+ if (owner) { const group = lines.get(owner) ?? []; group.push(line); lines.set(owner, group); }
1041
+ });
1042
+ for (const read of retained.reads) {
1043
+ const owner = owners.get(read.entryId);
1044
+ if (owner && entries.findIndex((entry) => entry.id === read.entryId) < cut)
1045
+ lines.get(owner)?.push(`[Retained startup read: ${read.path}]\n${read.text.join("\n")}`);
1046
+ }
1047
+ return entries.filter((entry) => entry.type === "message" && entry.message.role === "user").map((entry) => {
1048
+ const content = lines.get(entry.id) ?? [];
1049
+ const deferred = tailOwners.has(entry.id);
1050
+ const unavailable = deferred ? (flagged.has(entry.id) ? undefined : "in retained recent tail")
1051
+ : content.length === 0 ? "not individually represented in checkpoint" : undefined;
1052
+ const cache = new Map<string, { tokens: number; lines: string[] }>();
1053
+ return { id: entry.id, fidelity: fidelity[entry.id], fidelityInfo: (mode) => {
1054
+ if (!cache.has(mode)) {
1055
+ const messages = fidelityMessages(entries, { [entry.id]: mode }, firstKeptEntryId).get(entry.id)!;
1056
+ cache.set(mode, { tokens: messageTokens(messages), lines: previewMessages(messages) });
1057
+ }
1058
+ return cache.get(mode)!;
1059
+ }, label: content[0] ?? `[User]: ${entry.type === "message" ? textOf((entry.message as any).content).text : ""}`,
1060
+ lines: content, selected: excluded.has(entry.id) || (!unavailable && selected.has(entry.id)),
1061
+ filtered: excluded.has(entry.id), deferred, unavailable };
1062
+ });
1063
+ }
1064
+
1065
+ function applyTurnSelection(choices: FilterTurn[], result: TurnSelection, preflags: Set<string>,
1066
+ excluded: Set<string>, keptAsides: Set<string>, fidelity: TurnFidelities): void {
1067
+ const selected = new Set(result.pruned);
1068
+ for (const turn of choices) {
1069
+ if (turn.unavailable) continue;
1070
+ if (!turn.deferred) {
1071
+ if (selected.has(turn.id)) excluded.add(turn.id); else excluded.delete(turn.id);
1072
+ if (!selected.has(turn.id) && result.fidelity[turn.id]) fidelity[turn.id] = result.fidelity[turn.id];
1073
+ else delete fidelity[turn.id];
1074
+ }
1075
+ if (preflags.has(turn.id)) {
1076
+ if (selected.has(turn.id)) keptAsides.delete(turn.id); else keptAsides.add(turn.id);
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ // Remove file-list traces belonging only to excluded turns. A path also used
1082
+ // by a kept turn stays listed; filtering is not a claim that mutations were undone.
1083
+ function excludedFilePaths(entries: SessionEntry[], excluded: Set<string>, firstKeptEntryId: string, cwd: string): Set<string> {
1084
+ const owners = turnOwners(entries), removed = new Set<string>(), kept = new Set<string>();
1085
+ const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
1086
+ for (const entry of entries.slice(0, cut)) {
1087
+ if (entry.type !== "message") continue;
1088
+ const m = entry.message as any;
1089
+ const calls = m.role === "assistant" ? (m.content ?? []).filter((b: any) => b.type === "toolCall")
1090
+ : m.role === "toolResult" ? m.nestedCalls?.calls ?? [] : [];
1091
+ for (const call of calls) {
1092
+ if (!["read", "write", "edit"].includes(call.name) || typeof call.arguments?.path !== "string") continue;
1093
+ (excluded.has(owners.get(entry.id) ?? "") ? removed : kept).add(fileEvidenceKey(call.arguments.path, cwd));
1094
+ }
1095
+ }
1096
+ return new Set([...removed].filter((file) => !kept.has(file)));
1097
+ }
1098
+
1099
+ function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, cwd: string,
1100
+ startup: StartupReads, readFiles: string[], modifiedFiles: string[], excluded: Set<string>, fidelity: TurnFidelities = {}) {
1101
+ if (!excluded.size && !Object.keys(fidelity).length) return { startupReads: startup, readFiles, modifiedFiles };
1102
+ const owners = turnOwners(entries);
1103
+ const removedPaths = excludedFilePaths(entries, excluded, firstKeptEntryId, cwd);
1104
+ return {
1105
+ startupReads: { ...startup, reads: startup.reads.filter((read) => {
1106
+ const owner = owners.get(read.entryId) ?? "";
1107
+ return !excluded.has(owner) && !fidelity[owner];
1108
+ }) },
1109
+ readFiles: readFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
1110
+ modifiedFiles: modifiedFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
1111
+ };
1112
+ }
1113
+
958
1114
  const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
959
1115
  const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
960
1116
  const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
@@ -965,9 +1121,10 @@ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_N
965
1121
  2. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
966
1122
  3. **Distinguish earlier claims from supporting evidence.** Retained assistant prose records what was said, not independent verification. If a task-relevant claim has uncertain provenance or conflicts with new evidence, check its supporting output (using \`context_lookup\` if hidden) or the current source before treating it as established; label unresolved claims unverified. Retrieved reasoning remains a historical hypothesis, and historical outputs do not establish current file or build/test state.`;
967
1123
 
1124
+ const REVISION_NOTE_PREFIX = "- Turn context revised: ";
968
1125
  const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript. ${RECOVERY_HISTORY_NOTE}`;
969
1126
 
970
- const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Prefer \`context_lookup\` with a specific historical question: a subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SCOPE_RULE} If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`; follow their pagination instructions for more detail. ${RECOVERY_FILESYSTEM_RULE}`;
1127
+ const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Use \`context_lookup\` with a specific historical question: a subagent searches this conversation's full session history and returns relevant findings. Use the recovery tools for history established by this conversation or its checkpoint, not for project discovery or exploration of other sessions. If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`.`;
971
1128
 
972
1129
  const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs and file lists omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Use `context_lookup` for omitted observations or provenance; inspect sources for current state.";
973
1130
 
@@ -982,18 +1139,19 @@ function latestVerbatimCompaction(entries: SessionEntry[]) {
982
1139
  }
983
1140
  }
984
1141
 
985
- function reorientationMessage(compactionId: string) {
986
- return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}\n\n${RECOVERY_RECAP}`,
987
- display: false, details: { compactionId } };
1142
+ function reorientationMessage(compactionId: string, filtered = false, revisionId = compactionId, fidelity = false) {
1143
+ return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}${filtered ? `\n\n${FILTER_EXPLANATION}` : ""}${fidelity ? `\n\n${FIDELITY_EXPLANATION}` : ""}\n\n${RECOVERY_RECAP}`,
1144
+ display: false, details: { compactionId, ...(revisionId !== compactionId ? { revisionId } : {}) } };
988
1145
  }
989
1146
 
990
1147
  function isReorientation(msg: AgentMessage): boolean {
991
1148
  return msg.role === "custom" && msg.customType === REORIENT_MESSAGE;
992
1149
  }
993
1150
 
994
- function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
995
- return msg.role === "custom" && msg.customType === REORIENT_MESSAGE &&
996
- (msg.details as { compactionId?: string } | undefined)?.compactionId === compactionId;
1151
+ function reorientationFor(msg: AgentMessage, compactionId: string, revisionId: string): boolean {
1152
+ const details = msg.role === "custom" ? msg.details as { compactionId?: string; revisionId?: string } | undefined : undefined;
1153
+ return isReorientation(msg) && details?.compactionId === compactionId &&
1154
+ (details.revisionId ?? details.compactionId) === revisionId;
997
1155
  }
998
1156
 
999
1157
  /** Keep one current, persisted checklist. Obsolete managed messages can still be
@@ -1002,12 +1160,13 @@ function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
1002
1160
  * Later requests keep it in history before the work that followed it. */
1003
1161
  function projectReorientation(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
1004
1162
  const compaction = latestVerbatimCompaction(entries);
1163
+ const anchor = latestFilterRevision(entries) ?? compaction;
1005
1164
  let selected = -1;
1006
1165
  for (let i = 0; i < messages.length; i++)
1007
- if (compaction && reorientationFor(messages[i], compaction.id)) selected = i;
1166
+ if (compaction && reorientationFor(messages[i], compaction.id, anchor!.id)) selected = i;
1008
1167
  const result = messages.filter((m, i) => !isReorientation(m) || i === selected);
1009
1168
  if (selected < 0 || !compaction) return result;
1010
- const answered = entries.slice(entries.indexOf(compaction) + 1).some((e) =>
1169
+ const answered = entries.slice(entries.indexOf(anchor!) + 1).some((e) =>
1011
1170
  e.type === "message" && e.message.role === "assistant" &&
1012
1171
  e.message.stopReason !== "aborted" && e.message.stopReason !== "error");
1013
1172
  if (!answered) {
@@ -1017,13 +1176,44 @@ function projectReorientation(messages: AgentMessage[], entries: SessionEntry[])
1017
1176
  return result;
1018
1177
  }
1019
1178
 
1179
+ /** Attribute generated notice costs without touching quoted historical text.
1180
+ * Notices occur only in the generated prefix, before SECTION_HEADER. Using the
1181
+ * real estimator on counterfactual messages keeps counts tied to current text.
1182
+ */
1183
+ function contextNoticeTokens(messages: AgentMessage[], reminder: AgentMessage): NoticeTokens {
1184
+ const first = messages.find((message) => message.role === "compactionSummary");
1185
+ if (!first || first.role !== "compactionSummary" || reminder.role !== "custom" || typeof reminder.content !== "string")
1186
+ throw new Error("Cannot identify generated context notices.");
1187
+ const end = first.summary.indexOf(SECTION_HEADER);
1188
+ if (end < 0) throw new Error("Cannot identify the checkpoint introduction.");
1189
+ let header = first.summary.slice(0, end), content = reminder.content;
1190
+ const body = first.summary.slice(end);
1191
+ const revision = header.split("\n").find((line) => line.startsWith(REVISION_NOTE_PREFIX)) ?? "";
1192
+ const notes: NoticeTokens = { pruning: 0, revision: 0, fidelity: 0 };
1193
+ const parts: [keyof NoticeTokens, string][] = [["pruning", FILTER_EXPLANATION], ["revision", revision], ["fidelity", FIDELITY_EXPLANATION]];
1194
+ for (const [kind, text] of parts) {
1195
+ if (!text) continue;
1196
+ const before = messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
1197
+ header = header.replace(`${text}\n`, "");
1198
+ if (kind !== "revision") content = content.replace(`\n\n${text}`, "");
1199
+ notes[kind] = before - messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
1200
+ }
1201
+ return notes;
1202
+ }
1203
+
1020
1204
  async function buildMechanicalSummary(opts: {
1021
1205
  reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
1022
1206
  tokensBefore: number;
1023
1207
  branchEntries: SessionEntry[];
1024
1208
  now: string;
1025
1209
  spanLines: string[]; // this compaction's own span, un-capped
1210
+ revisedAt?: string; // rebuild existing spans only; no new compaction or boundary
1026
1211
  spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
1212
+ spanTurnIds?: (string | null)[];
1213
+ filteredTurnIds?: string[];
1214
+ fidelity?: TurnFidelities;
1215
+ slots?: TurnSlot[]; // generated output placements; no raw payloads
1216
+ presentation?: { shortened: boolean }; // optional presentation-accounting output
1027
1217
  spanFrom?: string; // ISO timestamp of the first summarised message
1028
1218
  spanTo?: string; // ISO timestamp of the last summarised message
1029
1219
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
@@ -1035,8 +1225,20 @@ async function buildMechanicalSummary(opts: {
1035
1225
  chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
1036
1226
  }): Promise<string | undefined> {
1037
1227
  const { base, spans } = collectBaseAndSpans(opts.branchEntries);
1038
- const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1039
- lines: opts.spanLines, tools: opts.spanTools }];
1228
+ const fidelity = opts.fidelity ?? {};
1229
+ const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
1230
+ const nativeMessages = [...native.values()].flat();
1231
+ const nativeChars = messageTokens(nativeMessages) * 4;
1232
+ const nativeResults = pairedToolResults(nativeMessages), nativeReadPaths = new Set<string>();
1233
+ for (const message of nativeMessages) if (message.role === "assistant") for (const block of message.content) {
1234
+ if (block.type === "toolCall" && block.name === "read" && typeof block.arguments?.path === "string" && nativeResults.get(block)?.isError === false)
1235
+ nativeReadPaths.add(fileEvidenceKey(block.arguments.path, opts.cwd));
1236
+ }
1237
+ const rendered = fidelitySpans(filterSpans(opts.revisedAt ? spans : [...spans, {
1238
+ at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1239
+ lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
1240
+ }], new Set(opts.filteredTurnIds)), fidelity);
1241
+ const allSpans = rendered.spans;
1040
1242
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
1041
1243
 
1042
1244
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -1044,7 +1246,7 @@ async function buildMechanicalSummary(opts: {
1044
1246
  // exceed the budget by itself; warn rather than silently dropping evidence.
1045
1247
  const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
1046
1248
  const retainedReads = renderStartupReads(opts.startupReads, opts.branchEntries, opts.firstKeptEntryId);
1047
- let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
1249
+ let overhead = nativeChars + SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
1048
1250
  if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
1049
1251
  overhead += allSpans.reduce(
1050
1252
  (a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + TIGHTENED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
@@ -1068,7 +1270,10 @@ async function buildMechanicalSummary(opts: {
1068
1270
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
1069
1271
  if (maxChars !== undefined && retainedReads.length > maxChars)
1070
1272
  opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
1273
+ if (maxChars !== undefined && nativeChars > maxChars)
1274
+ opts.notify(`transparent-compact: full-fidelity turns alone are ~${nativeChars.toLocaleString()} estimated chars (budget ${maxChars.toLocaleString()}); they are kept un-capped. Only PROSE can be trimmed.`);
1071
1275
  const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
1276
+ if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
1072
1277
 
1073
1278
  const blocks: string[] = [];
1074
1279
  if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
@@ -1085,18 +1290,20 @@ async function buildMechanicalSummary(opts: {
1085
1290
  ].join("\n"));
1086
1291
  });
1087
1292
 
1088
- const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
1293
+ const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + (opts.revisedAt ? 0 : 1);
1089
1294
  const parts: string[] = [];
1090
1295
  parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
1091
1296
  parts.push(CHECKPOINT_EXPLANATION);
1297
+ if (opts.filteredTurnIds?.length) parts.push(FILTER_EXPLANATION);
1298
+ if (native.size) parts.push(FIDELITY_EXPLANATION);
1092
1299
  if (base?.kind === "model-summary") {
1093
1300
  parts.push(MIXED_CONTEXT_WARNING);
1094
1301
  opts.notify(MIXED_CONTEXT_WARNING);
1095
1302
  }
1096
1303
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
1304
+ if (opts.revisedAt) parts.push(`${REVISION_NOTE_PREFIX}${opts.revisedAt}. No additional history was compacted; the verbatim boundary is unchanged.`);
1097
1305
  parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming. Retained prose is a record of what was said, not verification of its claims. Tool signatures are display notation, not replayable shell commands: paths under the working directory become relative (`.` in commands); read ranges are requested lines; write/edit payloads become sizes/counts. New bash previews keep the first 160 encoded characters, followed by … when truncated, with escaped newlines. Thinking and most output are removed; selected output observations remain after →.");
1098
1306
  parts.push("- [tool error] means the result was flagged as an error; [unknown] means no safely matched result/status. Unlabelled does NOT establish exit 0 or passing tests. → exit N is a reported shell status; output: quotes/extracts selected output, not an inferred verdict. Everything shown is historical. Legacy [ok] only means not flagged as a tool error; legacy calls without status are unknown.");
1099
- parts.push("- Under size pressure, `tools-tightened` marks 120/80-character previews or grouped tool-only lines. Conversation prose and tool calls are retained unless `trimmed` is also marked. Tightening stops as soon as the budget fits; outcome observations and identifying file paths are not shortened by these stages.");
1100
1307
  parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Stored canonical spans are unchanged; their presentation may tighten under the cap.");
1101
1308
  parts.push(
1102
1309
  "- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that. The retained verbatim conversation begins after the explicit boundary marker at the end of this checkpoint.",
@@ -1121,6 +1328,7 @@ async function buildMechanicalSummary(opts: {
1121
1328
  const key = fileEvidenceKey(file, opts.cwd);
1122
1329
  const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
1123
1330
  ? "startup read output retained in checkpoint or tail; may be partial"
1331
+ : nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
1124
1332
  : modified && knownTail ? "no read-tool output in tail" : undefined);
1125
1333
  return `${checkpointPath(file, opts.cwd)}${label ? ` (${label})` : ""}`;
1126
1334
  };
@@ -1135,7 +1343,10 @@ async function buildMechanicalSummary(opts: {
1135
1343
  parts.push("");
1136
1344
  parts.push(closingLine);
1137
1345
 
1138
- return parts.join("\n");
1346
+ const summary = parts.join("\n");
1347
+ if (native.size && !opts.slots) throw new Error("Missing full-fidelity placement output.");
1348
+ opts.slots?.push(...locateSlots(summary, rendered.markers, fidelity));
1349
+ return summary;
1139
1350
  }
1140
1351
 
1141
1352
  // ============================================================================
@@ -1662,15 +1873,39 @@ function registerDirectTools(pi: ExtensionAPI): void {
1662
1873
  // ============================================================================
1663
1874
 
1664
1875
  export default function (pi: ExtensionAPI) {
1876
+ // Only bridge a specific /filter-later (or /fl) submission to its actual persisted user
1877
+ // message. The next input clears a failed/handled submission, so it cannot
1878
+ // accidentally flag a later ordinary prompt. Durable state uses raw entries.
1879
+ let requestedAside: { sessionId: string; text: string } | undefined;
1880
+ let asideInputSession: string | undefined;
1881
+ const clearAsideSubmission = () => { requestedAside = undefined; asideInputSession = undefined; };
1882
+ pi.on("input", (event, ctx) => {
1883
+ asideInputSession = event.source === "extension" && requestedAside?.sessionId === ctx.sessionManager.getSessionId() &&
1884
+ requestedAside.text === event.text ? requestedAside.sessionId : undefined;
1885
+ requestedAside = undefined;
1886
+ });
1887
+ pi.on("message_end", (event, ctx) => {
1888
+ if (event.message.role !== "user" || asideInputSession !== ctx.sessionManager.getSessionId()) return;
1889
+ asideInputSession = undefined;
1890
+ // Pi persists this user message immediately after message_end handlers.
1891
+ pi.appendEntry(PREFLAG_ENTRY, { timestamp: event.message.timestamp });
1892
+ });
1893
+ pi.on("session_shutdown", clearAsideSubmission);
1894
+ pi.on("session_tree", clearAsideSubmission);
1895
+
1665
1896
  // Starting/resuming a run persists the checklist AFTER the starting user
1666
1897
  // message. Existing branch history, not an in-memory flag, prevents repeats.
1667
1898
  pi.on("before_agent_start", (_event, ctx) => {
1668
1899
  const entries = ctx.sessionManager.getBranch();
1669
1900
  const compaction = latestVerbatimCompaction(entries);
1670
1901
  if (!compaction) return;
1671
- const found = entries.some((e) => e.type === "custom_message" && e.customType === REORIENT_MESSAGE &&
1672
- (e.details as { compactionId?: string } | undefined)?.compactionId === compaction.id);
1673
- if (!found) return { message: reorientationMessage(compaction.id) };
1902
+ const revisionId = latestFilterRevision(entries)?.id ?? compaction.id;
1903
+ const found = entries.some((e) => {
1904
+ if (e.type !== "custom_message" || e.customType !== REORIENT_MESSAGE) return false;
1905
+ const details = e.details as { compactionId?: string; revisionId?: string } | undefined;
1906
+ return details?.compactionId === compaction.id && (details.revisionId ?? details.compactionId) === revisionId;
1907
+ });
1908
+ if (!found) return { message: reorientationMessage(compaction.id, filteredTurns(entries).length > 0, revisionId, Object.keys(turnFidelities(entries)).length > 0) };
1674
1909
  });
1675
1910
 
1676
1911
  // Between-turn compaction and overflow continuation do not necessarily pass
@@ -1680,16 +1915,25 @@ export default function (pi: ExtensionAPI) {
1680
1915
  pi.on("session_compact", (event, ctx) => {
1681
1916
  if ((event.compactionEntry.details as { kind?: string } | undefined)?.kind !== MECH_KIND) return;
1682
1917
  if (event.willRetry || ctx.signal)
1683
- pi.sendMessage(reorientationMessage(event.compactionEntry.id), { deliverAs: "steer" });
1918
+ pi.sendMessage(reorientationMessage(event.compactionEntry.id,
1919
+ ((event.compactionEntry.details as { filteredTurnIds?: string[] }).filteredTurnIds?.length ?? 0) > 0, event.compactionEntry.id,
1920
+ Object.keys((event.compactionEntry.details as { fidelity?: TurnFidelities }).fidelity ?? {}).length > 0), { deliverAs: "steer" });
1684
1921
  });
1685
1922
 
1686
1923
  // Run after ordinary transforms and system/tool restoration. Preserve all
1687
1924
  // non-managed messages, remove old checklists even if they survive in the tail,
1688
1925
  // and keep the current one active on subsequent requests (not just the first).
1689
1926
  pi.on("context_with_system", (event, ctx) => {
1690
- const messages = projectReorientation(event.messages, ctx.sessionManager.getBranch());
1691
- if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i]))
1692
- return { messages };
1927
+ const entries = ctx.sessionManager.getBranch();
1928
+ try {
1929
+ const messages = projectReorientation(projectCheckpoint(event.messages, entries), entries);
1930
+ if (Object.keys(turnFidelities(entries)).length) checkContextBudget(messages, ctx);
1931
+ if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i])) return { messages };
1932
+ } catch (error) {
1933
+ ctx.ui.notify(`Full-fidelity context blocked: ${errMsg(error)}`, "error");
1934
+ ctx.abort(); // Hook errors alone do not cancel Pi requests. Abort explicitly.
1935
+ throw error;
1936
+ }
1693
1937
  });
1694
1938
 
1695
1939
  // Method selection never changes Pi's auto-compaction enabled setting.
@@ -1738,7 +1982,190 @@ export default function (pi: ExtensionAPI) {
1738
1982
  },
1739
1983
  });
1740
1984
 
1985
+ for (const name of ["filter-later", "fl"]) pi.registerCommand(name, {
1986
+ description: "Submit a normal user turn pre-flagged for future checkpoint filtering",
1987
+ handler: async (args, ctx) => {
1988
+ if (!args.trim()) { ctx.ui.notify(`Usage: /${name} <message>`, "error"); return; }
1989
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
1990
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before submitting an aside.", "warning"); return;
1991
+ }
1992
+ if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
1993
+ ctx.ui.notify(`/${name} requires verbatim compaction. Use /compaction-method verbatim first.`, "error"); return;
1994
+ }
1995
+ clearAsideSubmission();
1996
+ requestedAside = { sessionId: ctx.sessionManager.getSessionId(), text: args };
1997
+ try {
1998
+ pi.sendUserMessage(args);
1999
+ } catch (error) {
2000
+ clearAsideSubmission();
2001
+ throw error;
2002
+ }
2003
+ },
2004
+ });
2005
+
2006
+ pi.registerCommand("filter-auto", {
2007
+ description: "Show or set automatic application of pre-flagged asides: on|off (default off)",
2008
+ getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix))
2009
+ .map((value) => ({ value, label: value })),
2010
+ handler: async (args, ctx) => {
2011
+ const value = args.trim();
2012
+ if (value && value !== "on" && value !== "off") { ctx.ui.notify("Usage: /filter-auto [on|off]", "error"); return; }
2013
+ const previous = autoFilterEnabled(ctx.sessionManager.getBranch());
2014
+ const enabled = value ? value === "on" : previous;
2015
+ if (enabled !== previous) pi.appendEntry(AUTO_FILTER_ENTRY, { enabled });
2016
+ ctx.ui.notify(`Automatic aside filtering: ${enabled ? "on" : "off"}. Applies user pre-flags during verbatim threshold/overflow compaction; no picker or automatic relevance judgments.`, "info");
2017
+ },
2018
+ });
2019
+
2020
+ const filterTurns = {
2021
+ description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
2022
+ handler: async (args: string, ctx: ExtensionContext) => {
2023
+ if (args.trim()) { ctx.ui.notify("Usage: /filter-turns", "error"); return; }
2024
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
2025
+ ctx.ui.notify("/filter-turns requires the interactive terminal UI.", "error"); return;
2026
+ }
2027
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
2028
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
2029
+ }
2030
+ const entries = ctx.sessionManager.getBranch();
2031
+ const compaction = latestVerbatimCompaction(entries);
2032
+ if (compactionMethod(entries) !== "verbatim" || !compaction) {
2033
+ ctx.ui.notify("/filter-turns requires an existing verbatim checkpoint. Use /compact-filtered to create one.", "error"); return;
2034
+ }
2035
+ const canonical = compaction.details as { span: StoredSpan; startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[] };
2036
+ if (!canonical.span || !canonical.startupReads) {
2037
+ ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
2038
+ }
2039
+ const sessionId = ctx.sessionManager.getSessionId();
2040
+ const revisionId = latestFilterRevision(entries)?.id;
2041
+ const signal = new AbortController().signal;
2042
+ try {
2043
+ const previousExcluded = filteredTurns(entries), previousKept = keptAsideTurns(entries);
2044
+ const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
2045
+ const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
2046
+ const preflags = preflaggedTurns(entries);
2047
+ const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
2048
+ const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
2049
+ compaction.firstKeptEntryId, canonical.startupReads, proposed);
2050
+ const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
2051
+ pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
2052
+ kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
2053
+ JSON.stringify(Object.entries(modes).sort()) === JSON.stringify(Object.entries(previousFidelity).sort());
2054
+ const cap = capSettings(entries);
2055
+ const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }) => buildMechanicalSummary({
2056
+ reason: canonical.span.reason, tokensBefore: compaction.tokensBefore, branchEntries: entries,
2057
+ now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
2058
+ firstKeptEntryId: compaction.firstKeptEntryId,
2059
+ ...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
2060
+ canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, pruned, modes),
2061
+ cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
2062
+ chooseCap: preview ? async () => {
2063
+ if (cap.mode === "off") return undefined;
2064
+ const limit = capBudgetChars(cap.budget, ctx.model?.contextWindow);
2065
+ if (limit === undefined) throw new Error("Cannot preview a percentage cap without the model's context window.");
2066
+ return limit; // Warn-mode previews assume applying the current cap; never open a dialog or persist policy here.
2067
+ } : (size) => chooseCapBudget(pi, ctx, signal, "manual", size, "checkpoint update"),
2068
+ });
2069
+ const activeTools = new Set(pi.getActiveTools());
2070
+ const system: AgentMessage = { role: "system", content: ctx.getSystemPrompt(), timestamp: 0,
2071
+ toolsAdded: pi.getAllTools().filter((tool) => activeTools.has(tool.name))
2072
+ .map(({ name, description, parameters }) => ({ name, description, parameters })) };
2073
+ const tailTokens = messageTokens(retainedTailMessages(entries, compaction.firstKeptEntryId));
2074
+ const measure = (summary: string, placements: TurnSlot[], modes: TurnFidelities, pruned: Set<string>, shortening?: ContextEstimate["shortening"]): ContextEstimate => {
2075
+ const reminder: AgentMessage = { ...reorientationMessage(compaction.id, pruned.size > 0,
2076
+ revisionId ?? compaction.id, Object.keys(modes).length > 0), role: "custom", timestamp: 0 };
2077
+ const messages = checkpointContextMessages(summary, placements, modes, entries, compaction.firstKeptEntryId);
2078
+ return { ...estimateContext([system, ...messages, reminder], ctx), tailTokens,
2079
+ noticeTokens: contextNoticeTokens(messages, reminder), shortening };
2080
+ };
2081
+ const saved = latestFilterRevision(entries)?.data ?? { summary: compaction.summary,
2082
+ slots: (compaction.details as { slots?: TurnSlot[] }).slots };
2083
+ let baseline: Promise<ContextEstimate | undefined> | undefined;
2084
+ const estimateSelection = async (selection: TurnSelection): Promise<ContextEstimate> => {
2085
+ baseline ??= Promise.resolve().then(() => measure(saved.summary, saved.slots ?? [], previousFidelity, new Set(previousExcluded))).catch(() => undefined);
2086
+ const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
2087
+ applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
2088
+ const original = await baseline;
2089
+ if (unchanged(pruned, kept, modes)) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
2090
+ const presentation = { shortened: false };
2091
+ const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
2092
+ if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
2093
+ const estimated = measure(summary, placements, modes, pruned,
2094
+ presentation.shortened ? cap.mode === "warn" ? "confirmation" : "automatic" : undefined);
2095
+ return { ...estimated, delta: original ? estimated.tokens - original.tokens : undefined,
2096
+ noticeDelta: original?.noticeTokens && estimated.noticeTokens ? {
2097
+ pruning: (previousExcluded.length > 0) === (pruned.size > 0) ? 0 : estimated.noticeTokens.pruning - original.noticeTokens.pruning,
2098
+ revision: revisionId ? 0 : estimated.noticeTokens.revision - original.noticeTokens.revision,
2099
+ fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
2100
+ } : undefined };
2101
+ };
2102
+ const result = await pickFilteredTurns(ctx, choices, signal, estimateSelection);
2103
+ if (result === undefined) return;
2104
+ applyTurnSelection(choices, result, preflags, excluded, keptAsides, fidelity);
2105
+ if (unchanged(excluded, keptAsides, fidelity)) {
2106
+ ctx.ui.notify("No checkpoint turn-mode changes.", "info"); return;
2107
+ }
2108
+ const summary = await renderCheckpoint(excluded, fidelity, slots, false);
2109
+ if (summary === undefined) return;
2110
+ checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
2111
+ const current = ctx.sessionManager.getBranch();
2112
+ if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
2113
+ latestFilterRevision(current)?.id !== revisionId) {
2114
+ ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
2115
+ }
2116
+ pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
2117
+ filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
2118
+ ...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
2119
+ ctx.ui.notify("Checkpoint turn modes updated. No additional history compacted; recent messages and boundary unchanged.", "info");
2120
+ } catch (error) {
2121
+ ctx.ui.notify(`Checkpoint turn update cancelled: ${errMsg(error)}`, "error");
2122
+ }
2123
+ },
2124
+ };
2125
+
2126
+ pi.registerCommand("compact-filtered", {
2127
+ description: "Run ordinary compaction, then open checkpoint turn controls",
2128
+ handler: async (args, ctx) => {
2129
+ if (args.trim()) { ctx.ui.notify("Usage: /compact-filtered", "error"); return; }
2130
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
2131
+ ctx.ui.notify("/compact-filtered requires the interactive terminal UI.", "error"); return;
2132
+ }
2133
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
2134
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
2135
+ }
2136
+ if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
2137
+ ctx.ui.notify("/compact-filtered requires verbatim compaction. Use /compaction-method verbatim first.", "error"); return;
2138
+ }
2139
+ const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
2140
+ try {
2141
+ // compact() is callback-based. Wait for completion, not merely dispatch,
2142
+ // so the editor sees the saved checkpoint and the host is idle again.
2143
+ const result = await new Promise<{ summary: string; firstKeptEntryId: string }>((resolve, reject) => {
2144
+ ctx.compact({ onComplete: resolve, onError: reject });
2145
+ });
2146
+ const entries = ctx.sessionManager.getBranch(), current = latestVerbatimCompaction(entries);
2147
+ if (ctx.sessionManager.getSessionId() !== sessionId || !current || current.summary !== result.summary ||
2148
+ current.firstKeptEntryId !== result.firstKeptEntryId || (leafId && !entries.some((entry) => entry.id === leafId))) {
2149
+ ctx.ui.notify("Session/checkpoint changed; turn controls not opened.", "warning"); return;
2150
+ }
2151
+ } catch (error) {
2152
+ // These are Pi's current no-op outcomes, not general compaction failures.
2153
+ // Only an unchanged session with an existing checkpoint can be edited.
2154
+ const noOp = error instanceof Error && (error.message === "Already compacted" || error.message === "Nothing to compact (session too small)");
2155
+ if (!noOp || ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leafId ||
2156
+ !latestVerbatimCompaction(ctx.sessionManager.getBranch())) {
2157
+ ctx.ui.notify(`Compaction before turn editing failed: ${errMsg(error)}`, "error"); return;
2158
+ }
2159
+ }
2160
+ // The common editor rechecks idle/UI/method state. Escape here leaves the
2161
+ // already completed compaction intact; only the proposed revision is lost.
2162
+ await filterTurns.handler("", ctx);
2163
+ },
2164
+ });
2165
+ pi.registerCommand("filter-turns", filterTurns);
2166
+
1741
2167
  pi.on("session_start", (_event, ctx) => {
2168
+ clearAsideSubmission();
1742
2169
  const entries = ctx.sessionManager.getBranch();
1743
2170
  if (compactionMethod(entries) === "verbatim" && collectBaseAndSpans(entries).base?.kind === "model-summary") {
1744
2171
  ctx.ui.notify(MIXED_CONTEXT_WARNING, "warning");
@@ -1772,10 +2199,40 @@ export default function (pi: ExtensionAPI) {
1772
2199
  // --------------------------------------------------------------------------
1773
2200
  pi.on("session_before_compact", async (event, ctx) => {
1774
2201
  const { preparation, branchEntries, reason, signal } = event;
2202
+ const automaticFiltering = reason !== "manual" && autoFilterEnabled(branchEntries);
1775
2203
  if (!preparation) return;
1776
2204
  if (signal?.aborted) return;
1777
2205
  if (preparation.messagesToSummarize.length === 0 && preparation.turnPrefixMessages.length === 0) return;
1778
2206
  if (compactionMethod(ctx.sessionManager.getBranch()) === "summary") {
2207
+ const revision = latestFilterRevision(branchEntries);
2208
+ if (revision || Object.keys(turnFidelities(branchEntries)).length) {
2209
+ // Pi prepares from the saved compaction, not our request projection.
2210
+ // Summary mode must consume the revised checkpoint too, rather than
2211
+ // resurrecting filtered text or dropping standalone restorations.
2212
+ const active = latestVerbatimCompaction(branchEntries)!;
2213
+ preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
2214
+ .map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
2215
+ const canonical = latestVerbatimCompaction(branchEntries)!.details as {
2216
+ startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[];
2217
+ };
2218
+ const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
2219
+ canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
2220
+ const ops = preparation.fileOps;
2221
+ ops.read = new Set(visible.readFiles);
2222
+ ops.edited = new Set(visible.modifiedFiles);
2223
+ ops.written = new Set();
2224
+ for (const message of [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages]) {
2225
+ const calls = message.role === "assistant" ? message.content.filter((block) => block.type === "toolCall")
2226
+ : message.role === "toolResult" ? message.nestedCalls?.calls ?? [] : [];
2227
+ for (const call of calls) {
2228
+ const file = (call.arguments as { path?: unknown } | undefined)?.path;
2229
+ if (typeof file !== "string" || !file) continue;
2230
+ if (call.name === "read") ops.read.add(file);
2231
+ else if (call.name === "write") ops.written.add(file);
2232
+ else if (call.name === "edit") ops.edited.add(file);
2233
+ }
2234
+ }
2235
+ }
1779
2236
  return; // No override: Pi runs its normal model-generated compaction.
1780
2237
  }
1781
2238
 
@@ -1800,8 +2257,8 @@ export default function (pi: ExtensionAPI) {
1800
2257
  }
1801
2258
 
1802
2259
  const modified = new Set([...(fileOps?.edited ?? []), ...(fileOps?.written ?? [])]);
1803
- const modifiedFiles = [...modified].sort();
1804
- const readFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
2260
+ const canonicalModifiedFiles = [...modified].sort();
2261
+ const canonicalReadFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
1805
2262
 
1806
2263
  // 2) The new span. Pi's preparation span is [previous cut, current cut)
1807
2264
  // — it includes the previous compaction's retained tail (verified
@@ -1821,12 +2278,26 @@ export default function (pi: ExtensionAPI) {
1821
2278
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1822
2279
  const spanFrom = toIso(msgTs(allMessages[0]));
1823
2280
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1824
- const span = summarizeMessages(allMessages, ctx.cwd);
2281
+ const span = summarizeMessages(allMessages, ctx.cwd, preparedTurnOwners(branchEntries, allMessages));
1825
2282
  const spanLines = span.lines;
1826
2283
 
1827
2284
  // 3) Freeze startup references after the second user prompt, then carry
1828
2285
  // their original outputs forward outside the trimmable conversation spans.
1829
- const retained = startupReads(branchEntries, ctx);
2286
+ const canonicalRetained = startupReads(branchEntries, ctx);
2287
+ const excluded = new Set(filteredTurns(branchEntries));
2288
+ const keptAsides = new Set(keptAsideTurns(branchEntries));
2289
+ const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
2290
+ if (automaticFiltering) {
2291
+ const preflags = preflaggedTurns(branchEntries);
2292
+ const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
2293
+ const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
2294
+ excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
2295
+ for (const turn of choices)
2296
+ if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
2297
+ }
2298
+ const filteredTurnIds = [...excluded];
2299
+ const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
2300
+ canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded, fidelity);
1830
2301
  const summary = await buildMechanicalSummary({
1831
2302
  reason, // pi's raw reason, passed through unchanged
1832
2303
  tokensBefore: preparation.tokensBefore,
@@ -1834,17 +2305,18 @@ export default function (pi: ExtensionAPI) {
1834
2305
  now: nowIso,
1835
2306
  spanLines,
1836
2307
  spanTools: span.tools,
2308
+ spanTurnIds: span.turnIds,
2309
+ filteredTurnIds, fidelity, slots,
1837
2310
  spanFrom,
1838
2311
  spanTo,
1839
2312
  firstKeptEntryId: preparation.firstKeptEntryId,
1840
- readFiles,
1841
- modifiedFiles,
1842
- startupReads: retained,
2313
+ ...evidence,
1843
2314
  cwd: ctx.cwd,
1844
2315
  notify: (m) => ctx.ui?.notify?.(m, "warning"),
1845
2316
  chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
1846
2317
  });
1847
2318
  if (summary === undefined || signal?.aborted) return { cancel: true };
2319
+ checkCheckpointBudget(summary, slots, fidelity, branchEntries, preparation.firstKeptEntryId, ctx);
1848
2320
 
1849
2321
  ctx.ui?.notify?.(
1850
2322
  `transparent-compact: ~${preparation.tokensBefore.toLocaleString()} tokens -> verbatim checkpoint; full transcript kept in the session`,
@@ -1858,19 +2330,26 @@ export default function (pi: ExtensionAPI) {
1858
2330
  tokensBefore: preparation.tokensBefore,
1859
2331
  details: {
1860
2332
  kind: MECH_KIND,
1861
- readFiles,
1862
- modifiedFiles,
1863
- startupReads: retained,
2333
+ // Canonical metadata stays reversible; only the rendered checkpoint
2334
+ // masks file paths/startup reads owned by excluded turns.
2335
+ readFiles: canonicalReadFiles,
2336
+ modifiedFiles: canonicalModifiedFiles,
2337
+ startupReads: canonicalRetained,
2338
+ ...(filteredTurnIds.length ? { filteredTurnIds } : {}),
2339
+ ...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
2340
+ ...(Object.keys(fidelity).length ? { fidelity, slots } : {}),
1864
2341
  // Only this compaction's own span (un-capped lines). Earlier spans
1865
2342
  // are re-rendered from the earlier entries' details — no nesting.
1866
2343
  span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
1867
- lines: spanLines, ...(span.tools ? { tools: span.tools } : {}) },
2344
+ lines: spanLines, turnIds: span.turnIds, ...(span.tools ? { tools: span.tools } : {}) },
1868
2345
  },
1869
2346
  },
1870
2347
  };
1871
2348
  } catch (err) {
1872
- ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); falling back to Pi's summary compaction`, "error");
1873
- return;
2349
+ // Never replace a filtered checkpoint with an unfiltered model summary.
2350
+ const preserveFiltering = automaticFiltering || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
2351
+ ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
2352
+ return preserveFiltering ? { cancel: true } : undefined;
1874
2353
  }
1875
2354
  });
1876
2355