@foliox/transparent-compact-pi 0.8.3 → 0.8.5

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 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,53 @@ 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
- After compaction, the checkpoint instructs the agent to re-read required documents,
107
- even if previously read, re-acquire missing task information, inspect Git state
108
- when in a Git repository, and re-read files before modifying them.
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 identifying documents mandated by system,
122
+ developer and applicable project instructions, then re-reading each in its
123
+ entirety before task planning or changes. For this step, a document is required
124
+ reading if and only if those instructions explicitly instruct the agent to read
125
+ it; merely mentioning or linking a document does not qualify. Grep matches, selected sections,
126
+ summaries and reading only edit targets explicitly do not satisfy this step;
127
+ truncated reads must continue to the end, and unavailable documents must be
128
+ reported rather than silently skipped. It also requires restoring missing inputs
129
+ rather than repeating completed writes, inspecting Git state, re-reading files
130
+ before editing and verifying evidence before relying on it. It is a saved
131
+ custom message tagged with the current compaction entry ID, not a temporary nudge:
132
+ subsequent responses and user turns retain it in history before the work that
133
+ followed it. `before_agent_start` adds it on normal starts/resume when missing;
134
+ `session_compact` steers it into automatic mid-run and overflow continuations.
135
+ Idle/post-run compaction waits for the next run and does not trigger extra work.
136
+
137
+ The final `context_with_system` phase places the checklist last on the first
138
+ post-compaction request, after ordinary context transforms and pending input.
139
+ It also removes obsolete or duplicate **managed** checklist messages, including
140
+ those Pi retained in its recent tail. On later turns the current message stays in
141
+ history rather than being moved to the end again. Branch-based IDs make this
142
+ work through reload, resume, forks and tree navigation without an in-memory flag.
143
+
144
+ Subsequent verbatim compactions skip these managed messages when building spans,
145
+ then regenerate one envelope around the entire accumulated compacted context.
146
+ Old generated checklists therefore do not accumulate inside spans or the active
147
+ tail. Their original entries remain in raw session history for recovery/audit.
148
+ Ordinary user, assistant and custom prose is never stripped by matching instruction
149
+ text. Opaque inherited model summaries/legacy checkpoints are likewise not rewritten
150
+ to remove text that looks like an old instruction envelope.
151
+
152
+ Offline tests inspect actual SDK requests with roughly 20k-token tails, multiple
153
+ compactions, persisted instructions and interrupted/automatic continuations.
154
+ These verify delivery and placement, not live-model compliance.
109
155
 
@@ -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
- lines.push(`[Custom]: ${textOf(m.content).text}`);
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,65 @@ 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 = `**Re-orient before continuing.** Compaction may have removed information needed to follow the project instructions:
608
- 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
- 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
- 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.
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:
610
+ 1. **Re-read every required document IN ITS ENTIRETY.** For this step, a document is required reading **if and only if** your applicable system prompt, developer instructions, or project instructions (including AGENTS.md / CLAUDE.md) explicitly instruct you to read it. Merely mentioning or linking a document does not qualify. Identify all such documents and re-read each from beginning to end, even if you read them before compaction. Grep matches, selected sections, summaries, and reading only files you intend to edit do NOT satisfy this requirement. If output is truncated, continue reading until you reach the end. Complete these reads before planning or changing anything; intending or promising to read does not count. If a required document is unavailable, report the blocker rather than silently skipping it.
611
+ 2. 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.
612
+ 3. 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.
613
+ 4. Re-read any file you are about to modify — do not trust content you only remember from before the compaction.
614
+ 5. **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
615
 
613
- **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.`;
616
+ 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.";
617
+
618
+ 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
619
 
615
620
  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
621
 
