pi-context 1.1.0 → 1.1.2
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/dist/index.js +370 -0
- package/package.json +1 -1
- package/skills/context-management/SKILL.md +18 -10
- package/src/index.ts +49 -19
package/dist/index.js
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { formatTokens } from "./utils.js";
|
|
3
|
+
const InternalTools = ["context_tag", "context_log", "context_checkout"];
|
|
4
|
+
let CommandCtx = null;
|
|
5
|
+
let CheckoutParams = null;
|
|
6
|
+
const isInternal = (name) => InternalTools.includes(name);
|
|
7
|
+
const resolveTargetId = (sm, target) => {
|
|
8
|
+
if (target.toLowerCase() === "root") {
|
|
9
|
+
const tree = sm.getTree();
|
|
10
|
+
return tree.length > 0 ? tree[0].entry.id : target;
|
|
11
|
+
}
|
|
12
|
+
// If it already looks like an ID, keep it.
|
|
13
|
+
if (/^[0-9a-f]{8,}$/i.test(target))
|
|
14
|
+
return target;
|
|
15
|
+
// Iterative DFS to avoid call stack overflows on deep histories.
|
|
16
|
+
const stack = [...sm.getTree()];
|
|
17
|
+
while (stack.length > 0) {
|
|
18
|
+
const n = stack.pop();
|
|
19
|
+
if (sm.getLabel(n.entry.id) === target)
|
|
20
|
+
return n.entry.id;
|
|
21
|
+
if (n.children?.length)
|
|
22
|
+
stack.push(...n.children);
|
|
23
|
+
}
|
|
24
|
+
// Fallback: let SessionManager deal with invalid targets downstream.
|
|
25
|
+
return target;
|
|
26
|
+
};
|
|
27
|
+
const ContextLogParams = Type.Object({
|
|
28
|
+
limit: Type.Optional(Type.Number({ description: "History limit for visible entries (default: 50)." })),
|
|
29
|
+
verbose: Type.Optional(Type.Boolean({ description: "If true, show ALL messages. If false (default), collapses intermediate AI steps and only shows 'milestones': User messages, Tags, Branch Points, and Summaries." })),
|
|
30
|
+
});
|
|
31
|
+
const ContextCheckoutParams = Type.Object({
|
|
32
|
+
target: Type.String({ description: "Where to jump/squash to. Can be a tag name (e.g., 'task-start'), a commit ID, or 'root'. This is the base for your new branch." }),
|
|
33
|
+
message: Type.String({ description: "The 'Carryover Message' for the new branch. A summary of your *current* progress/lessons that you want to bring with you to the new state. This ensures you don't lose key information when switching contexts. Good summary message: '[Status] + [Reason] + [Important Changes] + [Carryover Data]'" }),
|
|
34
|
+
backupTag: Type.Optional(Type.String({ description: "Optional tag name to apply to the CURRENT state before checking out. Use this to create an automatic backup of the history you are about to leave/squash." })),
|
|
35
|
+
});
|
|
36
|
+
const ContextTagParams = Type.Object({
|
|
37
|
+
name: Type.String({ description: "The tag/milestone name. Use meaningful names." }),
|
|
38
|
+
target: Type.Optional(Type.String({ description: "The commit ID to tag. Defaults to HEAD (current state)." })),
|
|
39
|
+
});
|
|
40
|
+
export default function (pi) {
|
|
41
|
+
pi.registerCommand("acm", {
|
|
42
|
+
description: "Enable agentic context management for the current session",
|
|
43
|
+
handler: async (args, ctx) => {
|
|
44
|
+
CommandCtx = ctx;
|
|
45
|
+
ctx.ui.notify("Agentic Context Management enabled.", "info");
|
|
46
|
+
pi.sendMessage({
|
|
47
|
+
customType: "pi-context",
|
|
48
|
+
content: "use context-management skill",
|
|
49
|
+
display: false,
|
|
50
|
+
}, {
|
|
51
|
+
deliverAs: "followUp"
|
|
52
|
+
});
|
|
53
|
+
if (args) {
|
|
54
|
+
pi.sendUserMessage(args);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
// Helper: Check if a tag name already exists in the tree
|
|
59
|
+
const findTagInTree = (sm, nodes, tagName) => {
|
|
60
|
+
for (const n of nodes) {
|
|
61
|
+
if (sm.getLabel(n.entry.id) === tagName)
|
|
62
|
+
return n.entry.id;
|
|
63
|
+
const r = findTagInTree(sm, n.children, tagName);
|
|
64
|
+
if (r)
|
|
65
|
+
return r;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
};
|
|
69
|
+
pi.registerTool({
|
|
70
|
+
name: "context_tag",
|
|
71
|
+
label: "Context Tag",
|
|
72
|
+
description: "Creates a 'Save Point' (Bookmark) in the history. Use this before trying risky changes or when a feature is stable. 'Untagged progress is risky'.",
|
|
73
|
+
parameters: ContextTagParams,
|
|
74
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
75
|
+
const sm = ctx.sessionManager;
|
|
76
|
+
// Deduplication check: ensure tag name is unique
|
|
77
|
+
const existingTagId = findTagInTree(sm, sm.getTree(), params.name);
|
|
78
|
+
if (existingTagId) {
|
|
79
|
+
return {
|
|
80
|
+
content: [{
|
|
81
|
+
type: "text",
|
|
82
|
+
text: `Error: Tag '${params.name}' already exists at ${existingTagId}. Tag names must be unique. Use a different name or delete the existing tag first.`
|
|
83
|
+
}],
|
|
84
|
+
details: {}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
let id = params.target ? resolveTargetId(sm, params.target) : undefined;
|
|
88
|
+
if (!id) {
|
|
89
|
+
// Auto-resolve: Find the last "interesting" node to tag.
|
|
90
|
+
// We skip ToolResults (which look ugly tagged) and internal-only Assistant messages (which look empty).
|
|
91
|
+
const branch = sm.getBranch();
|
|
92
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
93
|
+
const entry = branch[i];
|
|
94
|
+
// 1. Check ToolResults
|
|
95
|
+
if (entry.type === 'message' && entry.message.role === 'toolResult') {
|
|
96
|
+
const tr = entry.message;
|
|
97
|
+
if (isInternal(tr.toolName))
|
|
98
|
+
continue;
|
|
99
|
+
// Public tool result is a valid target
|
|
100
|
+
id = entry.id;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
// 2. Check Assistant messages for visibility
|
|
104
|
+
if (entry.type === 'message' && entry.message.role === 'assistant') {
|
|
105
|
+
const m = entry.message;
|
|
106
|
+
const hasInternalTool = m.content.some(c => c.type === 'toolCall' && isInternal(c.name));
|
|
107
|
+
if (!hasInternalTool) {
|
|
108
|
+
id = entry.id;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
id = entry.id;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
// Fallback to leaf if search failed
|
|
116
|
+
if (!id)
|
|
117
|
+
id = sm.getLeafId() ?? "";
|
|
118
|
+
}
|
|
119
|
+
pi.setLabel(id, params.name);
|
|
120
|
+
return { content: [{ type: "text", text: `Created tag '${params.name}' at ${id}` }], details: {} };
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
pi.registerTool({
|
|
124
|
+
name: "context_log",
|
|
125
|
+
label: "Context Log",
|
|
126
|
+
description: "Show the entire history structure (status, message, tags, milestones). Analogous to 'git log --graph --oneline --decorate'",
|
|
127
|
+
parameters: ContextLogParams,
|
|
128
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
129
|
+
const sm = ctx.sessionManager;
|
|
130
|
+
const branch = sm.getBranch();
|
|
131
|
+
const currentLeafId = sm.getLeafId();
|
|
132
|
+
const verbose = params.verbose ?? false;
|
|
133
|
+
const limit = params.limit ?? 50;
|
|
134
|
+
const backboneIds = new Set(branch.map((e) => e.id));
|
|
135
|
+
const sequence = [];
|
|
136
|
+
branch.forEach((entry) => {
|
|
137
|
+
sequence.push(entry);
|
|
138
|
+
// Preserve side-summary logic: Show branch summaries/compactions that are off-path
|
|
139
|
+
const children = sm.getChildren(entry.id);
|
|
140
|
+
children.forEach((child) => {
|
|
141
|
+
if ((child.type === "branch_summary" || child.type === "compaction") && !backboneIds.has(child.id)) {
|
|
142
|
+
sequence.push(child);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
const getMsgContent = (entry) => {
|
|
147
|
+
if (entry.type === "branch_summary" || entry.type === "compaction") {
|
|
148
|
+
const e = entry;
|
|
149
|
+
return e.summary || "[No summary provided]";
|
|
150
|
+
}
|
|
151
|
+
if (entry.type === "label") {
|
|
152
|
+
return `tag: ${entry.label}`;
|
|
153
|
+
}
|
|
154
|
+
if (entry.type === "message") {
|
|
155
|
+
const msg = entry.message;
|
|
156
|
+
if (msg.role === "toolResult") {
|
|
157
|
+
const tr = msg;
|
|
158
|
+
if (!verbose && isInternal(tr.toolName))
|
|
159
|
+
return "";
|
|
160
|
+
const extractText = (content) => {
|
|
161
|
+
return content
|
|
162
|
+
.map((p) => (p.type === "text" ? p.text : ""))
|
|
163
|
+
.join(" ")
|
|
164
|
+
.trim();
|
|
165
|
+
};
|
|
166
|
+
let resText = extractText(tr.content);
|
|
167
|
+
const details = tr.details;
|
|
168
|
+
if ((tr.toolName === "read" || tr.toolName === "edit") && details && "path" in details && typeof details.path === "string") {
|
|
169
|
+
resText = `${details.path}: ${resText}`;
|
|
170
|
+
}
|
|
171
|
+
return `(${tr.toolName}) ${resText}`;
|
|
172
|
+
}
|
|
173
|
+
if (msg.role === "bashExecution") {
|
|
174
|
+
return `[Bash] ${msg.command}`;
|
|
175
|
+
}
|
|
176
|
+
if (msg.role === "user" || msg.role === "assistant") {
|
|
177
|
+
let text = "";
|
|
178
|
+
if (typeof msg.content === "string") {
|
|
179
|
+
text = msg.content;
|
|
180
|
+
}
|
|
181
|
+
else if (Array.isArray(msg.content)) {
|
|
182
|
+
text = msg.content
|
|
183
|
+
.map((p) => {
|
|
184
|
+
if (typeof p === "object" && p !== null && "text" in p)
|
|
185
|
+
return p.text;
|
|
186
|
+
return "";
|
|
187
|
+
})
|
|
188
|
+
.join(" ")
|
|
189
|
+
.trim();
|
|
190
|
+
}
|
|
191
|
+
let toolCallsText = "";
|
|
192
|
+
if (msg.role === "assistant") {
|
|
193
|
+
const toolCalls = msg.content.filter((c) => c.type === "toolCall");
|
|
194
|
+
toolCallsText = toolCalls
|
|
195
|
+
.filter((tc) => verbose || !isInternal(tc.name))
|
|
196
|
+
.map((tc) => `call: ${tc.name}(${JSON.stringify(tc.arguments)})`)
|
|
197
|
+
.join("; ");
|
|
198
|
+
}
|
|
199
|
+
return [text, toolCallsText].filter(Boolean).join(" ");
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return "";
|
|
203
|
+
};
|
|
204
|
+
const isInteresting = (entry) => {
|
|
205
|
+
// 1. HEAD and Root
|
|
206
|
+
if (entry.id === currentLeafId)
|
|
207
|
+
return true;
|
|
208
|
+
if (branch.length > 0 && entry.id === branch[0].id)
|
|
209
|
+
return true;
|
|
210
|
+
// 2. Explicit Tags (Labels) - Only show the TAGGED node, not the label node itself
|
|
211
|
+
if (sm.getLabel(entry.id))
|
|
212
|
+
return true;
|
|
213
|
+
if (entry.type === 'label')
|
|
214
|
+
return false; // Hide label nodes, they are redundant
|
|
215
|
+
// 3. Structural Milestones (Summaries)
|
|
216
|
+
if (entry.type === 'branch_summary' || entry.type === 'compaction')
|
|
217
|
+
return true;
|
|
218
|
+
// 4. Branch Points (Forks)
|
|
219
|
+
if (sm.getChildren(entry.id).length > 1)
|
|
220
|
+
return true;
|
|
221
|
+
// 5. Natural Milestones (User Messages) - This is the key auto-tagging mechanism
|
|
222
|
+
if (entry.type === 'message' && entry.message.role === 'user')
|
|
223
|
+
return true;
|
|
224
|
+
return false;
|
|
225
|
+
};
|
|
226
|
+
const visibleSequenceIds = new Set();
|
|
227
|
+
sequence.forEach(e => {
|
|
228
|
+
if (verbose || isInteresting(e)) {
|
|
229
|
+
visibleSequenceIds.add(e.id);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
let visibleEntries = sequence.filter(e => visibleSequenceIds.has(e.id));
|
|
233
|
+
if (visibleEntries.length > limit) {
|
|
234
|
+
const allowedIds = new Set(visibleEntries.slice(-limit).map(e => e.id));
|
|
235
|
+
visibleSequenceIds.clear();
|
|
236
|
+
allowedIds.forEach(id => visibleSequenceIds.add(id));
|
|
237
|
+
}
|
|
238
|
+
const lines = [];
|
|
239
|
+
let hiddenCount = 0;
|
|
240
|
+
sequence.forEach((entry) => {
|
|
241
|
+
if (!visibleSequenceIds.has(entry.id)) {
|
|
242
|
+
hiddenCount++;
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (hiddenCount > 0) {
|
|
246
|
+
lines.push(` : ... (${hiddenCount} hidden messages) ...`);
|
|
247
|
+
hiddenCount = 0;
|
|
248
|
+
}
|
|
249
|
+
const isHead = entry.id === currentLeafId;
|
|
250
|
+
const label = sm.getLabel(entry.id);
|
|
251
|
+
const content = getMsgContent(entry).replace(/\s+/g, " ");
|
|
252
|
+
let role = entry.type.toUpperCase();
|
|
253
|
+
if (entry.type === "message") {
|
|
254
|
+
const m = entry.message;
|
|
255
|
+
role =
|
|
256
|
+
m.role === "assistant"
|
|
257
|
+
? "AI"
|
|
258
|
+
: m.role === "user"
|
|
259
|
+
? "USER"
|
|
260
|
+
: m.role === "bashExecution"
|
|
261
|
+
? "BASH"
|
|
262
|
+
: "TOOL";
|
|
263
|
+
}
|
|
264
|
+
else if (entry.type === "branch_summary" || entry.type === "compaction") {
|
|
265
|
+
role = "SUMMARY";
|
|
266
|
+
}
|
|
267
|
+
// hide custom messages
|
|
268
|
+
if (role === "CUSTOM_MESSAGE") {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const id = entry.id;
|
|
272
|
+
const isRoot = branch.length > 0 && entry.id === branch[0].id;
|
|
273
|
+
const meta = [isRoot ? "ROOT" : null, isHead ? "HEAD" : null, label ? `tag: ${label}` : null].filter(Boolean).join(", ");
|
|
274
|
+
const body = content.length > 100 ? content.slice(0, 100) + "..." : content;
|
|
275
|
+
const marker = isHead ? "*" : (role === "USER" ? "•" : "|");
|
|
276
|
+
lines.push(`${marker} ${id}${meta ? ` (${meta})` : ""} [${role}] ${body}`);
|
|
277
|
+
});
|
|
278
|
+
if (hiddenCount > 0) {
|
|
279
|
+
lines.push(` : ... (${hiddenCount} hidden messages) ...`);
|
|
280
|
+
}
|
|
281
|
+
// --- Context Dashboard (HUD) ---
|
|
282
|
+
const usage = await ctx.getContextUsage();
|
|
283
|
+
let usageStr = "Unknown";
|
|
284
|
+
if (usage) {
|
|
285
|
+
usageStr = `${usage.percent.toFixed(1)}% (${formatTokens(usage.tokens)}/${formatTokens(usage.contextWindow)})`;
|
|
286
|
+
}
|
|
287
|
+
// Find the distance to the nearest tag
|
|
288
|
+
let stepsSinceTag = 0;
|
|
289
|
+
let nearestTagName = "None";
|
|
290
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
291
|
+
const id = branch[i].id;
|
|
292
|
+
const label = sm.getLabel(id);
|
|
293
|
+
if (label) {
|
|
294
|
+
nearestTagName = label;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
stepsSinceTag++;
|
|
298
|
+
}
|
|
299
|
+
const hud = [
|
|
300
|
+
`[Context Dashboard]`,
|
|
301
|
+
`• Context Usage: ${usageStr}`,
|
|
302
|
+
`• Segment Size: ${stepsSinceTag} steps since last tag '${nearestTagName}'`,
|
|
303
|
+
`---------------------------------------------------`
|
|
304
|
+
].join("\n");
|
|
305
|
+
return { content: [{ type: "text", text: hud + "\n" + (lines.join("\n") || "(Root Path Only)") }], details: {} };
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
pi.registerTool({
|
|
309
|
+
name: "context_checkout",
|
|
310
|
+
label: "Context Checkout",
|
|
311
|
+
description: "Navigate to ANY point in the conversation history. This checkout only resets *conversation history*, NOT disk files. ALWAYS provide a detailed 'message' to bridge context.",
|
|
312
|
+
parameters: ContextCheckoutParams,
|
|
313
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
314
|
+
if (!CommandCtx) {
|
|
315
|
+
ctx.ui.setEditorText(`/acm ${ctx.ui.getEditorText() || "continue"}`);
|
|
316
|
+
return {
|
|
317
|
+
content: [{
|
|
318
|
+
type: "text",
|
|
319
|
+
text: "Agentic context management is not enabled. Ask the user to run `/acm` in the pi to enable it, then retry."
|
|
320
|
+
}],
|
|
321
|
+
details: {}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
const sm = ctx.sessionManager;
|
|
325
|
+
const tid = resolveTargetId(sm, params.target);
|
|
326
|
+
const currentLeaf = sm.getLeafId();
|
|
327
|
+
if (currentLeaf === tid) {
|
|
328
|
+
return { content: [{ type: "text", text: `Already at target ${tid}` }], details: {} };
|
|
329
|
+
}
|
|
330
|
+
if (params.backupTag && currentLeaf) {
|
|
331
|
+
pi.setLabel(currentLeaf, params.backupTag);
|
|
332
|
+
}
|
|
333
|
+
const currentLabel = currentLeaf ? sm.getLabel(currentLeaf) : undefined;
|
|
334
|
+
const origin = currentLabel ? `tag: ${currentLabel}` : (currentLeaf || "unknown");
|
|
335
|
+
const enrichedMessage = `(summary from ${origin})\n${params.message}`;
|
|
336
|
+
const nid = await sm.branchWithSummary(tid, enrichedMessage);
|
|
337
|
+
CheckoutParams = params;
|
|
338
|
+
CheckoutParams.nid = nid;
|
|
339
|
+
CheckoutParams.tid = tid;
|
|
340
|
+
CheckoutParams.enrichedMessage = enrichedMessage;
|
|
341
|
+
return { content: [{ type: "text", text: "checkout start" }], details: {} };
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
pi.on("turn_end", async (event, ctx) => {
|
|
345
|
+
if (!CheckoutParams) {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
ctx.abort();
|
|
349
|
+
});
|
|
350
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
351
|
+
if (!CheckoutParams) {
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if (!CommandCtx) {
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
await CommandCtx.navigateTree(CheckoutParams.nid, {
|
|
358
|
+
summarize: false,
|
|
359
|
+
});
|
|
360
|
+
ctx.ui.notify(`Checked out ${CheckoutParams.target}${CheckoutParams.target === CheckoutParams.tid ? "" : `(${CheckoutParams.tid})`}\nBackup tag created: ${CheckoutParams.backupTag || "none"}\nmessage: ${CheckoutParams.enrichedMessage}`, "info");
|
|
361
|
+
CheckoutParams = null;
|
|
362
|
+
pi.sendMessage({
|
|
363
|
+
customType: "pi-context",
|
|
364
|
+
content: "context_checkout complete. A summary of your previous branch was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",
|
|
365
|
+
display: false,
|
|
366
|
+
}, {
|
|
367
|
+
triggerTurn: true,
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
}
|
package/package.json
CHANGED
|
@@ -111,6 +111,13 @@ If you fail 3 times:
|
|
|
111
111
|
3. Summarize the failure in the checkout message ("Tried X, failed because Y").
|
|
112
112
|
4. Try a new approach from the clean state.
|
|
113
113
|
|
|
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.
|
|
120
|
+
|
|
114
121
|
## Decision Matrix: When to Act
|
|
115
122
|
|
|
116
123
|
| Situation | Action | Reason |
|
|
@@ -132,24 +139,24 @@ If you cannot answer these, run `context_log`:
|
|
|
132
139
|
| **Is this history useful?** | If "No" -> **SQUASH IT.** |
|
|
133
140
|
| **Am I in a loop?** | Repeated entries in the graph. |
|
|
134
141
|
|
|
135
|
-
|
|
136
142
|
## Good Checkout Messages
|
|
137
143
|
|
|
138
144
|
The `message` is your lifeline to your past self.
|
|
139
145
|
A good message preserves critical context that would otherwise be lost.
|
|
140
146
|
|
|
141
|
-
Structure: `[Key Finding/Status] + [Reason] + [Important Changes]`
|
|
147
|
+
Structure: `[Key Finding/Status] + [Reason] + [Important Changes] + [Next Step]`
|
|
142
148
|
|
|
143
149
|
* **Key Finding/Status**: What did you discover or complete? Include specific numbers, errors, or outcomes.
|
|
144
150
|
* **Reason**: Why are you branching/moving? (e.g., "Task complete", "Approach failed", "Need raw logs")
|
|
145
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")
|
|
146
153
|
|
|
147
154
|
Examples:
|
|
148
155
|
|
|
149
|
-
* *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`."
|
|
150
|
-
* *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`."
|
|
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."
|
|
151
158
|
* *Bad*: "Switching context." (Too vague - you will forget why)
|
|
152
|
-
* *Bad*: "Done." (What is done? What
|
|
159
|
+
* *Bad*: "Done." (What is done? What should you do next?)
|
|
153
160
|
|
|
154
161
|
## Anti-Patterns
|
|
155
162
|
|
|
@@ -162,6 +169,7 @@ Examples:
|
|
|
162
169
|
| **Blind Checkout** (Guessing IDs) | **Look** (`context_log`) first to get valid IDs. |
|
|
163
170
|
| **Vague Summaries** ("Done", "Fixed") | **Detailed Summaries** ("Found bug in line 40. Fixed with patch X.") |
|
|
164
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") |
|
|
165
173
|
|
|
166
174
|
## Recipes (Copy-Paste)
|
|
167
175
|
|
|
@@ -180,7 +188,7 @@ context_tag({ name: "timeout-analysis-start" });
|
|
|
180
188
|
// 2. Squash IMMEDIATELY. Do not wait for user.
|
|
181
189
|
context_checkout({
|
|
182
190
|
target: "timeout-analysis-start",
|
|
183
|
-
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).",
|
|
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.",
|
|
184
192
|
backupTag: "timeout-analysis-raw-history" // Safety backup
|
|
185
193
|
});
|
|
186
194
|
context_tag({ name: "timeout-analysis-done" });
|
|
@@ -197,7 +205,7 @@ context_tag({ name: "timeout-analysis-done" });
|
|
|
197
205
|
// Squash to Summary (Optimistic Cleanup)
|
|
198
206
|
context_checkout({
|
|
199
207
|
target: "oauth-impl-start", // Squash range: Start -> Now
|
|
200
|
-
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`.
|
|
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.",
|
|
201
209
|
backupTag: "oauth-impl-raw-history"
|
|
202
210
|
});
|
|
203
211
|
context_tag({ name: "oauth-impl-candidate" });
|
|
@@ -213,7 +221,7 @@ context_tag({ name: "oauth-impl-candidate" });
|
|
|
213
221
|
// Jump back to the raw history
|
|
214
222
|
context_checkout({
|
|
215
223
|
target: "oauth-impl-raw-history",
|
|
216
|
-
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."
|
|
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."
|
|
217
225
|
});
|
|
218
226
|
context_tag({ name: "oauth-review-start" });
|
|
219
227
|
```
|
|
@@ -228,7 +236,7 @@ context_tag({ name: "oauth-review-start" });
|
|
|
228
236
|
// Method A (weak references) failed, trying Method B (object pooling)
|
|
229
237
|
context_checkout({
|
|
230
238
|
target: "memory-leak-fix-start",
|
|
231
|
-
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)."
|
|
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."
|
|
232
240
|
});
|
|
233
241
|
context_tag({ name: "memory-leak-pool-approach-start" });
|
|
234
242
|
```
|
|
@@ -243,7 +251,7 @@ You tried to fix a bug but broke everything.
|
|
|
243
251
|
// Attempted mutex-based fix, but introduced deadlock
|
|
244
252
|
context_checkout({
|
|
245
253
|
target: "race-condition-fix-start",
|
|
246
|
-
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).",
|
|
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.",
|
|
247
255
|
backupTag: "race-condition-mutex-fail" // Save the failure for reference
|
|
248
256
|
});
|
|
249
257
|
context_tag({ name: "race-condition-lockfree-start" });
|
package/src/index.ts
CHANGED
|
@@ -30,17 +30,20 @@ const resolveTargetId = (sm: SessionManager, target: string): string => {
|
|
|
30
30
|
const tree = sm.getTree();
|
|
31
31
|
return tree.length > 0 ? tree[0].entry.id : target;
|
|
32
32
|
}
|
|
33
|
+
|
|
34
|
+
// If it already looks like an ID, keep it.
|
|
33
35
|
if (/^[0-9a-f]{8,}$/i.test(target)) return target;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
|
|
37
|
+
// Iterative DFS to avoid call stack overflows on deep histories.
|
|
38
|
+
const stack: SessionTreeNode[] = [...(sm.getTree() as unknown as SessionTreeNode[])];
|
|
39
|
+
while (stack.length > 0) {
|
|
40
|
+
const n = stack.pop()!;
|
|
41
|
+
if (sm.getLabel(n.entry.id) === target) return n.entry.id;
|
|
42
|
+
if (n.children?.length) stack.push(...n.children);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Fallback: let SessionManager deal with invalid targets downstream.
|
|
46
|
+
return target;
|
|
44
47
|
};
|
|
45
48
|
|
|
46
49
|
const ContextLogParams = Type.Object({
|
|
@@ -64,18 +67,30 @@ export default function (pi: ExtensionAPI) {
|
|
|
64
67
|
description: "Enable agentic context management for the current session",
|
|
65
68
|
handler: async (args, ctx) => {
|
|
66
69
|
CommandCtx = ctx;
|
|
67
|
-
pi.setActiveTools(pi.getActiveTools().concat(InternalTools));
|
|
68
70
|
ctx.ui.notify("Agentic Context Management enabled.", "info");
|
|
69
71
|
pi.sendMessage({
|
|
70
72
|
customType: "pi-context",
|
|
71
|
-
content: "
|
|
73
|
+
content: "use context-management skill",
|
|
72
74
|
display: false,
|
|
73
75
|
}, {
|
|
74
76
|
deliverAs: "followUp"
|
|
75
77
|
});
|
|
78
|
+
if (args) {
|
|
79
|
+
pi.sendUserMessage(args)
|
|
80
|
+
}
|
|
76
81
|
}
|
|
77
82
|
});
|
|
78
83
|
|
|
84
|
+
// Helper: Check if a tag name already exists in the tree
|
|
85
|
+
const findTagInTree = (sm: SessionManager, nodes: SessionTreeNode[], tagName: string): string | null => {
|
|
86
|
+
for (const n of nodes) {
|
|
87
|
+
if (sm.getLabel(n.entry.id) === tagName) return n.entry.id;
|
|
88
|
+
const r = findTagInTree(sm, n.children, tagName);
|
|
89
|
+
if (r) return r;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
};
|
|
93
|
+
|
|
79
94
|
pi.registerTool({
|
|
80
95
|
name: "context_tag",
|
|
81
96
|
label: "Context Tag",
|
|
@@ -83,6 +98,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
83
98
|
parameters: ContextTagParams,
|
|
84
99
|
async execute(_id, params: Static<typeof ContextTagParams>, _signal, _onUpdate, ctx) {
|
|
85
100
|
const sm = ctx.sessionManager as SessionManager;
|
|
101
|
+
|
|
102
|
+
// Deduplication check: ensure tag name is unique
|
|
103
|
+
const existingTagId = findTagInTree(sm, sm.getTree(), params.name);
|
|
104
|
+
if (existingTagId) {
|
|
105
|
+
return {
|
|
106
|
+
content: [{
|
|
107
|
+
type: "text",
|
|
108
|
+
text: `Error: Tag '${params.name}' already exists at ${existingTagId}. Tag names must be unique. Use a different name or delete the existing tag first.`
|
|
109
|
+
}],
|
|
110
|
+
details: {}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
86
114
|
let id = params.target ? resolveTargetId(sm, params.target) : undefined;
|
|
87
115
|
|
|
88
116
|
if (!id) {
|
|
@@ -343,7 +371,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
343
371
|
parameters: ContextCheckoutParams,
|
|
344
372
|
async execute(_id, params: Static<typeof ContextCheckoutParams>, _signal, _onUpdate, ctx) {
|
|
345
373
|
if (!CommandCtx) {
|
|
346
|
-
|
|
374
|
+
ctx.ui.setEditorText(`/acm ${ctx.ui.getEditorText() || "continue"}`)
|
|
375
|
+
return {
|
|
376
|
+
content: [{
|
|
377
|
+
type: "text",
|
|
378
|
+
text: "Agentic context management is not enabled. Ask the user to run `/acm` in the pi to enable it, then retry."
|
|
379
|
+
}],
|
|
380
|
+
details: {}
|
|
381
|
+
};
|
|
347
382
|
}
|
|
348
383
|
const sm = ctx.sessionManager as SessionManager;
|
|
349
384
|
|
|
@@ -395,15 +430,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
395
430
|
|
|
396
431
|
pi.sendMessage({
|
|
397
432
|
customType: "pi-context",
|
|
398
|
-
content: "context_checkout
|
|
433
|
+
content: "context_checkout complete. A summary of your previous branch was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",
|
|
399
434
|
display: false,
|
|
400
435
|
}, {
|
|
401
436
|
triggerTurn: true,
|
|
402
437
|
});
|
|
403
438
|
});
|
|
404
|
-
|
|
405
|
-
pi.on("session_start", () => {
|
|
406
|
-
// hide tools by default
|
|
407
|
-
pi.setActiveTools(pi.getActiveTools().filter(n => !InternalTools.includes(n)));
|
|
408
|
-
});
|
|
409
439
|
}
|