@foliox/transparent-compact-pi 0.11.1 → 0.11.3

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.
@@ -0,0 +1,105 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { episodeCoverage, readMode, selectedEpisode } from "./read-retention.js";
5
+ import type { ReadFile, ReadMode, ReadRetention } from "./read-retention.js";
6
+
7
+ const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
8
+
9
+ /** Local draft only. Enter reviews; a second Enter saves. Escape from the
10
+ * preview returns to selection, Escape from selection discards the draft. */
11
+ export async function pickRetainedReads(ctx: ExtensionContext, files: ReadFile[], initial: ReadRetention,
12
+ filtered: Set<string>, signal: AbortSignal): Promise<ReadRetention | undefined> {
13
+ return ctx.ui.custom<ReadRetention | undefined>((tui, theme, kb, done) => {
14
+ const state: ReadRetention = { defaults: { ...initial.defaults }, overrides: { ...initial.overrides } };
15
+ let cursor = 0, top = 0, scroll = 0, latestOrder = false;
16
+ let preview: "read" | "review" | undefined;
17
+ let wrapped: { width: number; lines: string[] } | undefined;
18
+ let finished = false;
19
+ const rows = () => latestOrder ? [...files].sort((a, b) => a.episodes.at(-1)!.reads.at(-1)!.order - b.episodes.at(-1)!.reads.at(-1)!.order) : files;
20
+ const pageSize = () => Math.max(1, tui.terminal.rows - 9);
21
+ const episodeOf = (file: ReadFile) => selectedEpisode(file, readMode(state, file.path) === "off" ? "first" : readMode(state, file.path))!;
22
+ const flagged = (file: ReadFile) => episodeOf(file).reads.some((r) => filtered.has(r.owner ?? ""));
23
+ const chars = (file: ReadFile) => episodeOf(file).reads.reduce((n, r) => n + r.text.join("\n").length, 0);
24
+ const heading = (file: ReadFile) => `${readMode(state, file.path).toUpperCase().padEnd(6)} ${file.path} · ${episodeCoverage(episodeOf(file))}` +
25
+ ` · ${chars(file).toLocaleString()} chars${flagged(file) ? " [filtered turn]" : ""}`;
26
+ const contents = (file: ReadFile) => [heading(file), ...episodeOf(file).reads.flatMap((r) => [
27
+ `Entry ${r.entryId} · offset ${r.offset}${r.limit === undefined ? "" : ` · limit ${r.limit}`}${filtered.has(r.owner ?? "") ? " · filtered turn" : ""}`,
28
+ ...r.text.join("\n").split("\n"), "",
29
+ ])];
30
+ const previewLines = () => preview === "read" ? contents(rows()[cursor]) : [
31
+ "Selected outputs (OFF adds no retained copy; normal tail/native content is unchanged):", "",
32
+ ...files.filter((f) => readMode(state, f.path) !== "off").flatMap(contents),
33
+ ...(files.some((f) => readMode(state, f.path) !== "off") ? [] : ["No additional read outputs selected."]),
34
+ ];
35
+ const invalidate = () => { wrapped = undefined; };
36
+ const finish = (value: ReadRetention | undefined) => {
37
+ if (finished) return;
38
+ finished = true; signal.removeEventListener("abort", abort); done(value);
39
+ };
40
+ const abort = () => finish(undefined);
41
+ signal.addEventListener("abort", abort, { once: true });
42
+ if (signal.aborted) queueMicrotask(abort);
43
+ return {
44
+ capturesViewportInput: true,
45
+ render(width: number): string[] {
46
+ const height = pageSize(), ordered = rows();
47
+ const line = (text: string) => truncateToWidth(text, width);
48
+ const selected = files.filter((f) => readMode(state, f.path) !== "off");
49
+ const total = selected.reduce((n, f) => n + chars(f), 0);
50
+ const out = [theme.fg("accent", theme.bold(`Read retention · ${preview === "review" ? "Review" : preview ? "Output preview" : "Select"}`)),
51
+ theme.fg("muted", `${selected.length} files · ${total.toLocaleString()} output chars (~${Math.ceil(total / 4).toLocaleString()} tokens); tail/native duplicates omitted`),
52
+ theme.fg("muted", preview ? "Historical outputs; retained independently of turn filtering." : `Order: ${latestOrder ? "latest" : "first"} read ascending · OFF / FIRST / LATEST`), ""];
53
+ if (preview) {
54
+ if (!wrapped || wrapped.width !== width) wrapped = { width, lines: previewLines().flatMap((s) => wrapTextWithAnsi(clean(s), Math.max(1, width))) };
55
+ scroll = Math.max(0, Math.min(scroll, wrapped.lines.length - height));
56
+ out.push(...wrapped.lines.slice(scroll, scroll + height));
57
+ } else {
58
+ cursor = Math.max(0, Math.min(cursor, ordered.length - 1));
59
+ top = Math.max(0, Math.min(top, cursor, ordered.length - height));
60
+ if (cursor >= top + height) top = cursor - height + 1;
61
+ for (let i = top; i < Math.min(top + height, ordered.length); i++) {
62
+ const file = ordered[i];
63
+ const text = clean(`${i === cursor ? "›" : " "} ${heading(file)}`);
64
+ out.push(i === cursor ? theme.bg("selectedBg", line(text)) : line(text));
65
+ }
66
+ if (!ordered.length) out.push("No successful text read outputs in this branch.");
67
+ }
68
+ out.push("", theme.fg("accent", preview ? "↑/↓ PgUp/PgDn Home/End: scroll · Esc: back" : "↑/↓: move · Space/f: mode · o: order · p/→: full preview · d: declared default"),
69
+ theme.fg("accent", preview === "review" ? "Enter: confirm & save" : preview ? "←/Esc: back" : "Enter: review & save · Esc: cancel"));
70
+ return out.map(line).slice(0, Math.max(1, tui.terminal.rows));
71
+ },
72
+ handleInput(data: string) {
73
+ const ordered = rows(), file = ordered[cursor], page = pageSize();
74
+ if (kb.matches(data, "tui.select.cancel") || (preview && matchesKey(data, Key.left))) {
75
+ if (preview) { preview = undefined; scroll = 0; } else { finish(undefined); return; }
76
+ } else if (preview) {
77
+ if (preview === "review" && kb.matches(data, "tui.select.confirm")) { finish(state); return; }
78
+ if (kb.matches(data, "tui.select.up")) scroll--;
79
+ else if (kb.matches(data, "tui.select.down")) scroll++;
80
+ else if (matchesKey(data, Key.pageUp)) scroll -= page;
81
+ else if (matchesKey(data, Key.pageDown)) scroll += page;
82
+ else if (matchesKey(data, Key.home)) scroll = 0;
83
+ else if (matchesKey(data, Key.end)) scroll = Number.MAX_SAFE_INTEGER;
84
+ // Keep the wrapped preview when only scrolling.
85
+ tui.requestRender(); return;
86
+ } else if (kb.matches(data, "tui.select.up")) cursor = Math.max(0, cursor - 1);
87
+ else if (kb.matches(data, "tui.select.down")) cursor = Math.min(ordered.length - 1, cursor + 1);
88
+ else if (matchesKey(data, Key.pageUp)) cursor = Math.max(0, cursor - page);
89
+ else if (matchesKey(data, Key.pageDown)) cursor = Math.min(ordered.length - 1, cursor + page);
90
+ else if (matchesKey(data, Key.home)) cursor = 0;
91
+ else if (matchesKey(data, Key.end)) cursor = ordered.length - 1;
92
+ else if (matchesKey(data, "o")) { latestOrder = !latestOrder; cursor = file ? rows().indexOf(file) : 0; top = 0; }
93
+ else if (file && (matchesKey(data, Key.space) || matchesKey(data, "f"))) {
94
+ const modes: ReadMode[] = ["off", "first", "latest"];
95
+ state.overrides[file.path] = modes[(modes.indexOf(readMode(state, file.path)) + 1) % modes.length];
96
+ } else if (file && matchesKey(data, "d")) delete state.overrides[file.path];
97
+ else if (file && (matchesKey(data, "p") || matchesKey(data, Key.right))) { preview = "read"; scroll = 0; }
98
+ else if (kb.matches(data, "tui.select.confirm")) { preview = "review"; scroll = 0; }
99
+ invalidate(); tui.requestRender();
100
+ },
101
+ invalidate,
102
+ dispose() { finished = true; signal.removeEventListener("abort", abort); },
103
+ };
104
+ });
105
+ }
@@ -0,0 +1,228 @@
1
+ import path from "node:path";
2
+ import { homedir } from "node:os";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
5
+ import { originalProjection, turnOwners } from "./turn-context.js";
6
+ import type { TurnSpan } from "./turn-filter.js";
7
+
8
+ export type ReadMode = "off" | "first" | "latest";
9
+ export interface ReadRetention {
10
+ defaults: Record<string, ReadMode>;
11
+ overrides: Record<string, ReadMode>;
12
+ }
13
+ export const READ_RETENTION_ENTRY = "transparent-compact:read-retention";
14
+ export interface ReadOutput {
15
+ entryId: string;
16
+ path: string;
17
+ owner: string | null;
18
+ order: number;
19
+ offset: number;
20
+ limit?: number;
21
+ text: string[];
22
+ end?: number;
23
+ total?: number;
24
+ eof: boolean;
25
+ }
26
+ export interface ReadEpisode { path: string; reads: ReadOutput[] }
27
+ export interface ReadFile { path: string; episodes: ReadEpisode[] }
28
+
29
+ /** Lexical tool-path normalization, never stat/realpath or a symlink claim. */
30
+ export function readPath(file: string, cwd: string): string {
31
+ let normalized = file.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
32
+ if (normalized === "~") normalized = homedir();
33
+ else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) normalized = path.join(homedir(), normalized.slice(2));
34
+ if (normalized.startsWith("file://")) {
35
+ try { normalized = fileURLToPath(normalized); } catch { /* Keep unknown syntax literal. */ }
36
+ }
37
+ return path.resolve(cwd, normalized);
38
+ }
39
+
40
+ /** Coverage describes delivered text, not the requested limit. Recognize Pi's
41
+ * terminal pagination notices; unrecognized truncation stays unknown. */
42
+ function coverage(text: string[], offset: number, limit: number | undefined, details: any): Pick<ReadOutput, "end" | "total" | "eof"> {
43
+ const body = text.join("\n");
44
+ const showing = body.match(/\n\n\[Showing lines (\d+)[-–](\d+) of (\d+)(?: \([^\n]*\))?\. Use offset=\d+ to continue\.\]$/);
45
+ if (showing && Number(showing[1]) === offset) return { end: Number(showing[2]), total: Number(showing[3]), eof: false };
46
+ const more = body.match(/\n\n\[(\d+) more lines in file\. Use offset=(\d+) to continue\.\]$/);
47
+ if (more) return { end: Number(more[2]) - 1, total: Number(more[2]) - 1 + Number(more[1]), eof: false };
48
+ if (details?.truncation?.truncated || /\[(?:Output truncated|Line \d+ is .*exceeds|Showing lines|\d+ more lines in file)/.test(body)) return { eof: false };
49
+ // Ordinary text-only read results without a pagination notice reach EOF.
50
+ // A bounded read returning exactly its limit is conservative: EOF unconfirmed.
51
+ const count = body === "" ? 0 : body.split("\n").length;
52
+ const end = offset + count - 1, eof = limit === undefined || count < limit;
53
+ return { end, eof, ...(eof ? { total: end } : {}) };
54
+ }
55
+
56
+ /** Read candidates come from the context-edited original projection, not from
57
+ * summaries. Tool source order defines adjacency even for parallel batches. */
58
+ export function readCatalog(entries: SessionEntry[], cwd: string): ReadFile[] {
59
+ const owners = turnOwners(entries);
60
+ const projected = originalProjection(entries).flatMap(({ sourceEntry, messages }) => messages.map((message) => ({ entry: sourceEntry, message })));
61
+ // An omitted/replaced tool operation may still have mutated the filesystem.
62
+ // It remains an episode boundary even though its content is not resurrected.
63
+ const visibleEntries = new Set(projected.map((p) => p.entry.id));
64
+ const visibleCalls = new Map<string, Set<string>>();
65
+ for (const { entry, message } of projected) if (message.role === "assistant")
66
+ visibleCalls.set(entry.id, new Set(message.content.filter((b) => b.type === "toolCall").map((b) => b.id)));
67
+ const hiddenBefore = new Map<string, number>(), changedBatches = new Set<string>();
68
+ let hidden = 0;
69
+ for (const entry of entries) {
70
+ if (entry.type === "message" && entry.message.role === "assistant") {
71
+ const missing = entry.message.content.filter((b) => b.type === "toolCall" && !visibleCalls.get(entry.id)?.has(b.id)).length;
72
+ hidden += missing;
73
+ if (missing) changedBatches.add(entry.id);
74
+ }
75
+ else if (entry.type === "message" && entry.message.role === "bashExecution" && !visibleEntries.has(entry.id)) hidden++;
76
+ hiddenBefore.set(entry.id, hidden);
77
+ }
78
+ const counts = new Map<string, number>();
79
+ for (const { message } of projected) if (message.role === "assistant")
80
+ for (const block of message.content) if (block.type === "toolCall") counts.set(block.id, (counts.get(block.id) ?? 0) + 1);
81
+ type Call = { args: any; name: string; order: number; owner: string | null };
82
+ const pending = new Map<string, Call>();
83
+ const reads: ReadOutput[] = [];
84
+ let order = 0, seenHidden = 0;
85
+ for (const { entry, message } of projected) {
86
+ const hidden = hiddenBefore.get(entry.id)!;
87
+ if (hidden !== seenHidden) { order += hidden - seenHidden; pending.clear(); seenHidden = hidden; }
88
+ if (message.role === "user") { order++; pending.clear(); }
89
+ else if (message.role === "bashExecution") order++;
90
+ else if (message.role === "assistant") {
91
+ pending.clear();
92
+ for (const block of message.content) if (block.type === "toolCall") {
93
+ if (changedBatches.has(entry.id)) order++; // Never join across an operation removed inside a batch.
94
+ const call = { args: block.arguments, name: block.name, order: order++, owner: owners.get(entry.id) ?? null };
95
+ if (counts.get(block.id) === 1) pending.set(block.id, call);
96
+ }
97
+ } else if (message.role === "toolResult") {
98
+ const call = pending.get(message.toolCallId);
99
+ pending.delete(message.toolCallId);
100
+ if (!call || call.name !== "read" || message.toolName !== call.name || message.isError !== false ||
101
+ typeof call.args?.path !== "string" || !message.content.length || message.content.some((b) => b.type !== "text" || typeof b.text !== "string")) continue;
102
+ const offset = call.args.offset ?? 1, limit = call.args.limit ?? undefined;
103
+ if (!Number.isSafeInteger(offset) || offset < 1 || (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1))) continue;
104
+ const text = message.content.map((b) => (b as { text: string }).text);
105
+ reads.push({ entryId: entry.id, path: readPath(call.args.path, cwd), owner: call.owner, order: call.order, offset,
106
+ ...(limit === undefined ? {} : { limit }), text, ...coverage(text, offset, limit, message.details) });
107
+ }
108
+ }
109
+ const files = new Map<string, ReadFile>();
110
+ let previous: ReadOutput | undefined, episode: ReadEpisode | undefined;
111
+ for (const read of reads.sort((a, b) => a.order - b.order)) {
112
+ const file = files.get(read.path) ?? { path: read.path, episodes: [] };
113
+ files.set(read.path, file);
114
+ if (!previous || previous.path !== read.path || previous.owner !== read.owner || previous.order + 1 !== read.order ||
115
+ previous.eof || previous.end === undefined || read.offset <= previous.offset || read.offset > previous.end + 1 ||
116
+ (previous.total !== undefined && read.total !== undefined && previous.total !== read.total)) {
117
+ episode = { path: read.path, reads: [] };
118
+ file.episodes.push(episode);
119
+ }
120
+ episode!.reads.push(read);
121
+ previous = read;
122
+ }
123
+ return [...files.values()];
124
+ }
125
+
126
+ const instructionFile = (file: string) => /^(AGENTS(?:\.override)?|CLAUDE)\.md$/i.test(path.basename(file));
127
+ export function retentionOverrides(entries: SessionEntry[]): Record<string, ReadMode> {
128
+ for (let i = entries.length - 1; i >= 0; i--) {
129
+ const entry = entries[i];
130
+ const state = entry.type === "compaction" ? (entry.details as { readRetention?: ReadRetention })?.readRetention
131
+ : entry.type === "custom" && entry.customType === "transparent-compact:filter-revision" ? (entry.data as { readRetention?: ReadRetention })?.readRetention
132
+ : entry.type === "custom" && entry.customType === READ_RETENTION_ENTRY ? entry.data as ReadRetention : undefined;
133
+ if (state) return { ...state.overrides };
134
+ }
135
+ return {};
136
+ }
137
+
138
+ export function readRetentionState(entries: SessionEntry[], ctx: ExtensionContext, catalog = readCatalog(entries, ctx.cwd)): ReadRetention {
139
+ const sources = new Map<string, string[]>();
140
+ for (const file of catalog) if (instructionFile(file.path)) {
141
+ const episode = file.episodes.at(-1)!;
142
+ // Parse each output independently; never fabricate declarations across gaps.
143
+ sources.set(file.path, episode.reads.map((r) => r.text.join("\n")));
144
+ }
145
+ const contextFiles = ctx.getSystemPromptOptions?.().contextFiles ?? [];
146
+ for (const file of contextFiles) if (instructionFile(file.path)) sources.set(readPath(file.path, ctx.cwd), [file.content]);
147
+ if (!contextFiles.length) for (const match of (ctx.getSystemPrompt?.() ?? "").matchAll(/<project_instructions path="([^"]+)">\n?([\s\S]*?)<\/project_instructions>/g))
148
+ if (instructionFile(match[1])) sources.set(readPath(match[1], ctx.cwd), [match[2]]);
149
+ const defaults: Record<string, ReadMode> = {};
150
+ for (const [source, contents] of sources) for (const content of contents) for (const block of content.matchAll(/<retain-reads>\s*\n([\s\S]*?)<\/retain-reads>/g)) {
151
+ for (const line of block[1].split("\n")) {
152
+ let file = line.trim();
153
+ if (!file) continue;
154
+ const mode: ReadMode = file.startsWith("latest:") ? "latest" : "first";
155
+ if (mode === "latest") file = file.slice(7).trim();
156
+ if (file) defaults[readPath(file, path.dirname(source))] = mode;
157
+ }
158
+ }
159
+ return { defaults, overrides: retentionOverrides(entries) };
160
+ }
161
+
162
+ export const readMode = (state: ReadRetention, file: string): ReadMode => state.overrides[file] ?? state.defaults[file] ?? "off";
163
+ export function selectedEpisode(file: ReadFile, mode: ReadMode): ReadEpisode | undefined {
164
+ return mode === "off" ? undefined : mode === "first" ? file.episodes[0] : file.episodes.at(-1);
165
+ }
166
+ export function selectedReads(catalog: ReadFile[], state: ReadRetention): ReadOutput[] {
167
+ return catalog.flatMap((file) => selectedEpisode(file, readMode(state, file.path))?.reads ?? []);
168
+ }
169
+ export function episodeCoverage(episode: ReadEpisode): string {
170
+ const first = episode.reads[0], last = episode.reads.at(-1)!;
171
+ const end = episode.reads.reduce<number | undefined>((end, r) => r.end === undefined || end === undefined ? undefined : Math.max(end, r.end), first.end);
172
+ const totals = new Set(episode.reads.flatMap((r) => r.total === undefined ? [] : [r.total]));
173
+ if (first.offset === 1 && last.eof && end !== undefined && totals.size <= 1) return "full";
174
+ return `partial: ${first.offset}–${end ?? "?"}${last.eof ? " (EOF)" : ""}`;
175
+ }
176
+
177
+ /** Only extra copies are rendered: OFF never touches normal tool/tail content.
178
+ * Turn pruning does not suppress explicit read retention. Native turns already
179
+ * contain their read output, so they and the recent tail need no duplicate. */
180
+ export function retainedReadOutputs(catalog: ReadFile[], state: ReadRetention, entries: SessionEntry[], boundary: string | undefined,
181
+ fidelity: Record<string, unknown>): ReadOutput[] {
182
+ const cut = entries.findIndex((e) => e.id === boundary);
183
+ const visible = new Set(cut < 0 ? [] : entries.slice(cut).map((e) => e.id));
184
+ return selectedReads(catalog, state).filter((r) => !visible.has(r.entryId) && !fidelity[r.owner ?? ""]);
185
+ }
186
+
187
+ function renderRetainedRead(read: ReadOutput, excluded: Set<string>): string {
188
+ return `<retained-read entry=${JSON.stringify(read.entryId)} path=${JSON.stringify(read.path)} offset=${read.offset}${read.limit === undefined ? "" : ` limit=${read.limit}`}${excluded.has(read.owner ?? "") ? ' filtered-turn="true"' : ""}>\n${read.text.join("\n")}\n</retained-read>`;
189
+ }
190
+
191
+ /** Stable comparison of selected copies; never used as a checkpoint section. */
192
+ export function renderRetainedReads(catalog: ReadFile[], state: ReadRetention, entries: SessionEntry[], boundary: string | undefined,
193
+ excluded: Set<string>, fidelity: Record<string, unknown>): string {
194
+ return retainedReadOutputs(catalog, state, entries, boundary, fidelity).map((read) => renderRetainedRead(read, excluded)).join("\n");
195
+ }
196
+
197
+ /** Insert outputs at recorded result boundaries, not by matching historical text.
198
+ * Source spans keep only IDs/indices, so OFF -> FIRST/LATEST remains reversible.
199
+ * Protected rows survive capping and are relocated by turn pruning as a group.
200
+ */
201
+ export function retainReadSpans<T extends TurnSpan>(spans: T[], reads: ReadOutput[], excluded: Set<string>) {
202
+ const selected = new Map(reads.map((read) => [read.entryId, read]));
203
+ const placed = new Set<string>();
204
+ const rendered = spans.map((span) => {
205
+ const positions = new Map<number, ReadOutput[]>();
206
+ for (const position of span.readPositions ?? []) {
207
+ const read = selected.get(position.entryId);
208
+ if (!read || placed.has(read.entryId)) continue;
209
+ if (!Number.isSafeInteger(position.index) || position.index < 0 || position.index > span.lines.length)
210
+ throw new Error(`Invalid retained-read position for ${read.entryId}.`);
211
+ placed.add(read.entryId);
212
+ const at = positions.get(position.index) ?? []; at.push(read); positions.set(position.index, at);
213
+ }
214
+ const lines: string[] = [], turnIds: (string | null)[] = [], protectedLines: number[] = [], indices = new Map<number, number>();
215
+ for (let index = 0; index <= span.lines.length; index++) {
216
+ for (const read of positions.get(index) ?? []) {
217
+ protectedLines.push(lines.length); lines.push(renderRetainedRead(read, excluded)); turnIds.push(read.owner);
218
+ }
219
+ if (index === span.lines.length) break;
220
+ indices.set(index, lines.length);
221
+ if (span.protectedLines?.includes(index)) protectedLines.push(lines.length);
222
+ lines.push(span.lines[index]); turnIds.push(span.turnIds?.[index] ?? null);
223
+ }
224
+ const tools = span.tools && { ...span.tools, lines: span.tools.lines.map((record) => ({ ...record, index: indices.get(record.index)! })) };
225
+ return { ...span, lines, turnIds, tools, protectedLines };
226
+ });
227
+ return { spans: rendered, unplaced: reads.filter((read) => !placed.has(read.entryId)) };
228
+ }
@@ -88,7 +88,11 @@ export function fidelitySpans<T extends TurnSpan>(spans: T[], fidelity: TurnFide
88
88
  const marker = `[Full-fidelity turn ${owner}: ${MODE_LABELS[fidelity[owner]]}; slot ${uuidv7()}]`;
89
89
  markers.set(owner, marker); protectedLines.push(lines.length); lines.push(marker); turnIds.push(owner);
90
90
  }
