pi-context 1.1.4 → 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,11 +1,21 @@
1
- # Pi Context: Agentic Context Management for the Pi
1
+ # Pi Context: Agentic Context Management for Pi
2
2
 
3
- A Git-like context management tool that allows AI agents to proactively manage their context.
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
- Inspired by kimi-cli d-mail, implementing lossless time travel on the Pi session tree.
5
+ Inspired by kimi-cli d-mail, it brings lossless time travel to Pi's session tree.
6
6
 
7
- For the design philosophy, see the [blog post](https://blog.xlab.app/p/51d26495/)
8
- ([中文版本](https://blog.xlab.app/p/6a966aeb/)).
7
+ For more on the design philosophy, see the [blog post](https://blog.xlab.app/p/51d26495/) ([中文版本](https://blog.xlab.app/p/6a966aeb/)).
8
+
9
+ ## Naming migration note
10
+
11
+ Earlier versions used more Git-like names such as `context_tag`, `context_log`, and `context_checkout`.
12
+
13
+ Current versions intentionally use conversation-native names instead:
14
+ - `context_checkpoint`
15
+ - `context_timeline`
16
+ - `context_compact`
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`. Context navigation does not modify or roll back files, running processes, browser state, tickets, databases, or remote services.
9
19
 
10
20
  ## Installation
11
21
 
@@ -17,13 +27,13 @@ pi install npm:pi-context
17
27
 
18
28
  ### For Humans
19
29
 
20
- Run the command to enable ACM (**A**gentic **C**ontext **M**anagement) for the current session.
30
+ Run the following command to enable ACM (**A**gentic **C**ontext **M**anagement) for the current session.
21
31
 
22
32
  ```bash
23
33
  /acm
24
34
  ```
25
35
 
26
- View detailed context window usage and token distribution with a visual dashboard. (like `claude code /context`)
36
+ Open a visual dashboard to inspect context-window usage and token distribution (similar to `claude code /context`).
27
37
 
28
38
  ```bash
29
39
  /context
@@ -33,13 +43,13 @@ View detailed context window usage and token distribution with a visual dashboar
33
43
 
34
44
  ### For Agents
35
45
 
36
- This extension adds the `context-management` skill with 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:
37
47
 
38
- 1. **🔖 Structure (`context_tag`)**
39
- `git tag` Create named milestones to structure your 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`.
40
50
 
41
- 2. **📊 Monitor (`context_log`)**
42
- `git log` Visualize your conversation history, check 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.
43
53
 
44
- 3. **⏪ Compress (`context_checkout`)**
45
- `git checkout` Move the HEAD pointer to any tag or commit ID. Compress completed tasks into a summary to free up context window space.
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,15 +1,15 @@
1
1
  {
2
2
  "name": "pi-context",
3
- "version": "1.1.4",
4
- "description": "Agentic Context Management for the Pi",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
3
+ "version": "2.0.0",
4
+ "description": "Agentic Context Management for Pi",
7
5
  "files": [
8
6
  "src",
9
7
  "skills",
10
8
  "README.md"
11
9
  ],
12
- "scripts": {},
10
+ "scripts": {
11
+ "typecheck": "tsc --noEmit"
12
+ },
13
13
  "keywords": [
14
14
  "pi-agent",
15
15
  "pi-package",
@@ -23,9 +23,10 @@
23
23
  "author": "",
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
- "@sinclair/typebox": "^0.34.13",
27
- "typescript": "^5.7.2",
28
- "@earendil-works/pi-coding-agent": "latest"
26
+ "@earendil-works/pi-ai": "^0.75.4",
27
+ "@earendil-works/pi-coding-agent": "^0.75.4",
28
+ "@earendil-works/pi-tui": "^0.75.4",
29
+ "typescript": "^5.7.2"
29
30
  },
30
31
  "pi": {
31
32
  "extensions": [
@@ -40,5 +41,10 @@
40
41
  "repository": {
41
42
  "type": "git",
42
43
  "url": "git+https://github.com/ttttmr/pi-context.git"
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-ai": "*",
47
+ "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-tui": "*"
43
49
  }
44
- }
50
+ }
@@ -1,258 +1,215 @@
1
1
  ---
2
2
  name: context-management
3
- description: Strategies for efficient context management using context_log, context_tag, and context_checkout. Learn when to tag, how to visualize the graph, and safe ways to squash history. Use for complex refactoring, debugging, and long conversations.
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
- **CRITICAL: THIS SKILL MANAGES YOUR MEMORY. WITHOUT IT, YOU WILL FORGET.**
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
- Your context window is limited. As conversations grow, "pollution" (noise, failed attempts) degrades your reasoning.
10
+ Core rhythm:
11
11
 
12
- **YOU MUST PROACTIVELY MANAGE YOUR HISTORY.**
13
- Do not wait for the user to tell you.
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**
14
15
 
15
- ## The Core Philosophy: Build, Perceive, Navigate
16
+ Use only these tools:
16
17
 
17
- ```
18
- Context Window = RAM (Expensive, volatile, limited)
19
- Context Graph = Disk (Cheap, persistent, unlimited)
18
+ - `context_checkpoint`
19
+ - `context_timeline`
20
+ - `context_compact`
20
21
 
21
- Move finished tasks from RAM to the Graph.
22
- ```
22
+ ## Working-set model
23
23
 
24
- Manage your context window like a Git repository. You are the maintainer.
24
+ Before choosing a tool, ask:
25
25
 
26
- 1. **BUILD the Skeleton (`context_tag`)**:
27
- * Raw conversation is a flat list. **Tags create structure.**
28
- * Without tags, `context_log` is just a list of IDs. With tags, it is a **Map**.
29
- 2. **PERCEIVE the State (`context_log`)**:
30
- * Check the HUD: Is "Segment Size" too big? You are drifting.
31
- * Check the Graph: Where are you? Are you in a deep branch?
32
- 3. **NAVIGATE & MERGE (`context_checkout`)**:
33
- * **Squash:** Convert a messy "feature branch" (thinking process) into a single "merge commit" (summary).
34
- * **Jump:** Move between tasks or retry paths without carrying baggage.
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?
35
30
 
36
- ## Quick Start: The Loop
31
+ Classify context into three forms:
37
32
 
38
- Follow this cycle for every major task:
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.
39
36
 
40
- 1. **CHECK:** Verify state.
41
- `context_log`
42
- 2. **START:** Tag the beginning with a semantic name.
43
- `context_tag({ name: "<task-slug>-start" })` // e.g., `auth-login-start`
44
- 3. **WORK:** Execute steps.
45
- 4. **MILESTONE:** Tag intermediate stable states.
46
- `context_tag({ name: "<task-slug>-plan" })` // e.g., `auth-login-plan`
47
- 5. **SQUASH (Autonomous):** If history becomes noisy or low-density, **Squash with Backup**.
48
- * *Action:* `context_checkout({ target: "<task-slug>-start", message: "...", backupTag: "<task-slug>-raw-history" })`
49
- * *Action (Optional):* `context_tag({ name: "<task-slug>-done" })`
50
- * *Safety:* If you need the details later, checkout the backup tag.
37
+ If the active context is already small, coherent, and directly useful for the next step, do not manage it just to be tidy.
51
38
 
52
- ## Tool Reference
39
+ ## When to use
53
40
 
54
- | Tool | Analog | Purpose | When to Use |
55
- | :--- | :--- | :--- | :--- |
56
- | `context_tag` | `git tag` | Bookmark a stable state. | Before risky changes. Before starting a new task. |
57
- | `context_log` | `git log` | See where you are. | When you feel lost. To find IDs for checkout. |
58
- | `context_checkout`| `git reset --soft` | **Time Travel / Squash.** | To undo mistakes. To compress history. |
41
+ Use this mode when the user is asking for work that may outgrow one clean thread:
59
42
 
60
- ## Critical Rules
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
45
+ - investigate -> decide -> execute -> validate
46
+ - plan -> implement -> verify
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
61
52
 
62
- ### Tag Wisely (Build The Skeleton)
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).
63
54
 
64
- Tags are the "Table of Contents". Name them so you can understand the history at a glance.
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.
65
56
 
66
- **Naming Formula:** `<task-slug>-<phase>`
57
+ ## Start-of-turn check
67
58
 
68
- * **task-slug**: Short, kebab-case identifier for the task (e.g., `auth-login`, `db-migration`)
69
- * **phase**: The stage of work (`start`, `plan`, `impl`, `done`, `fail`, `backup`)
59
+ At the start of each new user message, classify it:
70
60
 
71
- | Bad (Generic) | Good (Semantic) | Why |
72
- | :--- | :--- | :--- |
73
- | `task-start` | `auth-oauth-start` | Describes WHAT task |
74
- | `pre-research` | `error-log-analysis-start` | Future-you knows the topic |
75
- | `phase-1-done` | `db-schema-plan-done` | Know which phase of which task |
76
- | `debug-retry` | `null-pointer-fix-retry` | What bug? |
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.
77
64
 
78
- **Tag Categories:**
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.
79
66
 
80
- | Category | Pattern | Examples |
81
- | :--- | :--- | :--- |
82
- | **Start** | `<task>-start` | `auth-jwt-start`, `docker-setup-start` |
83
- | **Plan** | `<task>-plan` | `api-v2-plan`, `migration-plan` |
84
- | **Milestone** | `<task>-<milestone>` | `auth-jwt-impl-done`, `tests-passed` |
85
- | **Backup** | `<task>-raw-history` | `auth-jwt-raw-history` |
86
- | **Failure** | `<task>-fail-<reason>` | `auth-jwt-fail-timeout` |
67
+ This prevents both premature cleanup after final answers and endless checkpoint-only behavior that lets stale work accumulate.
87
68
 
88
- **How to generate:** Ask yourself "What is the task?" → Extract 1-3 keywords (e.g., "fix login timeout" → `login-timeout-fix-start`)
69
+ ## Main loop
89
70
 
90
- ### Squash Noise, Keep Signal, Focus on Goal (Context Hygiene)
91
- Think of your conversation as a "Feature Branch" full of messy thoughts.
92
- **You must distinguish Signal from Noise.**
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.
93
77
 
94
- * **Signal (High Value):** Design decisions, user constraints, final working code. -> **KEEP.**
95
- * **Noise (Low Value):** Failed attempts, long tool outputs, "thinking" steps. -> **SQUASH.**
96
- * **Focus on Goal:** Ask yourself: "Does this message help me achieve the current goal?" -> **KEEP.**
78
+ ## Read the right reference
97
79
 
98
- **When to Squash:**
99
- 1. **Task Done:** Convert the messy process into one clean summary.
100
- 2. **Low Density:** You read 2000 lines but only found 1 error.
80
+ Read **one primary reference** based on task shape when the scenario pattern will affect tool timing, anchor choice, or summary content:
101
81
 
102
- **Safety:** Squashing is **LOSSLESS**.
103
- By using `backupTag`, you save the "Messy Branch" forever. You can always checkout the backup tag if the summary isn't enough.
104
- * **Main Trunk:** Jump back to the summary.
105
- * **Backup Tag:** Jump back to the raw details.
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`
106
87
 
107
- ### Fail Fast, Revert Faster
108
- If you fail 3 times:
109
- 1. **STOP.** Don't try a 4th time.
110
- 2. `context_checkout` back to the last safe tag.
111
- 3. Summarize the failure in the checkout message ("Tried X, failed because Y").
112
- 4. Try a new approach from the clean state.
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`.
113
89
 
114
- ### After Checkout: Execute Next Step
115
-
116
- When `context_checkout` completes and injects a summary, you are in a **new context**.
117
-
118
- 1. **READ** the injected summary carefully
119
- 2. **EXECUTE** the `Next Step` from the summary - this is your new task.
90
+ ## Tool policy
120
91
 
121
- ## Decision Matrix: When to Act
122
-
123
- | Situation | Action | Reason |
124
- | :--- | :--- | :--- |
125
- | **Starting Task** | `context_tag({ name: "<task-slug>-start" })` | Create a rollback point. |
126
- | **Research / Logs** | `context_checkout` (Squash) | **Process is Noise.** Read 2000 lines -> Keep result. |
127
- | **Messy Debugging** | **Squash w/ Backup** | **Cleanup.** The error logs are noise once fixed. |
128
- | **Task Done (Candidate)**| **Squash w/ Backup** | **Assume Success.** Summary is usually enough. Backup exists if not. |
129
- | **Goal Shift** | `context_checkout` (Squash) | Old context is irrelevant. |
130
- | **Drift (some steps w/o tag)** | **Tag (Milestone)** | Maintain the skeleton. Don't fly blind. |
131
-
132
- ## The "Context Health" Check
133
-
134
- If you cannot answer these, run `context_log`:
92
+ ### `context_checkpoint`
135
93
 
136
- | Question | Answer Source |
137
- | :--- | :--- |
138
- | **Where is the skeleton?** | The sequence of `tag`s in the log. |
139
- | **Is this history useful?** | If "No" -> **SQUASH IT.** |
140
- | **Am I in a loop?** | Repeated entries in the graph. |
141
-
142
- ## Good Checkout Messages
143
-
144
- The `message` is your lifeline to your past self.
145
- A good message preserves critical context that would otherwise be lost.
146
-
147
- Structure: `[Key Finding/Status] + [Reason] + [Important Changes] + [Next Step]`
148
-
149
- * **Key Finding/Status**: What did you discover or complete? Include specific numbers, errors, or outcomes.
150
- * **Reason**: Why are you branching/moving? (e.g., "Task complete", "Approach failed", "Need raw logs")
151
- * **Important Changes**: What files or logic have been modified? (This checkout only resets *conversation history*, NOT disk files, so you must remember what changed.)
152
- * **Next Step**: What should you do immediately after this squash? Be specific. (e.g., "Wait for user feedback", "Implement the recommended fix", "Revert file X and try approach Y")
153
-
154
- Examples:
155
-
156
- * *Good (Resetting after failure)*: "Recursive parser hit stack overflow at depth 8000. Switching to iterative. **Reason**: Stack limit reached. **Important Changes**: Modified `utils/recursion.ts`. **Next Step**: Inform user of the failure and propose iterative approach."
157
- * *Good (Cleaning up)*: "Auth module complete: JWT + OAuth2 + RBAC. 23 tests passing. **Reason**: Task done, cleaning context. **Important Changes**: Created `auth/`, modified `routes.ts` and `middleware.ts`. **Next Step**: Report completion to user, ask if they want to review or test."
158
- * *Bad*: "Switching context." (Too vague - you will forget why)
159
- * *Bad*: "Done." (What is done? What should you do next?)
160
-
161
- ## Anti-Patterns
162
-
163
- | Don't | Do Instead |
164
- | :--- | :--- |
165
- | **Blind Tagging** (Tagging without looking) | **Check** (`context_log`) to avoid duplicates or tagging noise. |
166
- | **Over-Tagging** (Tagging every step) | **Tag** only major phase changes (`start`, `milestone`). |
167
- | **Hoard** (Keep all history "just in case") | **Squash** low-density history (research, logs). |
168
- | **Panic** (Apologize repeatedly for errors) | **Revert** (`context_checkout`) to before the error. |
169
- | **Blind Checkout** (Guessing IDs) | **Look** (`context_log`) first to get valid IDs. |
170
- | **Vague Summaries** ("Done", "Fixed") | **Detailed Summaries** ("Found bug in line 40. Fixed with patch X.") |
171
- | **Generic Tag Names** (`task-start`, `phase-1`) | **Semantic Names** (`auth-jwt-start`, `db-schema-plan`) |
172
- | **Missing Next Step** in checkout message | **Always specify** what to do after squash (e.g., "Wait for user", "Implement fix X") |
173
-
174
- ## Recipes (Copy-Paste)
175
-
176
- ### 1. The "Miner" (Immediate Squash)
177
- **Goal:** Pure information gathering (Reading files, Searching web).
178
- **Why:** The *process* of searching is irrelevant. Only the *result* matters.
179
-
180
- **Example Task:** Analyzing error logs to find root cause of timeout
181
-
182
- ```javascript
183
- // 1. Tag BEFORE starting the noisy work (use descriptive name)
184
- context_tag({ name: "timeout-analysis-start" });
185
-
186
- // ... (Read 5 log files, search 3 docs, find DB connection pool exhaustion) ...
187
-
188
- // 2. Squash IMMEDIATELY. Do not wait for user.
189
- context_checkout({
190
- target: "timeout-analysis-start",
191
- message: "Found DB connection pool exhaustion as root cause (pool size: 10, peak load: 1000 req/s). Recommended fix: increase to 50. **Reason**: Context cleanup after research. **Important Changes**: None (read-only). **Next Step**: Report findings to user and await approval to implement fix.",
192
- backupTag: "timeout-analysis-raw-history" // Safety backup
193
- });
194
- context_tag({ name: "timeout-analysis-done" });
195
- ```
196
-
197
- ### 2. The "Candidate" (Wait for Confirmation)
198
- **Goal:** You finished a complex task.
199
- **Why:** The history is noisy. The result is clean.
200
- **Safety:** We create a backup tag automatically.
201
-
202
- **Example Task:** Implementing OAuth login flow
203
-
204
- ```javascript
205
- // Squash to Summary (Optimistic Cleanup)
206
- context_checkout({
207
- target: "oauth-impl-start", // Squash range: Start -> Now
208
- message: "OAuth2 flow implemented with PKCE, Google + GitHub providers. All 12 tests passing. **Reason**: Task complete, cleaning up. **Important Changes**: Created `auth/oauth.ts`, modified `routes.ts`, `config.ts`. **Next Step**: Report completion to user, summarize what was implemented.",
209
- backupTag: "oauth-impl-raw-history"
210
- });
211
- context_tag({ name: "oauth-impl-candidate" });
212
- ```
213
-
214
- ### 3. The "Undo" (Revert Squash)
215
- **Goal:** User asks about a detail you squashed away.
216
- **Action:** Jump back to the backup tag.
217
-
218
- **Example Task:** Reviewing OAuth implementation details
219
-
220
- ```javascript
221
- // Jump back to the raw history
222
- context_checkout({
223
- target: "oauth-impl-raw-history",
224
- message: "Reviewing token refresh logic - user reports 401 after 15 min idle. Suspect refresh token not firing. **Reason**: Need raw logs to trace the bug. **Important Changes**: None. **Next Step**: Re-read token refresh implementation and identify the bug."
225
- });
226
- context_tag({ name: "oauth-review-start" });
227
- ```
228
-
229
- ### 4. Branching (Alternative Approach)
230
- **Scenario:** Method A failed (and was squashed). You want to try Method B from the clean state.
231
- **Action:** Checkout the start point.
232
-
233
- **Example Task:** Fixing memory leak - trying different approaches
234
-
235
- ```javascript
236
- // Method A (weak references) failed, trying Method B (object pooling)
237
- context_checkout({
238
- target: "memory-leak-fix-start",
239
- message: "WeakRef approach failed: objects GC'd within 30s (expected: 5min). Cache hit rate dropped from 95% to 12%. **Reason**: Switching to object pooling approach. **Important Changes**: `CacheManager.ts` modified (will revert). **Next Step**: Revert `CacheManager.ts` changes and implement object pooling strategy."
240
- });
241
- context_tag({ name: "memory-leak-pool-approach-start" });
242
- ```
243
-
244
- ### 5. The "Undo" (Failed Attempt)
245
- You tried to fix a bug but broke everything.
246
- **Goal:** Clean up a failed path.
247
-
248
- **Example Task:** Fixing race condition in async handler
249
-
250
- ```javascript
251
- // Attempted mutex-based fix, but introduced deadlock
252
- context_checkout({
253
- target: "race-condition-fix-start",
254
- message: "Mutex caused deadlock: Thread A holds mutex, awaits callback; callback needs mutex held by B; B waits for A. Circular wait detected. **Reason**: Trying lock-free CAS approach next. **Important Changes**: `AsyncQueue.ts` lines 70-90 modified (backup saved). **Next Step**: Revert `AsyncQueue.ts` and implement lock-free compare-and-swap approach.",
255
- backupTag: "race-condition-mutex-fail" // Save the failure for reference
256
- });
257
- context_tag({ name: "race-condition-lockfree-start" });
258
- ```
94
+ Default move. Use it before noisy work, a new phase, a risky attempt, switching subtasks, or after a meaningful milestone.
95
+
96
+ Use semantic names so the timeline stays readable:
97
+
98
+ - `<task>-start`
99
+ - `<task>-<phase>`
100
+ - `<task>-<attempt>`
101
+ - `<task>-<milestone>`
102
+
103
+ Examples: `auth-oauth-start`, `timeout-analysis-search`, `db-migration-plan`, `parser-fix-attempt-2`.
104
+
105
+ Avoid generic names like `start`, `checkpoint-1`, `phase-1`, or `retry`.
106
+
107
+ ### `context_timeline`
108
+
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.
128
+
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.
130
+
131
+ ## Compact gate
132
+
133
+ Before calling `context_compact`, require all three:
134
+
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.
138
+
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.
140
+
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.
142
+
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`.
186
+
187
+ Good examples:
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
+
196
+ 1. Read the injected summary carefully.
197
+ 2. Treat it as the new active state.
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.
202
+
203
+ ## Common mistakes
204
+
205
+ Avoid:
206
+
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