622
+ const REORIENT_MESSAGE = "transparent-compact:reorient";
623
+ 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.";
624
+
625
+ function latestVerbatimCompaction(entries: SessionEntry[]) {
626
+ for (let i = entries.length - 1; i >= 0; i--) {
627
+ const entry = entries[i];
628
+ if (entry.type === "compaction")
629
+ return (entry.details as { kind?: string } | undefined)?.kind === MECH_KIND ? entry : undefined;
630
+ }
631
+ }
632
+
633
+ function reorientationMessage(compactionId: string) {
634
+ return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}\n\n${RECOVERY_RECAP}`,
635
+ display: false, details: { compactionId } };
636
+ }
637
+
638
+ function isReorientation(msg: AgentMessage): boolean {
639
+ return msg.role === "custom" && msg.customType === REORIENT_MESSAGE;
640
+ }
641
+
642
+ function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
643
+ return msg.role === "custom" && msg.customType === REORIENT_MESSAGE &&
644
+ (msg.details as { compactionId?: string } | undefined)?.compactionId === compactionId;
645
+ }
646
+
647
+ /** Keep one current, persisted checklist. Obsolete managed messages can still be
648
+ * in Pi's retained tail, but are never presented as conversation or summarized.
649
+ * On the first request, move the checklist after pending input/other transforms.
650
+ * Later requests keep it in history before the work that followed it. */
651
+ function projectReorientation(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
652
+ const compaction = latestVerbatimCompaction(entries);
653
+ let selected = -1;
654
+ for (let i = 0; i < messages.length; i++)
655
+ if (compaction && reorientationFor(messages[i], compaction.id)) selected = i;
656
+ const result = messages.filter((m, i) => !isReorientation(m) || i === selected);
657
+ if (selected < 0 || !compaction) return result;
658
+ const answered = entries.slice(entries.indexOf(compaction) + 1).some((e) =>
659
+ e.type === "message" && e.message.role === "assistant" &&
660
+ e.message.stopReason !== "aborted" && e.message.stopReason !== "error");
661
+ if (!answered) {
662
+ const checklist = messages[selected];
663
+ return [...result.filter((m) => m !== checklist), checklist];
664
+ }
665
+ return result;
666
+ }
667
+
617
668
  async function buildMechanicalSummary(opts: {
618
669
  reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
619
670
  tokensBefore: number;
@@ -674,6 +725,7 @@ async function buildMechanicalSummary(opts: {
674
725
  const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
675
726
  const parts: string[] = [];
676
727
  parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
728
+ parts.push(CHECKPOINT_EXPLANATION);
677
729
  if (base?.kind === "model-summary") {
678
730
  parts.push(MIXED_CONTEXT_WARNING);
679
731
  opts.notify(MIXED_CONTEXT_WARNING);
@@ -682,11 +734,11 @@ async function buildMechanicalSummary(opts: {
682
734
  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
735
  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
736
  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; everything after the last span is uncompacted.",
737
+ "- 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
738
  );
687
739
  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
740
  parts.push("");
689
- parts.push(REORIENT_BLOCK);
741
+ parts.push(RECOVERY_INSTRUCTIONS);
690
742
  parts.push("");
691
743
  parts.push(SECTION_HEADER);
692
744
  parts.push("");
@@ -1220,6 +1272,36 @@ function registerDirectTools(pi: ExtensionAPI): void {
1220
1272
  // ============================================================================
1221
1273
 
1222
1274
  export default function (pi: ExtensionAPI) {
1275
+ // Starting/resuming a run persists the checklist AFTER the starting user
1276
+ // message. Existing branch history, not an in-memory flag, prevents repeats.
1277
+ pi.on("before_agent_start", (_event, ctx) => {
1278
+ const entries = ctx.sessionManager.getBranch();
1279
+ const compaction = latestVerbatimCompaction(entries);
1280
+ if (!compaction) return;
1281
+ const found = entries.some((e) => e.type === "custom_message" && e.customType === REORIENT_MESSAGE &&
1282
+ (e.details as { compactionId?: string } | undefined)?.compactionId === compaction.id);
1283
+ if (!found) return { message: reorientationMessage(compaction.id) };
1284
+ });
1285
+
1286
+ // Between-turn compaction and overflow continuation do not necessarily pass
1287
+ // through before_agent_start. Steering is consumed by Pi before that next
1288
+ // request and persists the same custom message. Idle/post-run compactions wait
1289
+ // for the next starting message instead; the checklist must not start a run.
1290
+ pi.on("session_compact", (event, ctx) => {
1291
+ if ((event.compactionEntry.details as { kind?: string } | undefined)?.kind !== MECH_KIND) return;
1292
+ if (event.willRetry || ctx.signal)
1293
+ pi.sendMessage(reorientationMessage(event.compactionEntry.id), { deliverAs: "steer" });
1294
+ });
1295
+
1296
+ // Run after ordinary transforms and system/tool restoration. Preserve all
1297
+ // non-managed messages, remove old checklists even if they survive in the tail,
1298
+ // and keep the current one active on subsequent requests (not just the first).
1299
+ pi.on("context_with_system", (event, ctx) => {
1300
+ const messages = projectReorientation(event.messages, ctx.sessionManager.getBranch());
1301
+ if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i]))
1302
+ return { messages };
1303
+ });
1304
+
1223
1305
  // Method selection never changes Pi's auto-compaction enabled setting.
1224
1306
  pi.registerCommand("compaction-method", {
1225
1307
  description: "Show or set the session compaction method: verbatim|summary (manual and automatic)",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -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 one re-orientation block and an opaque base when needed.
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 checkpoint's re-orientation instructions after compaction.
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