91
- } else { indices.set(index, lines.length); lines.push(line); turnIds.push(owner); }
91
+ } else {
92
+ indices.set(index, lines.length);
93
+ if (span.protectedLines?.includes(index)) protectedLines.push(lines.length);
94
+ lines.push(line); turnIds.push(owner);
95
+ }
92
96
  });
93
97
  const tools = span.tools && { ...span.tools, lines: span.tools.lines.filter((r) => indices.has(r.index))
94
98
  .map((r) => ({ ...r, index: indices.get(r.index)! })) };
@@ -34,16 +34,28 @@ export function preflaggedTurns(entries: SessionEntry[]): Set<string> {
34
34
  return flagged;
35
35
  }
36
36
  export const FILTER_EXPLANATION = "`[Turn manually filtered]` marks a user turn and its following agent/tool activity that the user chose to exclude as low-value context. Its contents remain retrievable from the full history. Do not recover filtered turns unless needed for the current task.";
37
- export interface TurnSpan extends SpanContent { turnIds?: (string | null)[] }
37
+ export interface ReadPosition { entryId: string; index: number }
38
+ export interface TurnSpan extends SpanContent {
39
+ turnIds?: (string | null)[];
40
+ /** Read-result entry IDs at boundaries between canonical prose/tool lines. */
41
+ readPositions?: ReadPosition[];
42
+ }
38
43
 
