pi-context 2.0.0-beta.0 β†’ 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pi Context: Agentic Context Management for Pi
2
2
 
3
- An Agentic Context Management tool that helps AI agents proactively manage checkpoints, timeline inspection, and rewind-based context cleanup.
3
+ An Agentic Context Management tool that helps AI agents keep long conversations focused by maintaining a clean working set: checkpoint useful anchors, inspect the active history structure, and compact noisy completed paths into state summaries.
4
4
 
5
5
  Inspired by kimi-cli d-mail, it brings lossless time travel to Pi's session tree.
6
6
 
@@ -13,9 +13,9 @@ Earlier versions used more Git-like names such as `context_tag`, `context_log`,
13
13
  Current versions intentionally use conversation-native names instead:
14
14
  - `context_checkpoint`
15
15
  - `context_timeline`
16
- - `context_rewind`
16
+ - `context_compact`
17
17
 
18
- These tools manage **conversation history**, not repository state. They should not be treated as Git commands or as replacements for real `git tag`, `git log`, or `git checkout`.
18
+ These tools manage **conversation history**, not repository state. They should not be treated as Git commands or as replacements for real `git tag`, `git log`, or `git checkout`. Context navigation does not modify or roll back files, running processes, browser state, tickets, databases, or remote services.
19
19
 
20
20
  ## Installation
21
21
 
