pi-context 1.1.4 → 2.0.0-beta.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 proactively manage checkpoints, timeline inspection, and rewind-based context cleanup.
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_rewind`
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`.
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 includes three core tools:
37
47
 
38
- 1. **🔖 Structure (`context_tag`)**
39
- `git tag` Create named milestones to structure your conversation history.
48
+ 1. **🔖 Structure (`context_checkpoint`)**
49
+ Create named checkpoints to organize conversation history.
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. **📊 Monitor (`context_timeline`)**
52
+ Visualize conversation history, inspect token usage, and see where you are in the task tree.
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. **⏪ 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.
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-beta.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,274 @@
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: 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.
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 adopt an explicit conversation-management working mode.
9
9
 
10
- Your context window is limited. As conversations grow, "pollution" (noise, failed attempts) degrades your reasoning.
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.
11
11
 
12
- **YOU MUST PROACTIVELY MANAGE YOUR HISTORY.**
13
- Do not wait for the user to tell you.
12
+ Use only the current tool names:
13
+ - `context_checkpoint`
14
+ - `context_timeline`
15
+ - `context_rewind`
14
16
 
15
- ## The Core Philosophy: Build, Perceive, Navigate
17
+ ## When to use this skill
16
18
 
17
- ```
18
- Context Window = RAM (Expensive, volatile, limited)
19
- Context Graph = Disk (Cheap, persistent, unlimited)
19
+ Read this skill when the task is likely to outgrow one clean thread and would benefit from explicit history management.
20
20
 
21
- Move finished tasks from RAM to the Graph.
22
- ```
21
+ It should feel like a good fit when the user is effectively asking for one of these patterns:
23
22
 
24
- Manage your context window like a Git repository. You are the maintainer.
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.
35
-
36
- ## Quick Start: The Loop
37
-
38
- Follow this cycle for every major task:
39
-
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.
51
-
52
- ## Tool Reference
53
-
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. |
59
-
60
- ## Critical Rules
61
-
62
- ### Tag Wisely (Build The Skeleton)
63
-
64
- Tags are the "Table of Contents". Name them so you can understand the history at a glance.
65
-
66
- **Naming Formula:** `<task-slug>-<phase>`
67
-
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`)
70
-
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? |
77
-
78
- **Tag Categories:**
79
-
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` |
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
87
29
 
88
- **How to generate:** Ask yourself "What is the task?" → Extract 1-3 keywords (e.g., "fix login timeout" → `login-timeout-fix-start`)
30
+ ### “This will probably take several rounds or several phases.”
31
+ Examples:
32
+ - investigate -> decide -> execute -> validate
33
+ - plan -> implement -> verify
34
+ - collect -> compare -> conclude
35
+ - any task that will keep changing shape as it progresses
89
36
 
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.**
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
93
43
 
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.**
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
97
50
 
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.
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
101
58
 
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.
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
106
65
 
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.
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
113
74
 
114
- ### After Checkout: Execute Next Step
75
+ If one of these patterns clearly applies, take the first structural action now—usually a checkpoint—instead of only describing the intended workflow.
115
76
 
116
- When `context_checkout` completes and injects a summary, you are in a **new context**.
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.
117
78
 
118
- 1. **READ** the injected summary carefully
119
- 2. **EXECUTE** the `Next Step` from the summary - this is your new task.
79
+ ## When to skip it
120
80
 
121
- ## Decision Matrix: When to Act
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
122
88
 
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. |
89
+ ## Operating rhythm
131
90
 
132
- ## The "Context Health" Check
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.
133
97
 
134
- If you cannot answer these, run `context_log`:
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.
135
99
 
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. |
100
+ ## Tool policy
141
101
 
142
- ## Good Checkout Messages
102
+ ### `context_checkpoint`
103
+ This is the default tool in this mode.
143
104
 
144
- The `message` is your lifeline to your past self.
145
- A good message preserves critical context that would otherwise be lost.
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
146
111
 
147
- Structure: `[Key Finding/Status] + [Reason] + [Important Changes] + [Next Step]`
112
+ Use semantic names so the timeline stays readable.
148
113
 
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")
114
+ Recommended patterns:
115
+ - `<task>-start`
116
+ - `<task>-<phase>`
117
+ - `<task>-<attempt>`
118
+ - `<task>-<milestone>`
153
119
 
154
120
  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
- ```
121
+ - `auth-oauth-start`
122
+ - `timeout-analysis-search`
123
+ - `db-migration-plan`
124
+ - `parser-fix-attempt-2`
125
+ - `vendor-review-milestone-1`
126
+
127
+ Avoid generic names like `start`, `checkpoint-1`, `phase-1`, or `retry`.
128
+
129
+ ### `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
+
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
197
+
198
+ If you are unsure which anchor is best, run `context_timeline` first.
199
+
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
205
+
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.
207
+
208
+ If the raw path is low value and unlikely to matter again, a backup is optional.
209
+
210
+ ### Write the message
211
+ A rewind message is the baton pass to future-you. It is not a throwaway comment.
212
+
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
218
+
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]`
223
+
224
+ 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:
246
+ 1. Read the injected summary carefully.
247
+ 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.
250
+
251
+ ## Common mistakes
252
+
253
+ 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
+
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