39
44
  /** Drop canonical lines before capping, retaining tool-record indices exactly.
40
- * A turn can cross compaction spans; emit only one marker at its first position.
45
+ * A turn can cross spans; its protected reads follow its single first marker.
41
46
  */
42
47
  export function filterSpans<T extends TurnSpan>(spans: T[], excluded: Set<string>): T[] {
43
48
  if (excluded.size === 0) return spans;
49
+ const retained = new Map<string, string[]>();
50
+ for (const span of spans) for (const index of span.protectedLines ?? []) {
51
+ const owner = span.turnIds?.[index];
52
+ if (owner && excluded.has(owner)) {
53
+ const lines = retained.get(owner) ?? []; lines.push(span.lines[index]); retained.set(owner, lines);
54
+ }
55
+ }
44
56
  const marked = new Set<string>();
45
57
  return spans.map((span) => {
46
- const lines: string[] = [], turnIds: (string | null)[] = [];
58
+ const lines: string[] = [], turnIds: (string | null)[] = [], protectedLines: number[] = [];
47
59
  const indices = new Map<number, number>();
48
60
  span.lines.forEach((line, index) => {
49
61
  const owner = span.turnIds?.[index] ?? null;
@@ -52,9 +64,13 @@ export function filterSpans<T extends TurnSpan>(spans: T[], excluded: Set<string
52
64
  marked.add(owner);
53
65
  lines.push(FILTER_MARKER);
54
66
  turnIds.push(owner);
67
+ for (const read of retained.get(owner) ?? []) {
68
+ protectedLines.push(lines.length); lines.push(read); turnIds.push(owner);
69
+ }
55
70
  }
56
71
  } else {
57
72
  indices.set(index, lines.length);
73
+ if (span.protectedLines?.includes(index)) protectedLines.push(lines.length);
58
74
  lines.push(line);
59
75
  turnIds.push(owner);
60
76
  }
@@ -62,7 +78,7 @@ export function filterSpans<T extends TurnSpan>(spans: T[], excluded: Set<string
62
78
  const tools: ToolLines | undefined = span.tools && { ...span.tools, lines: span.tools.lines
63
79
  .filter((record) => indices.has(record.index))
64
80
  .map((record) => ({ ...record, index: indices.get(record.index)! })) };
65
- return { ...span, lines, turnIds, tools };
81
+ return { ...span, lines, turnIds, tools, protectedLines };
66
82
  });
67
83
  }
68
84
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.11.1",
4
- "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
3
+ "version": "0.11.3",
4
+ "description": "Model-free, deterministic, and self-aware compaction; with session-backed subagent context recovery, and optional context pruning and fidelity controls.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi-extension",
@@ -9,7 +9,7 @@ description: "Guidance for using context_lookup after compaction: how to target
9
9
 
10
10
  Compaction hides earlier details from your current view. The original conversation
11
11
  history, including recorded tool outputs and your reasoning, is preserved in the
12
- session and can be retrieved. Retained startup reads and the uncompacted tail
12
+ session and can be retrieved. Selected retained reads and the uncompacted tail
13
13
  remain available as evidence; recover only hidden information needed for the task.
14
14
 
15
15
  Use the recovery tools for history established by this conversation or its checkpoint,
@@ -23,7 +23,7 @@ those tasks; use ordinary file tools as needed for the requested analysis.
23
23
 
24
24
  This skill pairs with the `@foliox/transparent-compact-pi` extension, which provides:
25
25
 
26
- - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Selected startup read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders and a recap follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
26
+ - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Explicitly selected read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders and a recap follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
27
27
  - **`context_lookup`** — the preferred first step for this recovery workflow: a subagent searches the full raw session branch in its **own** context and returns relevant findings. At lookup time, the extension mechanically renders the branch into entry-anchored text with an authoritative entry/section index, in memory.
28
28
  - **Bounded direct tools** — use `context_show_entry` for a specific detail hidden by compaction at a known ENTRY id returned by a recovery tool. If lookup findings are incomplete, use `context_list_entries` to locate an entry, `context_grep` to find a narrow passage, or `context_show_entry` to inspect a known entry. Their raw results enter this conversation; retrieve only what the question needs. For recovery of details hidden by compaction, these are the permitted direct tools, not filesystem access to session files.
29
29
 
@@ -37,7 +37,7 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
37
37
  - You are unsure where an earlier finding came from, what a command actually printed, or why you reached a conclusion.
38
38
  - Earlier notes conflict with new evidence and you need to check the historical evidence behind them.
39
39
 
40
- Tool stubs and file lists do not preserve the full supporting material. Most output
40
+ Tool stubs do not preserve the full supporting material. Most output
41
41
  and detailed payloads are omitted. Inline observations are historical, not verification
42
42
  of unshown details or current state. Unlabelled calls do not establish exit 0 or passing tests.
43
43
 
@@ -112,7 +112,7 @@ intended context parameters.
112
112
  2. Ask narrowly scoped questions using exact error strings, file paths, function names, or the command whose output you need. Recover tightly related details together; use separate queries for independent facts. Ask the subagent for evidence, not for a solution to the broader task.
113
113
  3. Findings cite ENTRY ids and the logical transcript name. Retain these citations when relying on recovered facts. The renderer preserves full thinking, text, tool-call arguments, and tool results, although individual search results have output limits.
114
114
  4. Distinguish **user instructions**, **observed tool output**, and **reasoning at the time**. A recovered `[thinking]` block is a historical hypothesis, not verified fact. Earlier assistant prose is not independently observed evidence either.
115
- 5. Historical tool output proves what was observed then, not what is true now. Review uncommitted work and re-verify current build/test state when needed. **Before using `write` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.** This is not a blanket reread requirement for small exact-match `edit`s. File-list annotations describe retained evidence as of the checkpoint, not live filesystem state; a read or write payload may already be visible in the tail.
115
+ 5. Historical tool output proves what was observed then, not what is true now. Review uncommitted work and re-verify current build/test state when needed. **Before using `write` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.** This is not a blanket reread requirement for small exact-match `edit`s.
116
116
  6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive.
117
117
 
118
118
  ## Independent exports