@foliox/transparent-compact-pi 0.8.8 → 0.9.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,178 @@
1
+ /** Pure checkpoint presentation and progressive size guard. No Pi, filesystem,
2
+ * model calls, or session mutation. Canonical span lines/records are never edited.
3
+ */
4
+ export const TOOL_PREFIX = "[Tools]: ";
5
+ export const NORMAL_PREVIEW_CHARS = 160;
6
+ export const TIGHTENED_ATTR = ' tools-tightened="true"';
7
+
8
+ // Encoded display fragments, NOT full commands or executable arguments.
9
+ // Retain the original prefix for every smaller head-only preview.
10
+ export interface CommandPreview { head: string; truncated?: boolean }
11
+ export interface ToolStub {
12
+ prefix: string;
13
+ command?: CommandPreview;
14
+ suffix: string;
15
+ }
16
+ export interface ToolLine {
17
+ index: number;
18
+ calls: ToolStub[];
19
+ /** Both adjacent messages must be tool-only before prefixes may be folded. */
20
+ mergeable: boolean;
21
+ }
22
+ export interface ToolLines { version: 2; lines: ToolLine[] }
23
+ export interface SpanContent { lines: string[]; tools?: ToolLines }
24
+ export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[] }
25
+
26
+ function headPrefix(text: string, max: number): string {
27
+ let end = Math.min(text.length, max);
28
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
29
+ return text.slice(0, end);
30
+ }
31
+ export function commandPreview(encoded: string): CommandPreview {
32
+ return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
33
+ : { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
34
+ }
35
+ export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
36
+ return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
37
+ }
38
+ export function renderToolStub(stub: ToolStub, max = NORMAL_PREVIEW_CHARS): string {
39
+ return stub.prefix + (stub.command ? renderCommand(stub.command, max) : "") + stub.suffix;
40
+ }
41
+ export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS): string {
42
+ return TOOL_PREFIX + calls.map((call) => renderToolStub(call, max)).join("; ");
43
+ }
44
+
45
+ // Stored records are optional/versioned. Require exact canonical round-tripping
46
+ // before using one; missing or invalid records leave text opaque.
47
+ function toolRecords(span: SpanContent): Map<number, ToolLine> {
48
+ const records = new Map<number, ToolLine>();
49
+ try {
50
+ const tools = span.tools;
51
+ if (!tools || tools.version !== 2 || !Array.isArray(tools.lines)) return records;
52
+ const seen = new Set<number>();
53
+ for (const record of tools.lines) {
54
+ if (!record || !Number.isSafeInteger(record.index) || record.index < 0 || record.index >= span.lines.length) continue;
55
+ if (seen.has(record.index)) { records.delete(record.index); continue; }
56
+ seen.add(record.index);
57
+ if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length) continue;
58
+ const valid = record.calls.every((call) => {
59
+ if (!call || typeof call.prefix !== "string" || typeof call.suffix !== "string") return false;
60
+ const p = call.command;
61
+ if (p === undefined) return true;
62
+ if (!p || typeof p.head !== "string") return false;
63
+ return p.head.length <= NORMAL_PREVIEW_CHARS &&
64
+ (p.truncated === undefined || typeof p.truncated === "boolean") &&
65
+ (p.truncated !== true || p.head.length >= NORMAL_PREVIEW_CHARS - 1);
66
+ });
67
+ if (valid && renderToolLine(record.calls) === span.lines[record.index]) records.set(record.index, record);
68
+ }
69
+ } catch { return new Map(); }
70
+ return records;
71
+ }
72
+
73
+ interface Row {
74
+ index: number;
75
+ text: string;
76
+ calls?: ToolStub[];
77
+ mergeable: boolean;
78
+ preview: number;
79
+ foldPrefix: boolean;
80
+ tightened: boolean;
81
+ }
82
+
83
+ /** Stop as soon as the budget fits: 120-char previews, then 80, adjacent
84
+ * tool-only prefixes, and finally the historical destructive cap.
85
+ * Every rung walks oldest first, across all spans (not just the new one).
86
+ */
87
+ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
88
+ const tightened = spans.map(() => false), trimmed = spans.map(() => false);
89
+ let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0);
90
+ if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed };
91
+ const states = spans.map((span) => {
92
+ const records = toolRecords(span);
93
+ return span.lines.map((text, index): Row => {
94
+ const record = records.get(index);
95
+ return { index, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
96
+ preview: NORMAL_PREVIEW_CHARS, foldPrefix: false, tightened: false };
97
+ });
98
+ });
99
+ const joined = (rows: Row[], i: number) => i > 0 && rows[i].foldPrefix && rows[i].calls && rows[i - 1].calls &&
100
+ rows[i].mergeable && rows[i - 1].mergeable && rows[i].index === rows[i - 1].index + 1;
101
+ const measure = () => states.reduce((n, rows) => n + rows.reduce((s, row, i) =>
102
+ s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0);
103
+ const finish = (): CappedSpans => ({
104
+ lines: states.map((rows, span) => {
105
+ const lines: string[] = [];
106
+ for (let i = 0; i < rows.length; i++) {
107
+ const row = rows[i];
108
+ if (joined(rows, i)) lines[lines.length - 1] += `; ${row.text.slice(TOOL_PREFIX.length)}`;
109
+ else lines.push(row.text);
110
+ if (row.tightened || joined(rows, i)) tightened[span] = true;
111
+ }
112
+ return lines;
113
+ }), tightened, trimmed,
114
+ });
115
+ const render = (row: Row) => renderToolLine(row.calls!, row.preview);
116
+ const update = (row: Row) => {
117
+ const text = render(row);
118
+ if (text.length < row.text.length) {
119
+ size += text.length - row.text.length;
120
+ row.text = text;
121
+ row.tightened = true;
122
+ }
123
+ };
124
+ for (const max of [120, 80]) {
125
+ for (const rows of states) for (const row of rows) {
126
+ if (!row.calls?.some((call) => call.command)) continue;
127
+ row.preview = max;
128
+ update(row);
129
+ if (size <= budget) return finish();
130
+ }
131
+ }
132
+ for (const rows of states) for (let i = 1; i < rows.length; i++) {
133
+ const row = rows[i];
134
+ row.foldPrefix = true;
135
+ if (joined(rows, i)) size -= TOOL_PREFIX.length - 1;
136
+ if (size <= budget) return finish();
137
+ }
138
+
139
+ // No presentation-only rung fits. Keep calls independently removable even
140
+ // when their prefixes are folded; never cap a giant concatenated tool line.
141
+ for (let span = 0; span < states.length && size > budget; span++) {
142
+ const rows = states[span];
143
+ for (let i = 0; i < rows.length && size > budget;) {
144
+ const row = rows[i];
145
+ if (row.text.startsWith("[User]:")) { i++; continue; }
146
+ if (row.calls && row.calls.length > 1) {
147
+ row.calls.shift();
148
+ row.text = render(row);
149
+ } else rows.splice(i, 1);
150
+ trimmed[span] = true;
151
+ size = measure();
152
+ }
153
+ }
154
+ // Stub each oversized user line once. Canonical lines remain untouched, so
155
+ // later checkpoints never shorten an already shortened presentation again.
156
+ for (let span = 0; span < states.length && size > budget; span++) {
157
+ for (const row of states[span]) {
158
+ if (size <= budget) break;
159
+ const line = row.text;
160
+ if (!line.startsWith("[User]:") || line.length <= 120) continue;
161
+ let end = 120;
162
+ if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
163
+ const stub = `${line.slice(0, end)}…[truncated +${line.length - end} chars — use context_lookup]`;
164
+ if (stub.length >= line.length) continue;
165
+ row.text = stub;
166
+ trimmed[span] = true;
167
+ size = measure();
168
+ }
169
+ }
170
+ for (let span = 0; span < states.length && size > budget; span++) {
171
+ while (states[span].length && size > budget) {
172
+ states[span].shift();
173
+ trimmed[span] = true;
174
+ size = measure();
175
+ }
176
+ }
177
+ return finish();
178
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.8.8",
3
+ "version": "0.9.3",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: context-retrieval
3
- description: Use context_lookup to recover earlier conversation details hidden by compaction, trace where an earlier finding came from, or investigate contradictions between earlier notes and new evidence.
3
+ description: "Guidance for using context_lookup after compaction: how to target earlier evidence, phrase effective lookup questions, and handle incomplete findings."
4
4
  ---
5
5
 
6
6
  # Session context recovery
@@ -12,6 +12,11 @@ history, including recorded tool outputs and your reasoning, is preserved in the
12
12
  session and can be retrieved. Retained startup reads and the uncompacted tail
13
13
  remain available as evidence; recover only hidden information needed for the task.
14
14
 
15
+ Under size pressure, `tools-tightened` on its own marks reduced tool previews
16
+ or grouped tool-only lines, without omitted conversation prose or calls. If
17
+ `trimmed` is also present, content was omitted or user text was shortened. Neither means that the original evidence
18
+ was never recorded; recover task-relevant missing detail through the tools below.
19
+
15
20
  Use the recovery tools for history established by this conversation or its checkpoint,
16
21
  not project discovery, requirements never supplied, other sessions, or abandoned branches.
17
22
  For unfamiliar project details or missing requirements, inspect project files or
@@ -25,7 +30,7 @@ This skill pairs with the `@foliox/transparent-compact-pi` extension, which prov
25
30
 
26
31
  - **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.
27
32
  - **`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
- - **Bounded fallback tools** — if those findings are incomplete, use `context_list_entries`, `context_grep`, and `context_show_entry` for direct evidence recovery. Their results enter this conversation. For recovery of details hidden by compaction, these are the permitted fallback, not filesystem access to session files.
33
+ - **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
34
 
30
35
  Pi normally saves sessions under `~/.pi/agent/sessions/`; custom session locations also work. In-memory sessions retain history only while the process lives and cannot be resumed after exit.
31
36
 
@@ -37,6 +42,10 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
37
42
  - You are unsure where an earlier finding came from, what a command actually printed, or why you reached a conclusion.
38
43
  - Earlier notes conflict with new evidence and you need to check the historical evidence behind them.
39
44
 
45
+ Tool stubs and file lists do not preserve the full supporting material. Most output
46
+ and detailed payloads are omitted. Inline observations are historical, not verification
47
+ of unshown details or current state. Unlabelled calls do not establish exit 0 or passing tests.
48
+
40
49
  Ask `context_lookup` a **specific historical question** to recover hidden supporting
41
50
  evidence. This can avoid repeating slow or unreliable research. For example:
42
51
  "Where did our earlier Holi 2026 date come from: a
@@ -55,6 +64,13 @@ published source or our own computation? Include the observed output and ENTRY i
55
64
  context_lookup({ question: "What exact error did the earlier test run return for the N=7 case? Include the ENTRY id and observed tool output." })
56
65
  ```
57
66
 
67
+ You may include an ENTRY id from an earlier recovery result in the question to
68
+ narrow the search. If you already know the ENTRY id and only need a specific
69
+ passage, `context_show_entry` can read that entry directly. Prefer
70
+ `context_lookup` when search or interpretation is needed. For post-compaction
71
+ recovery, continue paging only if the requested detail is missing, incomplete, or
72
+ needs more context to resolve ambiguity; stop once the question is answered.
73
+
58
74
  For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically. It does **not** search abandoned branches or unrelated sessions. If the detail is absent, report that limitation instead of claiming it was recovered or widening this recovery search through filesystem tools.
59
75
 
60
76
  A study harness may configure `MECH_COMPACT_LOOKUP_SESSION_FILE` to make the extension search a full session rather than a pruned fork. This is extension configuration, not a tool argument or a file the main agent should read. Do not discover or change the override to broaden a lookup.
@@ -69,10 +85,12 @@ the same recovery episode. Narration and thinking do not reset it either. Only
69
85
  a tool result outside the four recovery tools, a user message, or a bash
70
86
  execution resets the limit.
71
87
 
72
- Search responses are pages, not necessarily complete evidence. Follow pages
73
- only when omitted content is needed; do not exhaust every match or entry merely
74
- because a continuation is available. Keep other parameters unchanged and use
75
- all continuation parameters printed at the end of a limited page:
88
+ Search responses are pages, not necessarily complete evidence. Continue only
89
+ when the needed detail is missing, incomplete, or needs more context to resolve
90
+ ambiguity; do not exhaust every match or entry merely because a continuation is
91
+ available. A partial search does not establish that something never happened.
92
+ Keep other parameters unchanged and use all continuation parameters printed at
93
+ the end of a limited page:
76
94
 
77
95
  - Listings and entry retrieval: `offset` counts characters (UTF-16 code units)
78
96
  in the rendered listing or entry, starting at 0.
@@ -80,6 +98,10 @@ all continuation parameters printed at the end of a limited page:
80
98
  the context of an oversized match. Grep reports how many matches remain.
81
99
  - `maxLines` and `maxMatches` limit a page, not the backing history. Increasing
82
100
  them does not remove the character guard. Use the reported cursor instead.
101
+ - `context_show_entry` defaults to a single entry. `includeRelated=true` adds
102
+ unambiguously matched tool call/result entries in chronological order. Keep
103
+ this flag unchanged when paging. A result expands to its originating assistant,
104
+ not sibling outputs; an assistant expands to its matched results.
83
105
 
84
106
  Listing/grep cursors also report `throughEntry`: retain this original last-entry
85
107
  id on subsequent pages, so newly appended calls/results cannot keep expanding