@@ -43,13 +43,13 @@ Open a visual dashboard to inspect context-window usage and token distribution (
43
43
 
44
44
  ### For Agents
45
45
 
46
- This extension adds the `context-management` skill, which includes three core tools:
46
+ This extension adds the `context-management` skill, which guides agents to keep the active conversation as the smallest sufficient working set for the next step. It includes three core tools:
47
47
 
48
- 1. **πŸ”– Structure (`context_checkpoint`)**
49
- Create named checkpoints to organize conversation history.
48
+ 1. **πŸ”– Anchor (`context_checkpoint`)**
49
+ Label a meaningful conversation node with a unique semantic checkpoint name, such as `parser-fix-start` or `timeout-investigation-search`.
50
50
 
51
- 2. **πŸ“Š Monitor (`context_timeline`)**
52
- Visualize conversation history, inspect token usage, and see where you are in the task tree.
51
+ 2. **πŸ“Š Inspect (`context_timeline`)**
52
+ View the active path as a structural map of checkpoints, summaries/compactions, branch points, user turns, and current position. Use it when orientation or compact target selection depends on history shape.
53
53
 
54
- 3. **βͺ Compress (`context_rewind`)**
55
- Return to an earlier checkpoint or anchor with a carryover summary so completed noisy work can be compacted into a cleaner continuation.
54
+ 3. **βͺ Compact (`context_compact`)**
55
+ Create a summarized continuation branch from an earlier checkpoint, history node, or `root`. The summary should restore the useful state after the target: current task, decisions, external side effects such as changed files or remote updates, validation state, source anchors, and the explicit next step.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-context",
3
- "version": "2.0.0-beta.0",
3
+ "version": "2.0.0",
4
4
  "description": "Agentic Context Management for Pi",
5
5
  "files": [
6
6
  "src",
@@ -1,274 +1,215 @@
1
1
  ---
2
2
  name: context-management
3
- description: Read this skill for work that is likely to stretch across many turns or get messy if handled in one uninterrupted thread. Especially use it when the request sounds like first go search or read a lot, first look through logs/files/pages/results and come back with the real conclusion, this will probably take several rounds, there may be several approaches to try, first make a plan or todo list and then work through it, there will be many similar cases to handle, the user may interrupt with side tasks, or the thread is already getting messy and should be cleaned up before continuing. It teaches a working mode built around frequent checkpoints, periodic timeline review, and targeted rewinds as the task evolves. Usually skip it for one-shot reads, bounded summaries, direct rewrites, or deterministic scripts.
3
+ description: Use this skill for work likely to span many turns, branches, retries, research, reading several files/webpages, plan-then-execute phases, repeated cases, debugging, or interrupted/messy threads. It guides agents to maintain a clean working set with checkpoints, timeline review, and compaction at useful continuation boundaries. Usually skip for one-shot reads, bounded summaries, direct rewrites, simple lookups, or deterministic scripts.
4
4
  ---
5
5
 
6
6
  # Context Management
7
7
 
8
- Use this skill to adopt an explicit conversation-management working mode.
8
+ Use this skill to maintain the active conversation as a useful **working set** for the next step. The goal is not to archive more history or compress more aggressively; it is to keep raw only the context that still needs direct reasoning, and carry the rest as compact task state when that is more efficient.
9
9
 
10
- This mode is for tasks where the work may still be valid, but the thread carrying it is likely to become long, noisy, multi-phase, or hard to keep clean. The goal is to keep the work navigable: checkpoint early, review timeline when needed, and compact completed noisy phases back to clean anchors.
10
+ Core rhythm:
11
+
12
+ - **checkpoint before mess**
13
+ - **review timeline when structure affects the next decision**
14
+ - **compact when a state summary is a better working set than the raw trail**
15
+
16
+ Use only these tools:
11
17
 
12
- Use only the current tool names:
13
18
  - `context_checkpoint`
14
19
  - `context_timeline`
15
- - `context_rewind`
20
+ - `context_compact`
21
+
22
+ ## Working-set model
23
+
24
+ Before choosing a tool, ask:
16
25
 
17
- ## When to use this skill
26
+ - What am I trying to do next?
27
+ - What facts, constraints, or artifacts must stay raw for that next action?
28
+ - What history is useful only as a conclusion or state update?
29
+ - What history is just process noise or stale baggage?
18
30
 
19
- Read this skill when the task is likely to outgrow one clean thread and would benefit from explicit history management.
31
+ Classify context into three forms:
20
32
 
21
- It should feel like a good fit when the user is effectively asking for one of these patterns:
33
+ - **Raw context:** user intent, constraints, code/log/error details, evidence, or plan text that you expect to inspect directly soon.
34
+ - **State summary:** decisions, findings, lessons, changed files, validation status, rejected leads, and next steps that can replace raw process.
35
+ - **Discardable process:** repetitive searches, verbose logs, abandoned hypotheses, false starts, and unrelated turns whose useful value is already captured or no longer needed.
22
36
 
23
- ### β€œFirst go look through a lot of stuff, then come back with the real conclusion.”
24
- Examples:
25
- - searching or researching first
26
- - web search or browser-driven information gathering
27
- - reading many files, logs, docs, webpages, or web results
28
- - review / comparison / audit-heavy reading across many sources
37
+ If the active context is already small, coherent, and directly useful for the next step, do not manage it just to be tidy.
29
38
 
30
- ### β€œThis will probably take several rounds or several phases.”
31
- Examples:
39
+ ## When to use
40
+
41
+ Use this mode when the user is asking for work that may outgrow one clean thread:
42
+
43
+ - search, research, browser work, or reading many files/logs/pages/results
44
+ - several links or low-density webpages where only conclusions and next actions should survive
32
45
  - investigate -> decide -> execute -> validate
33
46
  - plan -> implement -> verify
34
- - collect -> compare -> conclude
35
- - any task that will keep changing shape as it progresses
36
-
37
- ### β€œWe may need to try more than one route.”
38
- Examples:
39
- - A / B / C approaches
40
- - dead ends and retries
41
- - compare and choose
42
- - pivoting after a failed direction
43
-
44
- ### β€œStart from a plan or todo list, then work through it.”
45
- Examples:
46
- - a formal implementation or migration plan
47
- - a roadmap with milestones
48
- - a lightweight todo list or checklist
49
- - staged execution that will be revisited across many turns
50
-
51
- ### β€œThere will be many similar cases, tickets, or items.”
52
- Examples:
53
- - repeated cases
54
- - repeated tickets
55
- - repeated checks
56
- - repeated reviews
57
- - repeated fix attempts on similar inputs
58
-
59
- ### β€œI may interrupt you, or this thread is already getting messy.”
60
- Examples:
61
- - the user may insert side tasks
62
- - you need to pause one line of work and resume it later
63
- - the thread is already long, stale, or cluttered
64
- - finished noisy phases should be cleaned up before continuing
65
-
66
- ### β€œThis is code-facing work and may turn noisy while I debug or implement it.”
67
- Examples:
68
- - implementation
69
- - debugging
70
- - troubleshooting
71
- - refactoring
72
- - migration
73
- - code-facing review or fix work
74
-
75
- If one of these patterns clearly applies, take the first structural action nowβ€”usually a checkpointβ€”instead of only describing the intended workflow.
76
-
77
- If multiple approaches, failed branches, compare work, or pivots become central, also read `references/retry-branch-and-pivot.md` in addition to the main scenario reference.
78
-
79
- ## When to skip it
80
-
81
- Usually skip this skill for:
82
- - one-shot reads
83
- - bounded summaries
84
- - direct rewrites with little exploration
85
- - simple fact lookup or concept explanation
86
- - deterministic scripts or fixed-rule automation
87
- - short tasks that can stay clean in one thread
88
-
89
- ## Operating rhythm
90
-
91
- 1. Before entering a noisy phase, create a checkpoint.
92
- 2. If you feel disoriented or anchor choice is unclear, run `context_timeline`.
93
- 3. Add more checkpoints at milestones, phase boundaries, risky branches, and interruptions.
94
- 4. Do not rewind just because the skill triggered.
95
- 5. Once a noisy phase is complete and summarizable, rewind to the best earlier clean anchor.
96
- 6. Continue from the compacted state instead of dragging the full messy path forward.
97
-
98
- The key habit is: **checkpoint is the default move; rewind is the selective cleanup move.** Checkpointing alone is not the end state. Checkpoints create anchors so that completed noisy phases can later be compacted cleanly.
47
+ - multiple approaches, retries, failed branches, or pivots
48
+ - repeated similar cases, tickets, reviews, or batch items
49
+ - a main task that may be interrupted by side tasks
50
+ - a scattered thread that should be cleaned up before continuing from a clean point
51
+ - debugging, troubleshooting, refactoring, migration, or other code-facing work that may get noisy
52
+
53
+ If one of these clearly applies, take a structural action now, usually a checkpoint. Do not merely describe the workflow. If the user has not yet provided enough task details, still create a checkpoint for the workflow shape before asking clarifying questions, and name the detected mode briefly (search/reading, planning, repeated batch, task switching/cleanup, development retry).
54
+
55
+ Usually skip this skill for one-shot reads, bounded summaries, direct rewrites, simple fact lookup, conceptual explanation, deterministic scripts, short tasks that can stay clean, or moments where the active context is already a good working set.
56
+
57
+ ## Start-of-turn check
58
+
59
+ At the start of each new user message, classify it:
60
+
61
+ - **Same task / next phase**: continue; if the previous phase is complete and noisy, compact before the next phase.
62
+ - **Correction or follow-up on the last answer**: usually answer from recent context; do not compact yet.
63
+ - **New unrelated task or direction shift**: if the previous task left a complete noisy segment, inspect the timeline first when multiple checkpoints or possible anchors exist, then compact to a continuation anchor that gives the new task a clean working set.
64
+
65
+ Think of the tools as a phase pipeline: `context_checkpoint` marks useful anchors, work happens, `context_timeline` shows the structure when orientation or target choice is unclear, and `context_compact` creates a new branch from the chosen continuation anchor with a summary of what happened after it. The target is a working-set choice, not an age choice: keep raw context only when it will help the next action; summarize or drop raw process when it would distract.
66
+
67
+ This prevents both premature cleanup after final answers and endless checkpoint-only behavior that lets stale work accumulate.
68
+
69
+ ## Main loop
70
+
71
+ 1. Before noisy work, create a semantic checkpoint as the first context-management action, even if the next visible step is asking for missing inputs. If the first job is orientation over existing history, run `context_timeline` before adding a new checkpoint.
72
+ 2. When the task shape is clear, read one matching scenario reference only if it will change tool timing, anchor choice, or summary content. Skip reference loading for obvious short applications where this main skill body is enough. Do not stop after checkpoint-only unless the prompt is intentionally lightweight.
73
+ 3. Add checkpoints at meaningful milestones: phase boundaries, risky attempts, reusable batch methods, and interruptions.
74
+ 4. Use `context_timeline` when the active path structure affects the next decision or compact target.
75
+ 5. At phase boundaries, run the compact gate before starting another phase. If the whole requested task is complete and only the final response remains, answer and wait; let the next user message determine whether cleanup is useful.
76
+ 6. After a successful compact, continue from the injected summary instead of dragging the full raw path forward.
77
+
78
+ ## Read the right reference
79
+
80
+ Read **one primary reference** based on task shape when the scenario pattern will affect tool timing, anchor choice, or summary content:
81
+
82
+ - search / research / reading-heavy work, especially web search, browser operation, or low-density webpages -> `references/search-research-and-reading.md`
83
+ - development / debugging / troubleshooting / refactoring / migration -> `references/development-and-troubleshooting.md`
84
+ - planning / staged execution / todo-driven work -> `references/planning-and-execution.md`
85
+ - repeated similar items / batch work -> `references/repeated-items-and-batch-work.md`
86
+ - task switching / pause-resume / interruptions to a mainline task / scattered-thread cleanup-and-continue -> `references/task-switching-and-cleanup.md`
87
+
88
+ Also read `references/retry-branch-and-pivot.md` when multiple approaches, failed branches, comparisons, retries, or pivots become central. For code/debugging work with repeated attempts, use both `references/development-and-troubleshooting.md` and `references/retry-branch-and-pivot.md`.
99
89
 
100
90
  ## Tool policy
101
91
 
102
92
  ### `context_checkpoint`
103
- This is the default tool in this mode.
104
93
 
105
- Use it:
106
- - before noisy work
107
- - before a new phase
108
- - after a meaningful milestone
109
- - before a risky attempt
110
- - before switching to another subtask
94
+ Default move. Use it before noisy work, a new phase, a risky attempt, switching subtasks, or after a meaningful milestone.
111
95
 
112
- Use semantic names so the timeline stays readable.
96
+ Use semantic names so the timeline stays readable:
113
97
 
114
- Recommended patterns:
115
98
  - `<task>-start`
116
99
  - `<task>-<phase>`
117
100
  - `<task>-<attempt>`
118
101
  - `<task>-<milestone>`
119
102
 
120
- Examples:
121
- - `auth-oauth-start`
122
- - `timeout-analysis-search`
123
- - `db-migration-plan`
124
- - `parser-fix-attempt-2`
125
- - `vendor-review-milestone-1`
103
+ Examples: `auth-oauth-start`, `timeout-analysis-search`, `db-migration-plan`, `parser-fix-attempt-2`.
126
104
 
127
105
  Avoid generic names like `start`, `checkpoint-1`, `phase-1`, or `retry`.
128
106
 
129
107
  ### `context_timeline`
130
- Use this tool to regain orientation.
131
-
132
- Use it:
133
- - when you feel lost or drifted
134
- - when several checkpoints or branches now exist
135
- - before choosing a rewind target
136
- - at major phase transitions if you need a quick map
137
- - when the thread feels cluttered and you want a structural view before acting
138
-
139
- When you inspect timeline, ask:
140
- - Where is the nearest clean anchor?
141
- - Has the current segment grown too long without a clean checkpoint?
142
- - Am I carrying a failed or stale branch forward?
143
- - Is there already a better checkpoint to rewind to?
144
-
145
- ### `context_rewind`
146
- Use this tool to compact a path that should no longer stay active in full.
147
-
148
- Use it:
149
- - after a noisy investigation has produced a stable finding
150
- - after a failed attempt has produced a clear lesson
151
- - after a completed phase where the next step is clear
152
- - after a representative item or branch has already taught you what you need
153
- - when the current path is dragging too much stale or low-value context forward
154
-
155
- A successful use of this mode often ends with `context_rewind`, not just more checkpointing.
156
-
157
- ## Rewind protocol
158
-
159
- ### When to rewind
160
- Rewind when the current phase is ready to be compacted.
161
-
162
- Good reasons to rewind:
163
- - a phase produced a stable finding or conclusion
164
- - a failed path produced a clear dead-end lesson
165
- - a milestone was reached and you want a cleaner continuation
166
- - a representative item or branch has already taught you the reusable lesson
167
- - the thread is carrying more stale intermediate process than active value
168
-
169
- A phase is usually rewind-ready when you now have one of these:
170
- - a root cause or research conclusion
171
- - a clear failure reason for abandoning a branch
172
- - a completed implementation or troubleshooting phase
173
- - a reusable method learned from a representative item
174
- - a finished repeated-item segment whose raw path no longer needs to stay live
175
-
176
- Do **not** rewind yet when:
177
- - you are still in the middle of active exploration
178
- - the result is still unstable or incomplete
179
- - you only feel mild clutter and a checkpoint would be enough
180
- - you have not yet decided which earlier anchor you want to continue from
181
-
182
- When in doubt: checkpoint first, review timeline if needed, and rewind later once the phase boundary is clearer.
183
-
184
- ### Choose the target and backup
185
- Choose the **best earlier clean anchor**, not just any earlier checkpoint.
186
-
187
- Usually prefer:
188
- - the start of the noisy phase you are compacting
189
- - the nearest clean phase-start before the current failed or completed path
190
- - the repeated-work anchor for repeated-item workflows
191
- - the last stable pre-branch checkpoint when abandoning an approach
192
108
 
193
- Avoid:
194
- - rewinding too far back when a nearer clean anchor exists
195
- - rewinding to a checkpoint that still includes the noise you want to leave behind
196
- - defaulting to `root` unless the whole active path should be reset
109
+ Use it as the structural view of the active path, not only as a rescue tool:
110
+
111
+ - when the current path shape affects the next decision
112
+ - when several checkpoints, branches, or task switches exist
113
+ - before choosing a compact target that is not obvious
114
+ - when the thread feels cluttered and you need to distinguish useful context from baggage
115
+
116
+ When reading the timeline, ask:
117
+
118
+ - What is the current task and immediate next action?
119
+ - Which prior raw messages are still needed for that next action?
120
+ - Which completed, failed, or unrelated paths are now baggage?
121
+ - Which anchor gives the smallest sufficient working set after summary injection?
122
+
123
+ ### `context_compact`
124
+
125
+ Use it to replace raw history with a state summary when the next phase would benefit from a smaller working set.
126
+
127
+ Typical compact boundaries: investigation -> execution, diagnosis -> fix, implementation -> validation, failed attempt -> next attempt, representative item -> remaining batch, completed noisy task -> new user task.
197
128
 
198
- If you are unsure which anchor is best, run `context_timeline` first.
129
+ Do not compact while exploration is still active, when the result is unstable, just because the skill triggered, or just because the user-visible task ended.
199
130
 
200
- Use `backupCheckpoint` when:
201
- - the raw path may still be useful later
202
- - you are compacting a long investigation
203
- - you are abandoning a branch but may need its details again
204
- - you want a safe recovery point before a major rewind
131
+ ## Compact gate
205
132
 
206
- A backup checkpoint preserves the raw path you are compacting. If the summary later proves insufficient, return to that backup instead of redoing the whole investigation.
133
+ Before calling `context_compact`, require all three:
207
134
 
208
- If the raw path is low value and unlikely to matter again, a backup is optional.
135
+ 1. The segment being left behind is noisy, stale, failed, low-value in raw form, or actively reducing focus.
136
+ 2. You can restore the useful task state in a clear summary.
137
+ 3. There is an immediate continuation that benefits from cleaner context.
209
138
 
210
- ### Write the message
211
- A rewind message is the baton pass to future-you. It is not a throwaway comment.
139
+ If the compact is prompted by a new user message, a direction shift, or several possible checkpoint targets, run `context_timeline` first and choose the target from the visible structure rather than from memory.
212
140
 
213
- At minimum, include:
214
- - the main result, lesson, or failure summary
215
- - why you are rewinding now
216
- - important changes, especially changed files if disk state changed
217
- - the next step after the rewind
141
+ Condition 3 means the next action is a new phase, not just more of the same exploration. Examples: run the export, implement the fix, validate, process the next item, or try the chosen next approach.
218
142
 
219
- Useful shapes:
220
- - `[result] + [reason for rewind] + [next step]`
221
- - `[result] + [reason for rewind] + [important decision or change] + [next step]`
222
- - `[result] + [reason for rewind] + [important changes / changed files] + [next step]`
143
+ If conditions 1 and 2 are true but the whole task is done and only the final answer remains, wait. Compact later only if the next user message makes it useful.
144
+
145
+ ## Choosing target and backup
146
+
147
+ Choose the continuation anchor by designing the next working set:
148
+
149
+ 1. Name the immediate next action.
150
+ 2. Decide what must remain raw: active user intent, current constraints, still-open evidence or code context, an approved plan being executed, or details you expect to inspect directly next.
151
+ 3. Decide what can become state summary or disappear: completed searches, verbose logs, failed attempts, stale branches, earlier unrelated tasks, and process details whose useful value is already clear.
152
+ 4. Pick the anchor that leaves the new branch with the **smallest sufficient context** after summary injection.
153
+ 5. If an older anchor plus a stronger summary is cleaner than a recent anchor plus stale context, prefer the older anchor.
154
+
155
+ The right target may be a recent phase-start, a plan-ready checkpoint, a pre-branch checkpoint, a repeated-work baseline, an older checkpoint, or `root`. `root` is appropriate when the old path no longer contributes raw context and the summary can carry the necessary state.
156
+
157
+ Avoid targets that create a poor working set:
158
+
159
+ - too late: the new branch still contains the clutter, failed path, or unrelated task you meant to leave behind
160
+ - too early with a weak summary: the next phase loses constraints, decisions, evidence, or changed-file state it needs
161
+ - semantically wrong: the anchor preserves a context frame that no longer matches the current task
162
+
163
+ For bounded phases, choose by what should remain raw:
164
+
165
+ - target `research-start` to summarize the whole research segment
166
+ - target `research-end` to keep research raw and summarize only later clutter before follow-up research
167
+
168
+ If there are several checkpoints, a task switch, or any uncertainty about the best working set, run `context_timeline` first.
169
+
170
+ Use `backupCheckpoint` when the raw path may still matter later: long investigations, abandoned branches, risky compactions, or details that may be needed for recovery. A backup checkpoint is a recovery safety net, not a substitute for the summary; include details likely needed in the next phase because returning to backup is costly.
171
+
172
+ ## Compact summary contract
173
+
174
+ The summary is not a transcript recap. It is the state needed to resume work from the chosen anchor; older or cleaner anchors require stronger summaries.
175
+
176
+ Context tools change conversation state, not the outside world. Files, processes, browser state, tickets, databases, remote services, and other side effects stay current. If you compact to an anchor before those changes, the summary must bridge the gap between old conversation context and current external state.
177
+
178
+ A compact summary must restore:
179
+
180
+ 1. **Task state:** current task, user intent, constraints, decisions, assumptions, and known result/progress/failure.
181
+ 2. **External state:** changed files, created/deleted artifacts, running/stopped processes, browser actions, tickets/records, deployments, remote changes.
182
+ 3. **Verification state:** commands already run, validation status, notable outputs, and remaining risks or open questions.
183
+ 4. **Navigation state:** source anchors/evidence when needed, rejected leads worth avoiding, backup checkpoint guidance, and the explicit next step.
184
+
185
+ Include why compacting is appropriate only when it helps future orientation. Avoid vague summaries like `Done`, `Investigated`, `Switching context`, or `Going back`.
223
186
 
224
187
  Good examples:
225
- - `Found DB connection pool exhaustion as the likely root cause. Reason: investigation phase is complete and ready to compact. Next step: report findings and propose mitigation.`
226
- - `Parser fix is implemented and the debugging phase is complete. Reason: compacting implementation history before focused validation. Important changes: modified src/parser.ts and test/parser.test.ts. Next step: run targeted validation and summarize remaining edge cases.`
227
- - `WeakRef approach failed because objects were collected too early and cache hit rate collapsed. Reason: abandoning this attempt and returning to a clean anchor. Next step: try object pooling instead.`
228
-
229
- Avoid vague messages like:
230
- - `Done`
231
- - `Switching context`
232
- - `Investigated`
233
- - `Going back`
234
-
235
- Before using `context_rewind`, quickly check:
236
- - Is there already a stable result, lesson, or failure summary?
237
- - Do I know why this is the right moment to rewind?
238
- - If disk state changed, did I record the important changes or changed files?
239
- - Is the next step explicit?
240
- - Would future-me understand what changed just from this message?
241
-
242
- If not, keep working a bit longer or checkpoint first.
243
-
244
- ### After rewind
245
- When `context_rewind` succeeds:
188
+
189
+ - `Current task: plan mitigation for API timeouts. State: DB pool exhaustion is the likely root cause. Evidence: logs show pool wait timeouts during peak traffic; config has pool size 10; no network errors found. Rejected lead: API gateway timeout appears downstream of DB waits. Next step: propose mitigation and validation steps.`
190
+ - `Current task: validate the parser fix. State: implementation is done. External state: changed files src/parser.ts and test/parser.test.ts. Validation not yet run after the final edit. Next step: run targeted parser tests and summarize remaining edge cases. Backup: parser-fix-debug-history if exact failed attempts are needed.`
191
+
192
+ Before compacting, quickly check: stable state? real continuation? anchor gives the smallest sufficient working set? summary restores state after that anchor? external side effects and validation captured? explicit next step?
193
+
194
+ ## After compact
195
+
246
196
  1. Read the injected summary carefully.
247
197
  2. Treat it as the new active state.
248
- 3. Execute the next step from that summary.
249
- 4. Do not keep reasoning from the full old path unless you intentionally return to a backup checkpoint.
198
+ 3. Before continuing, verify it contains enough state for the next action.
199
+ 4. Remember that disk and external systems were not rolled back by the context move; if state matters, inspect the current files/tools/services rather than trusting the historical anchor.
200
+ 5. If a missing detail is cheap to reconstruct from disk, tools, or source anchors, retrieve it directly.
201
+ 6. Return to the backup checkpoint only when the missing raw context cannot be reconstructed cheaply.
250
202
 
251
203
  ## Common mistakes
252
204
 
253
205
  Avoid:
254
- - checkpointing constantly without phase meaning
255
- - rewinding blindly without checking timeline when anchor choice is unclear
256
- - carrying completed noisy phases forward instead of compacting them
257
- - writing vague rewind messages that future-you cannot act on
258
-
259
- ## Read the right reference
260
206
 
261
- Read **one primary reference** based on the task shape:
262
- - search / research / reading-heavy work, especially web search, browser operation, or low-density webpage reading -> `references/search-research-and-reading.md`
263
- - development / debugging / troubleshooting / refactoring / migration -> `references/development-and-troubleshooting.md`
264
- - planning / staged execution / todo-driven work -> `references/planning-and-execution.md`
265
- - repeated similar items / batch work -> `references/repeated-items-and-batch-work.md`
266
- - task switching / pause-resume / cleanup-and-continue work -> `references/task-switching-and-cleanup.md`
267
-
268
- Then read the cross-cutting retry reference when needed:
269
- - multiple approaches, failed branches, compare, retry, or pivot behavior -> `references/retry-branch-and-pivot.md`
270
-
271
- Keep the mode simple:
272
- - checkpoint before mess
273
- - review timeline when orientation matters
274
- - rewind when a phase is ready to be compacted
207
+ - checkpointing constantly without phase meaning
208
+ - compacting blindly without timeline when anchor choice is unclear
209
+ - preserving too much raw history because older anchors or `root` feel risky
210
+ - using an old anchor or `root` with a weak summary that drops current task state
211
+ - compacting immediately after a final deliverable when no next user intent is known
212
+ - carrying completed noisy phases into a new task
213
+ - writing summaries that recap history but fail to restore current task state
214
+ - assuming compact or branch navigation reverts files, processes, browser state, or remote services
215
+ - omitting decisions, constraints, external side effects, changed files, validation status, or next step
@@ -15,7 +15,7 @@ These tasks often stay cleaner when treated as stages with anchors, instead of o
15
15
  1. Create a checkpoint before starting serious work.
16
16
  2. Add checkpoints before risky edits, new approaches, or major phase changes.
17
17
  3. Review the timeline when you need to understand the current shape of the work.
18
- 4. Rewind after a stable implementation milestone, a failed approach, or a completed troubleshooting phase.
18
+ 4. Compact after a stable implementation milestone, a failed approach, or a completed troubleshooting phase when there is another phase, attempt, validation step, or task switch that benefits from cleanup. If files, processes, or external systems changed, include those side effects in the summary because context navigation does not roll them back. If the completed phase is also the final user-visible deliverable, answer first and wait.
19
19
 
20
20
  ## Typical checkpoint moments
21
21
 
@@ -40,28 +40,28 @@ Run `context_timeline` when:
40
40
  - you are about to abandon one approach and restart from another anchor
41
41
  - you are unsure which checkpoint best represents the clean continuation point
42
42
 
43
- ## Rewind patterns
43
+ ## Compact patterns
44
44
 
45
45
  ### After a failed attempt
46
46
 
47
- Use rewind when an attempt clearly failed and you have a crisp summary of why.
47
+ Use compact when an attempt clearly failed and you have a crisp summary of why.
48
48
 
49
49
  ```javascript
50
- context_rewind({
50
+ context_compact({
51
51
  target: "memory-leak-fix-start",
52
- message: "WeakRef approach failed because objects were collected too early and cache hit rate collapsed. Reason: abandoning this attempt and returning to a clean anchor. Next step: try object pooling instead.",
52
+ summary: "Current task: continue the memory leak fix. State: WeakRef approach failed because objects were collected too early and cache hit rate collapsed. Decision: abandon WeakRef and try object pooling. Next step: implement the object-pooling approach.",
53
53
  backupCheckpoint: "memory-leak-weakref-raw-history"
54
54
  });
55
55
  ```
56
56
 
57
57
  ### After a completed phase
58
58
 
59
- Use rewind when a phase is done and you want to continue from a cleaner thread.
59
+ Use compact when a phase is done and the next phase would work better from a focused state summary than from the raw implementation/debugging trail. Do not use this as a reflexive final step after delivering the finished work; use it before validation, the next phase, the next attempt, or the next user task.
60
60
 
61
61
  ```javascript
62
- context_rewind({
62
+ context_compact({
63
63
  target: "parser-fix-start",
64
- message: "Parser fix is implemented and the debugging phase is complete. Reason: compacting implementation history before focused validation. Next step: run targeted validation and summarize remaining edge cases.",
64
+ summary: "Current task: validate the parser fix. State: implementation is done and the debugging trail can be summarized. External state: parser implementation and related tests were changed on disk; context navigation did not revert them. Validation not yet run after final edit. Next step: run targeted validation and summarize remaining edge cases.",
65
65
  backupCheckpoint: "parser-fix-debug-history"
66
66
  });
67
67
  ```
@@ -30,9 +30,10 @@ Both variants use the same context-management rhythm.
30
30
  2. Create a checkpoint for the clean plan-ready state.
31
31
  3. Execute one subtask or phase.
32
32
  4. If that subtask becomes noisy, let it get noisy locally.
33
- 5. Once the subtask produces a stable takeaway, rewind back to the plan-ready or phase-start anchor.
34
- 6. Continue with the next subtask from the clean anchor.
33
+ 5. Once the subtask produces a stable takeaway and another subtask or phase remains, compact to the anchor that gives the next subtask the cleanest sufficient working set, often the plan-ready or phase-start anchor.
34
+ 6. Continue with the next subtask from that focused working set.
35
35
  7. If the plan changes materially, checkpoint the updated plan state again.
36
+ 8. If the last subtask completes the user's whole request, give the final answer without an automatic compact; decide on cleanup at the next user message if the conversation continues.
36
37
 
37
38
  ## Useful anchors
38
39
 
@@ -49,16 +50,17 @@ Run `context_timeline` when:
49
50
  - several subtasks have already been executed
50
51
  - the plan has changed more than once
51
52
  - multiple branches now exist under the same plan
52
- - you are unsure whether to rewind to the overall plan anchor or the current phase-start anchor
53
+ - you are unsure whether the next subtask needs the overall plan, the current phase context, or only a summary
53
54
 
54
- ## When to rewind
55
+ ## When to compact
55
56
 
56
- Rewind when:
57
- - a subtask is complete and its raw execution path is no longer worth keeping active
57
+ Compact when:
58
+ - a subtask is complete, another subtask remains, and its raw execution path is no longer worth keeping active
58
59
  - a phase finished and the next phase should start from a cleaner state
59
60
  - the plan remains valid but the current execution segment has become noisy
61
+ - a later user message starts a new task after the plan-driven task completed noisily
60
62
 
61
- Do not rewind just because a todo list exists. Rewind when a specific execution segment has already served its purpose and can be compacted.
63
+ Do not compact just because a todo list exists. Compact when a specific execution segment has already served its purpose and can be compacted for an actual continuation. If the segment changed files, launched/stopped processes, or updated external systems, record those side effects in the summary; context navigation does not revert them.
62
64
 
63
65
  ## Replan
64
66
 
@@ -73,7 +75,7 @@ If the plan change is driven by failed branches or strategy shifts, also read `r
73
75
  ## Common mistakes
74
76
 
75
77
  Avoid:
76
- - keeping every finished subtask's raw reasoning active
77
- - rewinding too far back when the current plan-ready anchor is still valid
78
+ - keeping every finished subtask's raw reasoning active instead of preserving only the reusable state
79
+ - choosing an anchor that drops the current plan state without preserving it in the summary
78
80
  - failing to checkpoint the updated plan after a major replan
79
81
  - confusing repeated-item work with plan-driven work when the subtasks are actually different in nature
@@ -14,10 +14,10 @@ Use this reference when the items are similar enough that the same method should
14
14
  1. Create a checkpoint at the start of the overall repeated-item task.
15
15
  2. If item 1 teaches you a reusable approach, checkpoint again after that approach becomes clear.
16
16
  3. Work item by item.
17
- 4. Rewind after each completed item or completed mini-phase when the raw path is no longer worth carrying forward.
17
+ 4. Compact after each completed item or completed mini-phase when another item remains and the raw path is no longer worth carrying forward.
18
18
  5. Use timeline occasionally to verify that the history still has a clean structure.
19
19
 
20
- For repeated-item work, the default completion move is not "keep carrying the last item's raw reasoning". Once an item is done and its takeaway is stable, rewind back to the repeated-work anchor.
20
+ For repeated-item work, the default between-item move is not "keep carrying the last item's raw reasoning". Once an item is done, its takeaway is stable, and another item remains, compact to the repeated-work anchor or other baseline that preserves the reusable method without item-specific noise. If the last item completes the whole user request, deliver the final answer and wait for the next user message before deciding whether to compact.
21
21
 
22
22
  ## Useful anchors
23
23
 
@@ -31,16 +31,17 @@ Example checkpoint names:
31
31
 
32
32
  Run `context_timeline` when:
33
33
  - several items have already been processed
34
- - item-level work has created multiple branches or rewinds
34
+ - item-level work has created multiple branches or compactions
35
35
  - you want to confirm that the overall pattern still looks clean
36
36
  - you are about to choose which anchor repeated work should keep returning to
37
37
 
38
- ## When to rewind
38
+ ## When to compact
39
39
 
40
- Rewind after:
41
- - a representative item produced a reusable method
42
- - a single item is complete and the raw path should be compacted
40
+ Compact after:
41
+ - a representative item produced a reusable method and the batch will continue
42
+ - a single item is complete, another item remains, and the raw path should be compacted
43
43
  - an item-specific dead end is understood and should not remain active in full
44
+ - a new user message arrives after the batch completed, and the batch's raw path is stale baggage for the new task
44
45
 
45
46
  ## Example rhythm
46
47
 
@@ -53,16 +54,16 @@ context_checkpoint({ name: "vendor-review-method-clear" });
53
54
 
54
55
  // ... process another item ...
55
56
 
56
- context_rewind({
57
+ context_compact({
57
58
  target: "vendor-review-method-clear",
58
- message: "One more vendor review completed. Reason: compacting finished item work and returning to the clean repeated-item anchor. Next step: process the next vendor using the same method.",
59
+ summary: "Current task: continue the vendor review batch. State: one more vendor review is complete; item-specific reasoning no longer needs to stay raw. Reusable method remains the active baseline. Next step: process the next vendor using the same method.",
59
60
  backupCheckpoint: "vendor-review-item-7-history"
60
61
  });
61
62
  ```
62
63
 
63
64
  ## Warning signs
64
65
 
65
- Use stronger checkpoint/timeline/rewind discipline when:
66
+ Use stronger checkpoint/timeline/compact discipline when:
66
67
  - each item creates lots of local reasoning
67
68
  - you are starting to confuse one item's path with another's
68
69
  - the repeated work is stretching across many turns
@@ -5,7 +5,7 @@ Use this reference when multiple approaches are being tried and abandoned cleanl
5
5
  - failed branches that should not pollute the main line
6
6
  - compare-and-choose work
7
7
  - strategy pivots or goal shifts
8
- - restarting from a cleaner anchor after a dead end
8
+ - restarting from a focused working set after a dead end
9
9
 
10
10
  This is a **cross-cutting pattern reference**. Read it alongside a primary reference such as search/research, development/troubleshooting, or planning/execution when branch behavior becomes central.
11
11
 
@@ -14,24 +14,24 @@ This is a **cross-cutting pattern reference**. Read it alongside a primary refer
14
14
  1. Checkpoint before opening a risky branch or alternative path.
15
15
  2. Explore or implement that branch.
16
16
  3. If anchor choice becomes unclear, inspect timeline.
17
- 4. Once the branch produces a stable lesson, decision, or dead-end, rewind back to the best clean pre-branch anchor.
18
- 5. Continue with the next branch or the chosen direction from that clean state.
17
+ 4. Once the branch produces a stable lesson, decision, or dead-end, compact to the anchor that removes branch noise while preserving the state needed for the next attempt.
18
+ 5. Continue with the next branch or the chosen direction from that focused state.
19
19
 
20
20
  ## When to review timeline
21
21
 
22
22
  Run `context_timeline` when:
23
23
  - multiple branches now exist
24
24
  - you are unsure which branch actually stayed useful
25
- - you need to choose the cleanest pre-branch anchor
25
+ - you need to choose which pre-branch or older anchor gives the next attempt the best working set
26
26
  - the next direction is clear but the old branch still clutters active context
27
27
 
28
- ## When to rewind
28
+ ## When to compact
29
29
 
30
- Rewind when:
30
+ Compact when:
31
31
  - a branch clearly failed
32
32
  - a comparison is complete and one option won
33
33
  - the direction changed enough that the old path is now baggage
34
- - the next attempt should start from a cleaner base
34
+ - the next attempt should start from a focused state rather than the raw failed branch
35
35
 
36
36
  ## Strategy pivot
37
37
 
@@ -44,7 +44,7 @@ Examples:
44
44
 
45
45
  In these cases:
46
46
  - summarize what still matters
47
- - rewind back to the best clean anchor before the stale branch
47
+ - compact to the anchor that removes the stale branch while preserving current task state
48
48
  - continue under the new direction
49
49
 
50
50
  ## Example rhythm
@@ -54,9 +54,9 @@ context_checkpoint({ name: "oauth-fix-start" });
54
54
 
55
55
  // ... try cookie-based approach ...
56
56
 
57
- context_rewind({
57
+ context_compact({
58
58
  target: "oauth-fix-start",
59
- message: "Cookie-based approach is not viable because the callback flow loses session continuity. Reason: retrying from a clean anchor after a failed branch. Important decision: switch to signed state tokens. Next step: implement the signed-state approach.",
59
+ summary: "Current task: continue the OAuth fix with a new approach. State: cookie-based approach is not viable because the callback flow loses session continuity. Decision: switch to signed state tokens. Next step: implement the signed-state approach.",
60
60
  backupCheckpoint: "oauth-cookie-approach-history"
61
61
  });
62
62
  context_checkpoint({ name: "oauth-signed-state-start" });
@@ -67,5 +67,5 @@ context_checkpoint({ name: "oauth-signed-state-start" });
67
67
  Avoid:
68
68
  - opening alternative branches without a clean checkpoint first
69
69
  - dragging failed branches forward after their lesson is already clear
70
- - rewinding to a point that still includes the branch you meant to abandon
70
+ - compacting to a point that still includes the branch you meant to abandon
71
71
  - treating every branch as equally worth preserving
@@ -17,10 +17,12 @@ This reference is for **input-heavy work where the process is much larger than t
17
17
  1. Create a checkpoint before a large search or reading loop.
18
18
  2. Search, browse, read, inspect, and follow leads normally.
19
19
  3. If you lose orientation, review the timeline.
20
- 4. Once the investigation yields a stable finding, rewind to a cleaner anchor.
21
- 5. Continue with the conclusion, recommendation, or next action instead of carrying the entire raw exploration forward.
20
+ 4. Once the investigation yields a stable finding and there is another step to take, compact to the anchor that gives the next step a focused working set.
21
+ 5. Continue with the conclusion, recommendation, or next action instead of carrying the entire raw exploration forward. If the finding is the final answer to the user's current request, answer first and wait; compact on the next user message if it starts new work.
22
22
 
23
- Do not stop at "I already made a checkpoint" if the investigation phase is actually complete. The cleanup move for completed research is usually a rewind back to the best earlier anchor.
23
+ Do not stop at "I already made a checkpoint" if the investigation phase is complete and the conversation is continuing. The cleanup move for completed research is usually a compact to the anchor that preserves only the raw context the next step still needs.
24
+
25
+ **Important:** β€œanother step” includes the next phase of the same request. If you searched to find the right data source, previous task record, API shape, rule id, or query pattern, then the next execution step (running the real query/export, implementing, validating, etc.) is an immediate continuation. Compact before that execution step, not only before a future user message.
24
26
 
25
27
  ## When to checkpoint
26
28
 
@@ -44,17 +46,34 @@ Run `context_timeline` when:
44
46
  - the investigation has already produced multiple checkpoints
45
47
  - you are deciding which path should be compacted
46
48
 
47
- ## When to rewind
49
+ ## When to compact
48
50
 
49
- Rewind after the investigation produces one of these:
51
+ Compact after the investigation produces one of these and there is a continuation that benefits from cleanup:
50
52
  - a stable root cause
51
53
  - a stable comparison result
52
54
  - a dead-end conclusion
53
55
  - a shortlist of viable next actions
56
+ - a located data source, old conversation, schema, rule id, query/API pattern, or other fact that unlocks execution
57
+
58
+ If you already have one of these, the investigation phase is usually complete enough to compact. If the next step is to use the finding in another tool call, compact first. If there is no continuation yet because you are about to give the final answer, wait until the next user message before deciding.
59
+
60
+ Do not compact in the middle of a still-open search loop just because the thread feels busy.
61
+
62
+ ## Message quality for research compactions
63
+
64
+ Research compactions are especially sensitive to summary quality. The raw exploration may contain details that become important later, but returning to the backup branch is a context switch. Preserve the state needed to use the finding, not the whole journey.
54
65
 
55
- If you already have one of these, the investigation phase is usually complete enough to compact.
66
+ Include:
67
+ - **Current task/state:** what the research unlocked and how it will be used next
68
+ - **Finding:** what is now known
69
+ - **Source anchors:** key files, URLs, docs, sessions, commands, queries, or records used to reach the finding
70
+ - **Evidence:** important numbers, errors, examples, IDs, or constraints that support the finding
71
+ - **Rejected leads:** only expensive dead ends that future-you should not repeat
72
+ - **Open questions:** what is still uncertain
73
+ - **Next step:** what to do immediately after compact
74
+ - **Backup pointer:** if `backupCheckpoint` is set, when to return to it
56
75
 
57
- Do not rewind in the middle of a still-open search loop just because the thread feels busy.
76
+ Do not compress research to only β€œfound the answer”. That forces future-you to either trust an unsupported conclusion or switch back to the backup for basic details.
58
77
 
59
78
  ## Typical rhythm
60
79
 
@@ -63,17 +82,19 @@ context_checkpoint({ name: "timeout-investigation-start" });
63
82
 
64
83
  // ... search logs, read code, compare docs, inspect outputs ...
65
84
 
85
+ // Stable finding found and the next action is execution/validation, so compact before continuing.
66
86
  context_timeline();
67
87
 
68
- context_rewind({
88
+ context_compact({
69
89
  target: "timeout-investigation-start",
70
- message: "Found DB connection pool exhaustion as the likely root cause. Reason: investigation phase is complete and ready to compact. Next step: report findings and propose mitigation."
90
+ backupCheckpoint: "timeout-investigation-raw-history",
91
+ summary: "Current task: plan mitigation for API timeouts. State: DB connection pool exhaustion is the likely root cause. Evidence: logs show pool wait timeouts during peak traffic; config has pool size 10; no network errors found in the checked logs. Rejected lead: API gateway timeout was downstream of DB waits, not the origin. Backup: timeout-investigation-raw-history if exact log lines are needed. Next step: propose mitigation and validation steps."
71
92
  });
72
93
  ```
73
94
 
74
- ## Good rewind outcomes
95
+ ## Good compact outcomes
75
96
 
76
- After rewinding, you should be able to continue with:
97
+ After compacting, you should be able to continue with:
77
98
  - the finding
78
99
  - the recommendation
79
100
  - the next verification step
@@ -2,29 +2,34 @@
2
2
 
3
3
  Use this reference when the main problem is not the task domain itself, but a change in thread state, such as:
4
4
  - the user inserts a temporary side task
5
+ - the user starts a new task after a completed noisy task
5
6
  - you need to pause one line of work and resume it later
6
7
  - several active fronts now exist
7
8
  - the thread is already messy and needs cleanup before continuing
8
- - a finished noisy phase should be summarized and left behind
9
+ - a finished noisy phase should be summarized and left behind before new work starts
9
10
 
10
11
  This reference is for **pause/resume, cleanup, and clean continuation**. It is not for repeated similar items or plan-driven execution.
11
12
 
12
- ## Two common variants
13
+ ## Three common variants
13
14
 
14
15
  ### Interruption / task switch
15
16
  Use when you are actively switching away from one line of work and intend to come back.
16
17
 
18
+ ### Completed-task handoff
19
+ Use when a previous task is complete, the user has now said something new, and the previous task's raw path is noisy enough that it should not be carried into the new work.
20
+
17
21
  ### Cleanup and continue
18
22
  Use when the thread is already stale or messy and you want to compress it now, even though context management is being adopted late.
19
23
 
20
24
  ## Working pattern
21
25
 
22
26
  1. Inspect timeline if anchor choice is unclear.
23
- 2. Before switching away or compacting a noisy path, preserve the best clean anchor.
27
+ 2. Before switching away or compacting a noisy path, preserve or choose the anchor that will give the resumed/new task a clean working set.
24
28
  3. If needed, create a backup checkpoint for the current noisy branch.
25
- 4. Handle the side task or cleanup move.
26
- 5. Rewind away the stale path when the baton pass is clear.
27
- 6. Resume from the paused anchor or continue from the compacted state.
29
+ 4. If the user has just started a new task after a completed noisy task, compact before doing the new task so the completed task becomes a compact summary rather than active baggage.
30
+ 5. Handle the side task or cleanup move.
31
+ 6. Compact away the stale path when the handoff summary is clear.
32
+ 7. Resume from the paused anchor or continue from the compacted state.
28
33
 
29
34
  ## Useful anchors
30
35
 
@@ -40,24 +45,28 @@ Run `context_timeline` when:
40
45
  - multiple interruptions happened
41
46
  - the pause lasted many turns
42
47
  - several side-task branches now exist
43
- - you are unsure which clean anchor should be resumed
48
+ - you are unsure which anchor gives the resumed/new task the right working set
44
49
  - the thread is already messy and you need to find the right pre-noise checkpoint
45
50
 
46
- ## When to rewind
51
+ ## When to compact
47
52
 
48
- Rewind when:
53
+ Compact when:
49
54
  - the interruption created lots of noise
50
55
  - the side task is done and should not stay active in full
56
+ - the user begins a new task after a completed noisy task and the previous raw path is no longer useful in full
51
57
  - a stale path is making current reasoning worse
52
58
  - the useful state is now much smaller than the accumulated process
53
- - you can express the baton pass clearly in a summary
59
+ - you can express the handoff clearly in a summary
54
60
 
55
- If the interruption was tiny and clean, a rewind may be unnecessary. A checkpoint before switching away is still the key move.
61
+ Do not compact at the instant you finish a user-visible task if there is no known continuation. In that moment, deliver the answer and wait. If the next user message starts a new task, that is the right time to compact the completed task before proceeding. If the completed task changed files, browser state, tickets, or remote services, include those side effects in the handoff summary because the context move does not undo them. If the interruption was tiny and clean, a compact may be unnecessary. A checkpoint before switching away is still the key move.
56
62
 
57
63
  ## Common mistakes
58
64
 
59
65
  Avoid:
60
66
  - switching away without a pause checkpoint
67
+ - compacting immediately after a final answer just because the task completed
68
+ - starting a new, unrelated user task while still carrying the previous task's full raw path
61
69
  - returning to the main line while still carrying the side task's full raw path
62
70
  - trying to clean up without first checking timeline when anchor choice is unclear
63
- - over-resetting and losing still-valid near-term context
71
+ - resetting past still-valid near-term context without carrying it in the summary
72
+ - forgetting that files and external systems remain in their latest state after context navigation
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  type SessionManager,
4
4
  type SessionEntry,
5
5
  type ExtensionCommandContext,
6
+ type ContextUsage,
6
7
  } from "@earendil-works/pi-coding-agent";
7
8
  import {
8
9
  Type,
@@ -20,12 +21,21 @@ interface SessionTreeNode {
20
21
  label?: string;
21
22
  }
22
23
 
23
- const InternalTools = ["context_checkpoint", "context_timeline", "context_rewind"];
24
+ const InternalTools = ["context_checkpoint", "context_timeline", "context_compact"];
24
25
  let CommandCtx: ExtensionCommandContext | null = null;
25
- let RewindParams: any = null;
26
+ let CompactParams: any = null;
26
27
 
27
28
  const isInternal = (name: string) => InternalTools.includes(name);
28
29
 
30
+ const formatContextUsage = (usage: ContextUsage | undefined, includeTokens = false): string => {
31
+ if (usage?.percent == null) return "Unknown";
32
+
33
+ const percent = `${usage.percent.toFixed(1)}%`;
34
+ if (!includeTokens || usage.tokens == null) return percent;
35
+
36
+ return `${percent} (${formatTokens(usage.tokens)}/${formatTokens(usage.contextWindow)})`;
37
+ };
38
+
29
39
  const resolveTargetId = (sm: SessionManager, target: string): string => {
30
40
  if (target.toLowerCase() === "root") {
31
41
  const tree = sm.getTree();
@@ -47,20 +57,23 @@ const resolveTargetId = (sm: SessionManager, target: string): string => {
47
57
  return target;
48
58
  };
49
59
 
60
+ const ContextTimelineDescription = "Inspect the active conversation path as a structural map: checkpoints, summaries/compactions, branch points, user turns, and current position. Use when orientation or compact target selection depends on the shape of history.";
50
61
  const ContextTimelineParams = Type.Object({
51
- limit: Type.Optional(Type.Number({ description: "History limit for visible entries (default: 50)." })),
52
- verbose: Type.Optional(Type.Boolean({ description: "If true, show all messages. If false (default), collapse intermediate AI steps and only show milestones, user messages, checkpoints, branch points, and summaries." })),
62
+ limit: Type.Optional(Type.Number({ description: "Maximum visible timeline entries (default: 50)." })),
63
+ verbose: Type.Optional(Type.Boolean({ description: "If true, show all messages including internal context-tool traffic. If false (default), collapse to structural milestones." })),
53
64
  });
54
65
 
55
- const ContextRewindParams = Type.Object({
56
- target: Type.String({ description: "Where to rewind or compact to. Can be a checkpoint name, a history node ID, or root. This becomes the starting point for a fresh continuation of the conversation." }),
57
- message: Type.String({ description: "The carryover summary for the fresh continuation. Summarize current progress, lessons, important file changes, and the next step so the agent can continue from a clean context. A good summary message includes status, reason, important changes, and next step." }),
58
- backupCheckpoint: Type.Optional(Type.String({ description: "Optional checkpoint name to apply to the current conversation state before rewinding. Use this to preserve a named backup of the noisy path you are about to compact away." })),
66
+ const ContextCompactDescription = "Create a summarized continuation branch from an earlier checkpoint or history node. The selected target is the branch point; the summary must restore the useful state from the compacted path after that target. This changes conversation history only; it does not modify or roll back disk files or external systems.";
67
+ const ContextCompactParams = Type.Object({
68
+ target: Type.String({ description: "Checkpoint name, history node ID, or root to use as the branch point for the summarized continuation." }),
69
+ summary: Type.String({ description: "Handoff summary injected into the new continuation branch. Restore current task/state, decisions/constraints, important external side effects (changed files, processes, browser/tickets/remote state), validation status, source anchors/evidence/open questions likely needed soon, and explicit next step. Do not rely on backupCheckpoint for details needed in the next phase." }),
70
+ backupCheckpoint: Type.Optional(Type.String({ description: "Optional checkpoint name to label the current conversation state before branching. This is only a recovery pointer; the summary must still contain the state needed to continue." })),
59
71
  });
60
72
 
73
+ const ContextCheckpointDescription = "Create a named anchor by labeling a conversation history node. This does not branch, summarize, or affect external state; it only makes the point easy to find later in timeline or compact target selection.";
61
74
  const ContextCheckpointParams = Type.Object({
62
- name: Type.String({ description: "The checkpoint or milestone name. Use meaningful names." }),
63
- target: Type.Optional(Type.String({ description: "Optional history node ID or checkpoint name to label. Defaults to the current conversation position." })),
75
+ name: Type.String({ description: "Unique semantic anchor name that encodes the task and phase/purpose, e.g. parser-fix-start or timeout-investigation-search. Avoid generic names like start, checkpoint-1, or retry." }),
76
+ target: Type.Optional(Type.String({ description: "Optional history node ID or checkpoint name to label. Defaults to the current meaningful position near the conversation head." })),
64
77
  });
65
78
 
66
79
  export default function (pi: ExtensionAPI) {
@@ -69,15 +82,8 @@ export default function (pi: ExtensionAPI) {
69
82
  handler: async (args, ctx) => {
70
83
  CommandCtx = ctx;
71
84
  ctx.ui.notify("Agentic Context Management enabled.", "info");
72
- pi.sendMessage({
73
- customType: "pi-context",
74
- content: "use context-management skill",
75
- display: false,
76
- }, {
77
- deliverAs: "followUp"
78
- });
79
85
  if (args) {
80
- pi.sendUserMessage(args)
86
+ pi.sendUserMessage(args, { deliverAs: "followUp" });
81
87
  }
82
88
  }
83
89
  });
@@ -102,7 +108,7 @@ export default function (pi: ExtensionAPI) {
102
108
  pi.registerTool({
103
109
  name: "context_checkpoint",
104
110
  label: "Context Checkpoint",
105
- description: "Create a named checkpoint in the conversation history. Use this before risky work, before a long research pass, or whenever you reach a stable milestone.",
111
+ description: ContextCheckpointDescription,
106
112
  parameters: ContextCheckpointParams,
107
113
  async execute(_id, params: Static<typeof ContextCheckpointParams>, _signal, _onUpdate, ctx) {
108
114
  const sm = ctx.sessionManager as SessionManager;
@@ -157,14 +163,20 @@ export default function (pi: ExtensionAPI) {
157
163
  }
158
164
 
159
165
  pi.setLabel(id, params.name);
160
- return { content: [{ type: "text", text: `Created checkpoint '${params.name}' at ${id}` }], details: {} };
166
+ return {
167
+ content: [{
168
+ type: "text",
169
+ text: `Created checkpoint '${params.name}' at ${id}.`
170
+ }],
171
+ details: {}
172
+ };
161
173
  },
162
174
  });
163
175
 
164
176
  pi.registerTool({
165
177
  name: "context_timeline",
166
178
  label: "Context Timeline",
167
- description: "Show the conversation timeline, checkpoints, summaries, and current position. Use this to understand session structure, monitor drift, and choose a checkpoint to return to.",
179
+ description: ContextTimelineDescription,
168
180
  parameters: ContextTimelineParams,
169
181
  async execute(_id, params: Static<typeof ContextTimelineParams>, _signal, _onUpdate, ctx) {
170
182
  const sm = ctx.sessionManager as SessionManager;
@@ -342,11 +354,7 @@ export default function (pi: ExtensionAPI) {
342
354
  }
343
355
 
344
356
  // --- Context Dashboard (HUD) ---
345
- const usage = await ctx.getContextUsage();
346
- let usageStr = "Unknown";
347
- if (usage?.percent != null && usage.tokens != null && usage.contextWindow != null) {
348
- usageStr = `${usage.percent.toFixed(1)}% (${formatTokens(usage.tokens)}/${formatTokens(usage.contextWindow)})`;
349
- }
357
+ const usageStr = formatContextUsage(ctx.getContextUsage(), true);
350
358
 
351
359
  // Find the distance to the nearest checkpoint
352
360
  let stepsSinceCheckpoint = 0;
@@ -361,10 +369,15 @@ export default function (pi: ExtensionAPI) {
361
369
  stepsSinceCheckpoint++;
362
370
  }
363
371
 
372
+ const compactCue = nearestCheckpointName === "None"
373
+ ? "create a checkpoint before the next noisy phase"
374
+ : `if this segment has produced a stable result and another phase remains, compact to '${nearestCheckpointName}' with a handoff summary before continuing`;
375
+
364
376
  const hud = [
365
377
  `[Context Dashboard]`,
366
378
  `β€’ Context Usage: ${usageStr}`,
367
379
  `β€’ Segment Size: ${stepsSinceCheckpoint} steps since last checkpoint '${nearestCheckpointName}'`,
380
+ `β€’ Compact Cue: ${compactCue}`,
368
381
  `---------------------------------------------------`
369
382
  ].join("\n");
370
383
 
@@ -373,11 +386,11 @@ export default function (pi: ExtensionAPI) {
373
386
  });
374
387
 
375
388
  pi.registerTool({
376
- name: "context_rewind",
377
- label: "Conversation Rewind",
378
- description: "Return to an earlier conversation checkpoint and start a fresh continuation with a carryover summary. This changes session history only and does not modify disk files. Always provide a detailed message.",
379
- parameters: ContextRewindParams,
380
- async execute(_id, params: Static<typeof ContextRewindParams>, _signal, _onUpdate, ctx) {
389
+ name: "context_compact",
390
+ label: "Context Compact",
391
+ description: ContextCompactDescription,
392
+ parameters: ContextCompactParams,
393
+ async execute(_id, params: Static<typeof ContextCompactParams>, _signal, _onUpdate, ctx) {
381
394
  if (!CommandCtx) {
382
395
  ctx.ui.setEditorText(`/acm ${ctx.ui.getEditorText() || "continue"}`)
383
396
  return {
@@ -389,6 +402,7 @@ export default function (pi: ExtensionAPI) {
389
402
  };
390
403
  }
391
404
  const sm = ctx.sessionManager as SessionManager;
405
+ const usageBeforeText = formatContextUsage(ctx.getContextUsage());
392
406
 
393
407
  const tid = resolveTargetId(sm, params.target);
394
408
 
@@ -402,46 +416,69 @@ export default function (pi: ExtensionAPI) {
402
416
  const currentLabel = currentLeaf ? sm.getLabel(currentLeaf) : undefined;
403
417
  const origin = currentLabel ? `checkpoint: ${currentLabel}` : (currentLeaf || "unknown");
404
418
 
405
- const enrichedMessage = `(summary from ${origin})\n${params.message}`;
419
+ const enrichedMessage = `(handoff summary from ${origin})\n${params.summary}`;
406
420
 
407
421
  const nid = await sm.branchWithSummary(tid, enrichedMessage);
408
- RewindParams = params;
409
- RewindParams.nid = nid;
410
- RewindParams.tid = tid;
411
- RewindParams.enrichedMessage = enrichedMessage;
422
+ CompactParams = params;
423
+ CompactParams.nid = nid;
424
+ CompactParams.tid = tid;
425
+ CompactParams.enrichedMessage = enrichedMessage;
426
+ CompactParams.usageBeforeText = usageBeforeText;
412
427
 
413
- return { content: [{ type: "text", text: "rewind start" }], details: {} };
428
+ return { content: [{ type: "text", text: "compact start" }], details: {} };
414
429
  },
415
430
  });
416
431
 
417
432
  pi.on("turn_end", async (_event, ctx) => {
418
- if (!RewindParams) {
433
+ if (!CompactParams) {
419
434
  return
420
435
  }
421
436
  ctx.abort()
422
437
  });
423
438
 
424
- pi.on("agent_end", async (_event, ctx) => {
425
- if (!RewindParams) {
439
+ pi.on("agent_end", async () => {
440
+ if (!CompactParams) {
426
441
  return
427
442
  }
428
443
  if (!CommandCtx) {
429
444
  return
430
445
  }
431
446
 
432
- await CommandCtx.navigateTree(RewindParams.nid, {
433
- summarize: false,
434
- });
435
-
436
- ctx.ui.notify(`Rewound to ${RewindParams.target}${RewindParams.target === RewindParams.tid ? "" : `(${RewindParams.tid})`}\nBackup checkpoint created: ${RewindParams.backupCheckpoint || "none"}\nmessage: ${RewindParams.enrichedMessage}`, "info");
437
- RewindParams = null;
447
+ const compactParams = CompactParams;
448
+ const commandCtx = CommandCtx;
449
+ CompactParams = null;
450
+
451
+ // `agent_end` is emitted before the core Agent is actually idle. If we
452
+ // call pi.sendMessage({ triggerTurn: true }) inside this handler, pi still
453
+ // sees an active stream and queues the message as steering; after
454
+ // `agent_end` the loop has already stopped, so that queued message is not
455
+ // drained. Defer navigation + continuation until the current run settles.
456
+ setTimeout(async () => {
457
+ try {
458
+ await commandCtx.waitForIdle();
459
+ await commandCtx.navigateTree(compactParams.nid, {
460
+ summarize: false,
461
+ });
438
462
 
439
- pi.sendMessage({
440
- customType: "pi-context",
441
- content: "context_rewind complete. A summary of your previous conversation path was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",
442
- display: false,
443
- }, {
444
- triggerTurn: true,
445
- });
463
+ const usageAfter = commandCtx.getContextUsage();
464
+ commandCtx.ui.notify([
465
+ `Compacted to ${compactParams.target}${compactParams.target === compactParams.tid ? "" : `(${compactParams.tid})`}`,
466
+ `Context Usage: ${compactParams.usageBeforeText} -> ${formatContextUsage(usageAfter)}`,
467
+ `Backup checkpoint created: ${compactParams.backupCheckpoint || "none"}`,
468
+ `Summary: ${compactParams.enrichedMessage}`,
469
+ ].join("\n"), "info");
470
+
471
+ pi.sendMessage({
472
+ customType: "pi-context",
473
+ content: "context_compact complete. A handoff summary of your previous conversation path was injected above. Read it to understand your new state. Execute the Next Step from the summary",
474
+ display: false,
475
+ }, {
476
+ triggerTurn: true,
477
+ deliverAs: "followUp",
478
+ });
479
+ } catch (err) {
480
+ commandCtx.ui.notify(`context_compact failed to continue: ${err instanceof Error ? err.message : String(err)}`, "error");
481
+ }
482
+ }, 0);
446
483
  });
447
484
  }