@foliox/transparent-compact-pi 0.8.2 → 0.8.4
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.
- package/CHANGELOG.md +9 -0
- package/README.md +8 -0
- package/docs/DESIGN.md +42 -3
- package/extensions/transparent-compact.ts +87 -6
- package/package.json +2 -2
- package/skills/context-retrieval/SKILL.md +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,15 @@
|
|
|
9
9
|
ambiguous outcomes are never inferred, including unlabelled older spans.
|
|
10
10
|
- Read-file entries explicitly mark content as removed; a closing evidence rule
|
|
11
11
|
requires lookup or re-reading before relying on removed outputs or document rules.
|
|
12
|
+
- The instruction envelope now has recovery explanations before all compacted
|
|
13
|
+
spans, one evidence-boundary warning after them, and a mandatory numbered
|
|
14
|
+
re-orientation checklist plus brief recovery recap after the retained tail.
|
|
15
|
+
The checklist is persisted and remains active after the first response. Later
|
|
16
|
+
compactions regenerate the envelope: old generated checklists are neither
|
|
17
|
+
summarized into spans nor replayed from the retained tail. Raw originals remain
|
|
18
|
+
available for audit/recovery. Offline SDK tests cover ~20k-token tail placement,
|
|
19
|
+
persistence, repeated compaction, reload/resume, mid-run and overflow continuation,
|
|
20
|
+
without making a live-model compliance claim.
|
|
12
21
|
- Flat chronological spans avoid repeatedly summarizing earlier facts.
|
|
13
22
|
- Session-persistent `/compaction-method verbatim|summary` selects manual,
|
|
14
23
|
automatic, and overflow-recovery compaction independently of auto-compaction
|
package/README.md
CHANGED
|
@@ -53,6 +53,14 @@ To compact manually:
|
|
|
53
53
|
/compact
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
The checkpoint begins with an explanation and full recovery instructions, and
|
|
57
|
+
ends with an evidence-boundary warning. A mandatory re-orientation checklist and
|
|
58
|
+
brief recovery recap follow **the retained recent history and any pending new
|
|
59
|
+
user input**. They are saved in the session and remain available on later turns.
|
|
60
|
+
After another compaction, only the current checklist is presented: older generated
|
|
61
|
+
checklists are excluded from compacted spans and the retained tail. This is
|
|
62
|
+
instruction delivery, not a guarantee of model compliance.
|
|
63
|
+
|
|
56
64
|
### Select the compaction method
|
|
57
65
|
|
|
58
66
|
```text
|
package/docs/DESIGN.md
CHANGED
|
@@ -103,7 +103,46 @@ the count. Pending lookup calls in the same batch also count, preventing paralle
|
|
|
103
103
|
calls from bypassing the limit. Blocked attempts return a short fallback note
|
|
104
104
|
without launching a subagent; later lookups after other work remain available.
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
106
|
+
### Instruction envelope and persistent re-orientation
|
|
107
|
+
|
|
108
|
+
Pi projects the checkpoint before its retained recent history (normally about
|
|
109
|
+
20,000 tokens). The extension separates explanations about that history from the
|
|
110
|
+
instructions that must be prominent at the actual point of resumption:
|
|
111
|
+
|
|
112
|
+
```text
|
|
113
|
+
Checkpoint introduction: what was removed + full recovery instructions
|
|
114
|
+
All compacted spans (oldest first), then read/modified file lists
|
|
115
|
+
One evidence-boundary warning + start-of-verbatim-tail marker
|
|
116
|
+
Retained verbatim tail
|
|
117
|
+
Any pending new user input
|
|
118
|
+
Mandatory re-orientation checklist + brief recovery recap
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The numbered checklist requires re-reading required documents, restoring missing
|
|
122
|
+
inputs rather than repeating completed writes, inspecting Git state, re-reading
|
|
123
|
+
files before editing and verifying evidence before relying on it. It is a saved
|
|
124
|
+
custom message tagged with the current compaction entry ID, not a temporary nudge:
|
|
125
|
+
subsequent responses and user turns retain it in history before the work that
|
|
126
|
+
followed it. `before_agent_start` adds it on normal starts/resume when missing;
|
|
127
|
+
`session_compact` steers it into automatic mid-run and overflow continuations.
|
|
128
|
+
Idle/post-run compaction waits for the next run and does not trigger extra work.
|
|
129
|
+
|
|
130
|
+
The final `context_with_system` phase places the checklist last on the first
|
|
131
|
+
post-compaction request, after ordinary context transforms and pending input.
|
|
132
|
+
It also removes obsolete or duplicate **managed** checklist messages, including
|
|
133
|
+
those Pi retained in its recent tail. On later turns the current message stays in
|
|
134
|
+
history rather than being moved to the end again. Branch-based IDs make this
|
|
135
|
+
work through reload, resume, forks and tree navigation without an in-memory flag.
|
|
136
|
+
|
|
137
|
+
Subsequent verbatim compactions skip these managed messages when building spans,
|
|
138
|
+
then regenerate one envelope around the entire accumulated compacted context.
|
|
139
|
+
Old generated checklists therefore do not accumulate inside spans or the active
|
|
140
|
+
tail. Their original entries remain in raw session history for recovery/audit.
|
|
141
|
+
Ordinary user, assistant and custom prose is never stripped by matching instruction
|
|
142
|
+
text. Opaque inherited model summaries/legacy checkpoints are likewise not rewritten
|
|
143
|
+
to remove text that looks like an old instruction envelope.
|
|
144
|
+
|
|
145
|
+
Offline tests inspect actual SDK requests with roughly 20k-token tails, multiple
|
|
146
|
+
compactions, persisted instructions and interrupted/automatic continuations.
|
|
147
|
+
These verify delivery and placement, not live-model compliance.
|
|
109
148
|
|
|
@@ -488,7 +488,9 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
|
488
488
|
lines.push(`[BashExecution]: $ ${String(m.command ?? "")} (output removed — use context_lookup)`);
|
|
489
489
|
break;
|
|
490
490
|
case "custom":
|
|
491
|
-
|
|
491
|
+
// Our instruction envelope is regenerated, not conversation prose.
|
|
492
|
+
// Keep originals in raw history, but never carry old checklists into spans.
|
|
493
|
+
if (m.customType !== REORIENT_MESSAGE) lines.push(`[Custom]: ${textOf(m.content).text}`);
|
|
492
494
|
break;
|
|
493
495
|
case "branchSummary":
|
|
494
496
|
case "compactionSummary":
|
|
@@ -604,16 +606,64 @@ function capSpans(spans: string[][], budget: number): string[][] {
|
|
|
604
606
|
return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
|
|
605
607
|
}
|
|
606
608
|
|
|
607
|
-
const REORIENT_BLOCK = `**
|
|
609
|
+
const REORIENT_BLOCK = `**Post-compaction re-orientation — REQUIRED BEFORE CONTINUING.** Compaction may have removed information needed to follow the project instructions. Before planning or performing the next task, you MUST complete this checklist:
|
|
608
610
|
1. Re-read documents required by the applicable instructions (such as files referenced by AGENTS.md / CLAUDE.md), even if you read them before compaction. Re-acquire any other information needed for the current task that is no longer in context. This means restoring inputs, not repeating completed work: do not redo writes, edits, or other state-changing actions merely because their results were dropped. If needed, recover those results with \`context_lookup\`, or verify current state.
|
|
609
611
|
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.
|
|
610
612
|
3. Re-read any file you are about to modify — do not trust content you only remember from before the compaction.
|
|
611
|
-
4. **Treat other pre-compaction knowledge as unverified too.** Thinking and tool outputs were removed. Anything you know only from them — or from earlier assistant prose describing them — is a note, not evidence. Before you state it as fact or base a decision on it, re-read the source or ask \`context_lookup\`. If you cannot verify it, say explicitly that it is unverified
|
|
613
|
+
4. **Treat other pre-compaction knowledge as unverified too.** Thinking and tool outputs were removed. Anything you know only from them — or from earlier assistant prose describing them — is a note, not evidence. Before you state it as fact or base a decision on it, re-read the source or ask \`context_lookup\`. If you cannot verify it, say explicitly that it is unverified.`;
|
|
612
614
|
|
|
613
|
-
|
|
615
|
+
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: assistant thinking and tool outputs have been removed from the compacted spans, but are preserved in the session and can be recovered.";
|
|
616
|
+
|
|
617
|
+
const RECOVERY_INSTRUCTIONS = `**Recovering dropped details.** Information removed from your active context is preserved in the session, including earlier thinking and tool outputs. Prefer \`context_lookup\` with a specific question: a subagent searches the transcript in its own context and returns relevant findings. 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. Do not read or grep raw session JSONL files or old dumps through filesystem tools in this conversation — use these recovery tools instead.`;
|
|
614
618
|
|
|
615
619
|
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; if a claim depends on that removed evidence, use `context_lookup` or re-read the source before relying on it.";
|
|
616
620
|
|
|
621
|
+
const REORIENT_MESSAGE = "transparent-compact:reorient";
|
|
622
|
+
const RECOVERY_RECAP = "**Recovery recap.** Re-read current sources or ask `context_lookup` a specific question about removed history. If its findings are incomplete, use `context_list_entries`, `context_grep`, or `context_show_entry`, following pagination instructions. Do not read raw session JSONL files or old dumps through filesystem tools. Keep these evidence/recovery rules in force as work continues.";
|
|
623
|
+
|
|
624
|
+
function latestVerbatimCompaction(entries: SessionEntry[]) {
|
|
625
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
626
|
+
const entry = entries[i];
|
|
627
|
+
if (entry.type === "compaction")
|
|
628
|
+
return (entry.details as { kind?: string } | undefined)?.kind === MECH_KIND ? entry : undefined;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function reorientationMessage(compactionId: string) {
|
|
633
|
+
return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}\n\n${RECOVERY_RECAP}`,
|
|
634
|
+
display: false, details: { compactionId } };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function isReorientation(msg: AgentMessage): boolean {
|
|
638
|
+
return msg.role === "custom" && msg.customType === REORIENT_MESSAGE;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
|
|
642
|
+
return msg.role === "custom" && msg.customType === REORIENT_MESSAGE &&
|
|
643
|
+
(msg.details as { compactionId?: string } | undefined)?.compactionId === compactionId;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Keep one current, persisted checklist. Obsolete managed messages can still be
|
|
647
|
+
* in Pi's retained tail, but are never presented as conversation or summarized.
|
|
648
|
+
* On the first request, move the checklist after pending input/other transforms.
|
|
649
|
+
* Later requests keep it in history before the work that followed it. */
|
|
650
|
+
function projectReorientation(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
|
|
651
|
+
const compaction = latestVerbatimCompaction(entries);
|
|
652
|
+
let selected = -1;
|
|
653
|
+
for (let i = 0; i < messages.length; i++)
|
|
654
|
+
if (compaction && reorientationFor(messages[i], compaction.id)) selected = i;
|
|
655
|
+
const result = messages.filter((m, i) => !isReorientation(m) || i === selected);
|
|
656
|
+
if (selected < 0 || !compaction) return result;
|
|
657
|
+
const answered = entries.slice(entries.indexOf(compaction) + 1).some((e) =>
|
|
658
|
+
e.type === "message" && e.message.role === "assistant" &&
|
|
659
|
+
e.message.stopReason !== "aborted" && e.message.stopReason !== "error");
|
|
660
|
+
if (!answered) {
|
|
661
|
+
const checklist = messages[selected];
|
|
662
|
+
return [...result.filter((m) => m !== checklist), checklist];
|
|
663
|
+
}
|
|
664
|
+
return result;
|
|
665
|
+
}
|
|
666
|
+
|
|
617
667
|
async function buildMechanicalSummary(opts: {
|
|
618
668
|
reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
|
|
619
669
|
tokensBefore: number;
|
|
@@ -674,6 +724,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
674
724
|
const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
|
|
675
725
|
const parts: string[] = [];
|
|
676
726
|
parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
|
|
727
|
+
parts.push(CHECKPOINT_EXPLANATION);
|
|
677
728
|
if (base?.kind === "model-summary") {
|
|
678
729
|
parts.push(MIXED_CONTEXT_WARNING);
|
|
679
730
|
opts.notify(MIXED_CONTEXT_WARNING);
|
|
@@ -682,11 +733,11 @@ async function buildMechanicalSummary(opts: {
|
|
|
682
733
|
parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming; tool calls are kept as one-line signatures (arguments truncated). Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
|
|
683
734
|
parts.push("- Tool status: ok = result not flagged as an error; error = result flagged as an error; unknown = no safely matched result/status. Output content is removed in all cases. ok does not prove a command or tests passed. Calls without a status in older spans have unknown outcomes.");
|
|
684
735
|
parts.push(
|
|
685
|
-
"- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that
|
|
736
|
+
"- 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.",
|
|
686
737
|
);
|
|
687
738
|
parts.push("- The full transcript before this point is kept in the session; use `context_lookup` to recover details (including thinking and tool outputs).");
|
|
688
739
|
parts.push("");
|
|
689
|
-
parts.push(
|
|
740
|
+
parts.push(RECOVERY_INSTRUCTIONS);
|
|
690
741
|
parts.push("");
|
|
691
742
|
parts.push(SECTION_HEADER);
|
|
692
743
|
parts.push("");
|
|
@@ -1220,6 +1271,36 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1220
1271
|
// ============================================================================
|
|
1221
1272
|
|
|
1222
1273
|
export default function (pi: ExtensionAPI) {
|
|
1274
|
+
// Starting/resuming a run persists the checklist AFTER the starting user
|
|
1275
|
+
// message. Existing branch history, not an in-memory flag, prevents repeats.
|
|
1276
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
1277
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1278
|
+
const compaction = latestVerbatimCompaction(entries);
|
|
1279
|
+
if (!compaction) return;
|
|
1280
|
+
const found = entries.some((e) => e.type === "custom_message" && e.customType === REORIENT_MESSAGE &&
|
|
1281
|
+
(e.details as { compactionId?: string } | undefined)?.compactionId === compaction.id);
|
|
1282
|
+
if (!found) return { message: reorientationMessage(compaction.id) };
|
|
1283
|
+
});
|
|
1284
|
+
|
|
1285
|
+
// Between-turn compaction and overflow continuation do not necessarily pass
|
|
1286
|
+
// through before_agent_start. Steering is consumed by Pi before that next
|
|
1287
|
+
// request and persists the same custom message. Idle/post-run compactions wait
|
|
1288
|
+
// for the next starting message instead; the checklist must not start a run.
|
|
1289
|
+
pi.on("session_compact", (event, ctx) => {
|
|
1290
|
+
if ((event.compactionEntry.details as { kind?: string } | undefined)?.kind !== MECH_KIND) return;
|
|
1291
|
+
if (event.willRetry || ctx.signal)
|
|
1292
|
+
pi.sendMessage(reorientationMessage(event.compactionEntry.id), { deliverAs: "steer" });
|
|
1293
|
+
});
|
|
1294
|
+
|
|
1295
|
+
// Run after ordinary transforms and system/tool restoration. Preserve all
|
|
1296
|
+
// non-managed messages, remove old checklists even if they survive in the tail,
|
|
1297
|
+
// and keep the current one active on subsequent requests (not just the first).
|
|
1298
|
+
pi.on("context_with_system", (event, ctx) => {
|
|
1299
|
+
const messages = projectReorientation(event.messages, ctx.sessionManager.getBranch());
|
|
1300
|
+
if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i]))
|
|
1301
|
+
return { messages };
|
|
1302
|
+
});
|
|
1303
|
+
|
|
1223
1304
|
// Method selection never changes Pi's auto-compaction enabled setting.
|
|
1224
1305
|
pi.registerCommand("compaction-method", {
|
|
1225
1306
|
description: "Show or set the session compaction method: verbatim|summary (manual and automatic)",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foliox/transparent-compact-pi",
|
|
3
|
-
"version": "0.8.
|
|
4
|
-
"description": "Deterministic,
|
|
3
|
+
"version": "0.8.4",
|
|
4
|
+
"description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi-extension",
|
|
@@ -7,7 +7,7 @@ description: Recover earlier pi session context through the context_lookup subag
|
|
|
7
7
|
|
|
8
8
|
This skill pairs with `transparent-compact.ts`, which provides:
|
|
9
9
|
|
|
10
|
-
- **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and tool outputs are removed from the active model context, not from the raw session history. Earlier spans are re-rendered flat, with
|
|
10
|
+
- **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and tool outputs are removed from the active model context, not from the raw session history. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. A persistent mandatory re-orientation checklist and recovery recap follow the retained tail; later compactions replace the old generated checklist rather than duplicating it. An inherited opaque base is kept when needed.
|
|
11
11
|
- **`context_lookup`** — the preferred first step: 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. There is no local dump or temporary transcript file to manage.
|
|
12
12
|
- **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. These are the permitted fallback, not filesystem access to session files.
|
|
13
13
|
|
|
@@ -19,7 +19,7 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
|
|
|
19
19
|
|
|
20
20
|
- After a compaction, you need an exact error message, a full tool output, previously read file content, full tool-call arguments, an earlier instruction or decision, or reasoning that was dropped → call `context_lookup` with a **specific** question.
|
|
21
21
|
- A checkpoint or your memory contains a claim based on pre-compaction tool output → re-read the current source or ask `context_lookup` for the historical evidence before relying on the claim. If you cannot verify it, explicitly label it unverified.
|
|
22
|
-
- Before a long, tool-heavy task → no extra snapshot is required for recovery. Pi's raw session history already retains finalized entries. Follow the
|
|
22
|
+
- Before a long, tool-heavy task → no extra snapshot is required for recovery. Pi's raw session history already retains finalized entries. Follow the mandatory post-tail re-orientation checklist after compaction: re-read required project documents before planning or acting, even if earlier prose says you already read them. The checklist and recovery recap remain in context on subsequent turns; the evidence/recovery rules continue to apply.
|
|
23
23
|
|
|
24
24
|
## How to ask
|
|
25
25
|
|