repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

chore: remove unused workflow extensions

75c85eea551bcaa7c70d16f6f69abed929bf876b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (56)

CHANGELOG.md

Modified
32 32 - Remove synchronous Pulse Git processes, use the current Node process version, and fold vcs-status stash detection into its existing Git status process
33 33 - Remove the Overkill and Q extensions
34 34 - Remove the Goal, Diff Review, and Devil extensions
35 +- Remove the Cwd, Split Fork, LLM Iterate, and Goldfish extensions
35 36 - Remove the unneeded `builtin-tools` extension and `/builtin-tools` command
36 37 - Update npm dependency lockfile to latest resolved package versions
37 38 - Replace dprint and markdownlint-cli2 with rumdl for Markdown, Taplo for TOML, and yq frontmatter validation; add structural Markdown checks for links, footnotes, fences, TOCs, anchors, encoding, and comments

README.md

Modified
73 73 | `context-size` | Context-window usage telemetry for Pi. | [README](extensions/context-size/README.md) |
74 74 | `continuity` | Continue Pi tasks after context compaction. | [README](extensions/continuity/README.md) |
75 75 | `cost` | Token and spend telemetry for Pi. | [README](extensions/cost/README.md) |
76 -| `cwd` | Switch Pi cwd without leaving the session. | [README](extensions/cwd/README.md) |
77 76 | `fast` | OpenAI Codex priority service tier for Pi. | [README](extensions/fast/README.md) |
78 77 | `footer` | Shared stable footer renderer for Pi. | [README](extensions/footer/README.md) |
79 78 | `git-safe` | Hardened git clone tool for Pi. | [README](extensions/git-safe/README.md) |
80 79 | `intellij` | Connect Pi to IntelliJ MCP on demand. | [README](extensions/intellij/README.md) |
81 80 | `iq` | Personal model work-ability scoring from real Pi sessions. | [README](extensions/iq/README.md) |
82 81 | `leaks` | Provider-bound secret redaction for Pi. | [README](extensions/leaks/README.md) |
83 -| `llmiterate` | Manual editor-save bridge from comment markers to background Pi edits. | [README](extensions/llmiterate/README.md) |
84 82 | `masks` | Named model and thinking combinations for Pi. | [README](extensions/masks/README.md) |
85 83 | `model-info` | Model and thinking telemetry for Pi. | [README](extensions/model-info/README.md) |
86 84 | `neko` | Tiny animated editor cat for Pi. Pointless. Correct. | [README](extensions/neko/README.md) |
92 90 | `runtime` | Runtime detection telemetry for Pi footer/status. | [README](extensions/runtime/README.md) |
93 91 | `rtk` | RTK bash command rewrite hook for Pi. | [README](extensions/rtk/README.md) |
94 92 | `session-rename` | Automatic short session names for Pi. | [README](extensions/session-rename/README.md) |
95 -| `split-fork` | Fork Pi into a Ghostty split. | [README](extensions/split-fork/README.md) |
96 93 | `the-system` | Project governance through one `/system` command. | [README](extensions/the-system/README.md) |
97 94 | `os-notifier` | Native-first OS notifications for interactive Pi completion. | [README](extensions/os-notifier/README.md) |
98 95 | `terse` | Terse response protocol injector for Pi. | [README](extensions/terse/README.md) |

extensions/cwd/CHANGELOG.md

Deleted
deleted file mode 100644
1 -# Changelog
3 -## 0.0.3
5 -- Switch test runner from bun test to vitest across workspace
6 -- Isolate extension harness environment in tests
7 -- Fix harness tests for import.meta.dirname, Vitest deps, and Chai matchers
8 -- Tighten Biome lint rules and apply fixes
9 -- Format cwd docs; update extension guides and demos
11 -## 0.0.2
13 -- Tag 0.0.2:
14 - no commits touched `extensions/cwd` after `v0.0.1`
15 -- Keep `/cwd [path]`:
16 - same cwd display, validation, idle wait, session switch
17 -- Keep `README.md`, `CHANGELOG.md`, and harness load test unchanged
19 -## 0.1.0 - 2026-05-21
21 -- a40a427 prepare extensions for npm release
22 -- 133cb7d chore(pi):
23 - migrate extensions to earendil packages
24 -- 68c7911 feat(cwd):
25 - add cwd switching command

extensions/cwd/README.md

Deleted
deleted file mode 100644
1 -# cwd
3 -Switch Pi cwd without leaving the session.
5 -## Install / load
7 -This extension is loaded through the root pi-ext package.
8 -See [root README](../../README.md).
10 -## Commands / tools / settings
12 -Commands:
14 -- `/cwd [path]` — switch session cwd, or show current cwd when no path is given.
16 -Tools:
17 -none.
19 -Hooks:
20 -none.
22 -Settings:
23 -none.
25 -## Behavior
27 -- Resolves relative paths from current Pi cwd.
28 -- Expands `~` and `~/...`.
29 -- Rejects missing paths and non-directories.
30 -- No-op when target cwd equals current cwd.
31 -- Waits for idle before switching.
32 -- Forks current session into target cwd when a source session file exists.
33 -- Uses target cwd session directory config when available.
34 -- Writes a target session file from in-memory entries when no source session
35 - file exists.
36 -- Completion suggestions for empty prefix: `.`, `..`, `~`.

extensions/cwd/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { afterEach, describe, expect, it } from "vitest";
2 -import { createTestSession, type TestSession } from "../../../test/harness";
3 -import cwdExtension from "../index";
5 -describe("cwd pi-test-harness", () => {
6 - let t: TestSession | undefined;
8 - afterEach(() => {
9 - t?.dispose();
10 - t = undefined;
11 - });
13 - it("loads in real Pi extension runtime", async () => {
14 - t = await createTestSession({ extensionFactories: [cwdExtension] });
16 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
17 - });
18 -});

extensions/cwd/index.ts

Deleted
deleted file mode 100644
1 -import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2 -import { homedir } from "node:os";
3 -import { dirname, resolve } from "node:path";
4 -import type {
5 - ExtensionAPI,
6 - ExtensionCommandContext,
7 - SessionEntry,
8 - SessionHeader,
9 -} from "@earendil-works/pi-coding-agent";
10 -import {
11 - CURRENT_SESSION_VERSION,
12 - getAgentDir,
13 - SessionManager,
14 - SettingsManager,
15 -} from "@earendil-works/pi-coding-agent";
17 -function expandTilde(path: string): string {
18 - if (path === "~") return homedir();
19 - if (path.startsWith("~/")) return resolve(homedir(), path.slice(2));
20 - return path;
23 -function resolveTarget(raw: string, cwd: string): string {
24 - const input = raw.trim() || ".";
25 - const expanded = expandTilde(input);
26 - return resolve(cwd, expanded);
29 -function assertDirectory(path: string): string | undefined {
30 - if (!existsSync(path)) return `cwd not found: ${path}`;
31 - try {
32 - const stats = statSync(path);
33 - if (!stats.isDirectory()) return `cwd is not a directory: ${path}`;
34 - return undefined;
35 - } catch (error) {
36 - return `cannot stat cwd: ${error instanceof Error ? error.message : String(error)}`;
37 - }
40 -function sessionFileExists(ctx: ExtensionCommandContext): string | undefined {
41 - const file = ctx.sessionManager.getSessionFile();
42 - return file && existsSync(file) ? file : undefined;
45 -function configuredSessionDir(targetCwd: string): string | undefined {
46 - try {
47 - return SettingsManager.create(targetCwd, getAgentDir()).getSessionDir();
48 - } catch {
49 - return undefined;
50 - }
53 -function createSessionFileFromMemory(
54 - ctx: ExtensionCommandContext,
55 - targetCwd: string,
56 - sessionDir?: string,
57 -): string {
58 - const manager = SessionManager.create(targetCwd, sessionDir);
59 - const sessionFile = manager.getSessionFile();
60 - if (!sessionFile) throw new Error("Failed to allocate target session file");
62 - const timestamp = new Date().toISOString();
63 - const header: SessionHeader = {
64 - type: "session",
65 - version: CURRENT_SESSION_VERSION,
66 - id: manager.getSessionId(),
67 - timestamp,
68 - cwd: targetCwd,
69 - parentSession: ctx.sessionManager.getSessionFile(),
70 - };
71 - const entries = ctx.sessionManager.getEntries() as SessionEntry[];
72 - mkdirSync(dirname(sessionFile), { recursive: true });
73 - writeFileSync(
74 - sessionFile,
75 - `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}\n`,
76 - );
77 - return sessionFile;
80 -function createTargetSession(
81 - ctx: ExtensionCommandContext,
82 - targetCwd: string,
83 -): string {
84 - const sessionDir = configuredSessionDir(targetCwd);
85 - const sourceFile = sessionFileExists(ctx);
86 - if (sourceFile) {
87 - const forked = SessionManager.forkFrom(sourceFile, targetCwd, sessionDir);
88 - const forkedFile = forked.getSessionFile();
89 - if (!forkedFile) throw new Error("Failed to fork session into target cwd");
90 - return forkedFile;
91 - }
92 - return createSessionFileFromMemory(ctx, targetCwd, sessionDir);
95 -export default function (pi: ExtensionAPI) {
96 - pi.registerCommand("cwd", {
97 - description:
98 - "Switch Pi cwd by moving current session into target directory",
99 - getArgumentCompletions: (prefix) => {
100 - if (prefix.trim().length > 0) return null;
101 - return [
102 - { value: ".", label: ".", description: "current cwd" },
103 - { value: "..", label: "..", description: "parent cwd" },
104 - { value: "~", label: "~", description: "home cwd" },
105 - ];
106 - },
107 - handler: async (args, ctx) => {
108 - if (!args.trim()) {
109 - ctx.ui.notify(`cwd: ${ctx.cwd}`, "info");
110 - return;
111 - }
113 - const targetCwd = resolveTarget(args, ctx.cwd);
114 - const error = assertDirectory(targetCwd);
115 - if (error) {
116 - ctx.ui.notify(error, "error");
117 - return;
118 - }
120 - if (targetCwd === ctx.cwd) {
121 - ctx.ui.notify(`cwd already: ${targetCwd}`, "info");
122 - return;
123 - }
125 - await ctx.waitForIdle();
126 - const targetSessionFile = createTargetSession(ctx, targetCwd);
127 - await ctx.switchSession(targetSessionFile, {
128 - withSession: async (ctx) => {
129 - ctx.ui.notify(`cwd → ${ctx.cwd}`, "info");
130 - },
131 - });
132 - },
133 - });

extensions/cwd/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-cwd",
3 - "type": "module",
4 - "main": "index.ts",
5 - "peerDependencies": {
6 - "@earendil-works/pi-coding-agent": "*"
7 - },
8 - "license": "MIT",
9 - "description": "Switch Pi cwd without leaving the session.",
10 - "keywords": [
11 - "pi",
12 - "pi-extension"
13 - ],
14 - "devDependencies": {
15 - "@marcfargas/pi-test-harness": "^0.6.1",
16 - "vitest": "^4.1.9"
17 - },
18 - "private": true
19 -}

extensions/goldfish/README.md

Deleted
deleted file mode 100644
1 -# goldfish
3 -Task-gated Pi tool-use experiment.
5 -When no task is active, normal tools stay visible but are hard-blocked.
6 -The agent must create a task with a done command before using them.
8 -The widget shows current state above the editor.

extensions/goldfish/__tests__/goldfish.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, test } from "vitest";
2 -import goldfishExtension, { __test } from "../index";
4 -const {
5 - applyEvent,
6 - buildGuidance,
7 - createState,
8 - currentTask,
9 - executeTaskAction,
10 - gateToolCall,
11 - replayGoldfish,
12 - taskResultLines,
13 - taskResultTone,
14 - toolNamesForMode,
15 - widgetLines,
16 - widgetTone,
17 -} = __test;
19 -describe("goldfish state", () => {
20 - test("empty state is idle", () => {
21 - expect(currentTask(createState())).toBeUndefined();
22 - });
24 - test("create/done/abandon transitions are replayable", () => {
25 - const state = createState();
26 - applyEvent(state, {
27 - op: "create",
28 - id: 1,
29 - title: "Fix tests",
30 - doneCommand: "npm test",
31 - doneTimeoutSeconds: 60,
32 - createdAt: 1,
33 - });
34 - expect(currentTask(state)?.title).toBe("Fix tests");
35 - applyEvent(state, { op: "done", id: 1, result: "passed", updatedAt: 2 });
36 - expect(currentTask(state)).toBeUndefined();
38 - const replayed = replayGoldfish([
39 - {
40 - type: "custom",
41 - customType: "goldfish-state",
42 - data: {
43 - op: "create",
44 - id: 2,
45 - title: "Next",
46 - doneCommand: "true",
47 - doneTimeoutSeconds: 60,
48 - createdAt: 3,
49 - },
50 - },
51 - {
52 - type: "custom",
53 - customType: "goldfish-state",
54 - data: { op: "abandon", id: 2, reason: "bad check", updatedAt: 4 },
55 - },
56 - ]);
57 - expect(currentTask(replayed)).toBeUndefined();
58 - expect(replayed.tasks.get(2)?.status).toBe("abandoned");
59 - });
60 -});
62 -describe("goldfish tool", () => {
63 - test("create creates active task and renders collapsed/expanded professionally", async () => {
64 - const state = createState();
65 - const result = await executeTaskAction(state, {
66 - action: "create",
67 - title: "Fix goldfish",
68 - doneCommand: "mise run test -- extensions/goldfish",
69 - doneTimeoutSeconds: 99,
70 - });
72 - expect(
73 - result.content[0]?.type === "text" ? result.content[0].text : "",
74 - ).toBe("task active. Do work, then call task.check before final answer.");
75 - expect(currentTask(state)?.title).toBe("Fix goldfish");
76 - expect(taskResultLines(result, false)).toEqual([
77 - "◌ task active · #1 Fix goldfish · check: mise run test -- extensions/goldfish · timeout 99s · expand for context",
78 - ]);
79 - expect(taskResultTone(result)).toBe("accent");
80 - expect(taskResultLines(result, true)).toContain("status: active");
81 - expect(taskResultLines(result, true)).toContain(
82 - "done: mise run test -- extensions/goldfish",
83 - );
84 - });
86 - test("check command exit contract closes, continues, or abandons", async () => {
87 - const done = createState();
88 - await executeTaskAction(done, {
89 - action: "create",
90 - title: "done",
91 - doneCommand: "x",
92 - });
93 - await executeTaskAction(done, { action: "check" }, async () => ({
94 - exitCode: 0,
95 - stdout: "ok",
96 - stderr: "",
97 - }));
98 - expect(done.tasks.get(1)?.status).toBe("done");
99 - expect(
100 - taskResultTone(
101 - await executeTaskAction(createState(), { action: "check" }),
102 - ),
103 - ).toBe("error");
105 - const active = createState();
106 - await executeTaskAction(active, {
107 - action: "create",
108 - title: "not yet",
109 - doneCommand: "x",
110 - });
111 - await executeTaskAction(active, { action: "check" }, async () => ({
112 - exitCode: 1,
113 - stdout: "no",
114 - stderr: "",
115 - }));
116 - expect(currentTask(active)?.status).toBe("active");
118 - const abandoned = createState();
119 - await executeTaskAction(abandoned, {
120 - action: "create",
121 - title: "bad",
122 - doneCommand: "x",
123 - });
124 - await executeTaskAction(abandoned, { action: "check" }, async () => ({
125 - exitCode: 2,
126 - stdout: "",
127 - stderr: "boom",
128 - }));
129 - expect(abandoned.tasks.get(1)?.status).toBe("abandoned");
130 - expect(
131 - taskResultTone(
132 - await executeTaskAction(abandoned, {
133 - action: "abandon",
134 - reason: "already abandoned",
135 - }),
136 - ),
137 - ).toBe("error");
138 - });
140 - test("timeout abandons", async () => {
141 - const state = createState();
142 - await executeTaskAction(state, {
143 - action: "create",
144 - title: "slow",
145 - doneCommand: "x",
146 - });
147 - await executeTaskAction(state, { action: "check" }, async () => ({
148 - exitCode: null,
149 - timedOut: true,
150 - stdout: "",
151 - stderr: "",
152 - }));
153 - expect(state.tasks.get(1)?.status).toBe("abandoned");
154 - });
155 -});
157 -describe("goldfish gates and guidance", () => {
158 - test("disabled mode restores normal tools and hides goldfish", () => {
159 - expect(toolNamesForMode(["read", "bash"], createState(), false)).toEqual([
160 - "read",
161 - "bash",
162 - ]);
163 - });
165 - test("enabled tool visibility keeps normal tools visible for same-turn unlock", () => {
166 - expect(toolNamesForMode(["read", "bash"], createState(), true)).toEqual([
167 - "read",
168 - "bash",
169 - "task",
170 - ]);
171 - const state = createState();
172 - applyEvent(state, {
173 - op: "create",
174 - id: 1,
175 - title: "x",
176 - doneCommand: "true",
177 - doneTimeoutSeconds: 60,
178 - createdAt: 1,
179 - });
180 - expect(toolNamesForMode(["read", "bash"], state, true)).toEqual([
181 - "read",
182 - "bash",
183 - "task",
184 - ]);
185 - });
187 - test("hard gate blocks non-goldfish tools while idle", () => {
188 - expect(gateToolCall(createState(), "read")).toEqual({
189 - block: true,
190 - reason: "goldfish: call task with action=create before other tools",
191 - });
192 - expect(gateToolCall(createState(), "task")).toBeUndefined();
193 - const state = createState();
194 - applyEvent(state, {
195 - op: "create",
196 - id: 1,
197 - title: "x",
198 - doneCommand: "true",
199 - doneTimeoutSeconds: 60,
200 - createdAt: 1,
201 - });
202 - expect(gateToolCall(state, "read")).toBeUndefined();
203 - });
205 - test("guidance is short and stateful", () => {
206 - expect(buildGuidance(createState())).toContain(
207 - "Call `task` with action=create before using normal tools",
208 - );
209 - const state = createState();
210 - applyEvent(state, {
211 - op: "create",
212 - id: 1,
213 - title: "x",
214 - doneCommand: "true",
215 - doneTimeoutSeconds: 60,
216 - createdAt: 1,
217 - });
218 - expect(buildGuidance(state)).toContain("Active task #1: x");
219 - expect(buildGuidance(state).split("\n").length).toBeLessThanOrEqual(12);
220 - });
221 -});
223 -describe("goldfish widget", () => {
224 - test("widget shows persistent compact and expanded state", () => {
225 - expect(widgetLines(createState(), false, 120)).toEqual([
226 - "󰈸 blocked · create task to unlock tools",
227 - ]);
228 - expect(widgetTone(createState())).toBe("warning");
229 - const state = createState();
230 - applyEvent(state, {
231 - op: "create",
232 - id: 1,
233 - title: "Fix widget",
234 - doneCommand: "mise run test",
235 - doneTimeoutSeconds: 60,
236 - createdAt: 1,
237 - });
238 - expect(widgetLines(state, false, 120)[0]).toContain(
239 - "active #1 · Fix widget",
240 - );
241 - expect(widgetTone(state)).toBe("accent");
242 - expect(widgetLines(state, true, 120)).toContain(
243 - " done mise run test",
244 - );
245 - });
246 -});
248 -describe("goldfish extension registration", () => {
249 - test("registers goldfish controls", () => {
250 - const tools: string[] = [];
251 - const events: string[] = [];
252 - const shortcuts: string[] = [];
253 - const commands: string[] = [];
254 - const flags: string[] = [];
255 - goldfishExtension({
256 - registerTool(tool: { name: string }) {
257 - tools.push(tool.name);
258 - },
259 - on(event: string) {
260 - events.push(event);
261 - },
262 - registerShortcut(key: string) {
263 - shortcuts.push(key);
264 - },
265 - registerCommand(name: string) {
266 - commands.push(name);
267 - },
268 - registerFlag(name: string) {
269 - flags.push(name);
270 - },
271 - getFlag() {
272 - return false;
273 - },
274 - } as any);
275 - expect(tools).toEqual(["task"]);
276 - expect(commands).toEqual(["goldfish"]);
277 - expect(flags).toEqual(["goldfish"]);
278 - expect(events).toEqual(
279 - expect.arrayContaining([
280 - "session_start",
281 - "tool_call",
282 - "before_agent_start",
283 - ]),
284 - );
285 - expect(shortcuts).toEqual(["alt+t"]);
286 - });
288 - test("--goldfish starts enabled", () => {
289 - const handlers = new Map<string, Function>();
290 - const activeTools: string[][] = [];
291 - goldfishExtension({
292 - registerTool() {},
293 - registerCommand() {},
294 - registerShortcut() {},
295 - registerFlag() {},
296 - getFlag(name: string) {
297 - return name === "goldfish" ? "true" : undefined;
298 - },
299 - on(event: string, handler: Function) {
300 - handlers.set(event, handler);
301 - },
302 - getActiveTools() {
303 - return ["read", "bash", "task"];
304 - },
305 - setActiveTools(names: string[]) {
306 - activeTools.push(names);
307 - },
308 - } as any);
310 - handlers.get("session_start")?.(
311 - {},
312 - {
313 - hasUI: false,
314 - sessionManager: { getBranch: () => [] },
315 - },
316 - );
318 - expect(activeTools).toEqual([]);
319 - });
321 - test("OFF session start has no visible Pi changes except hiding goldfish tool", () => {
322 - const handlers = new Map<string, Function>();
323 - const activeTools: string[][] = [];
324 - const widgets: unknown[] = [];
325 - goldfishExtension({
326 - registerTool() {},
327 - registerCommand() {},
328 - registerShortcut() {},
329 - registerFlag() {},
330 - getFlag() {
331 - return false;
332 - },
333 - on(event: string, handler: Function) {
334 - handlers.set(event, handler);
335 - },
336 - getActiveTools() {
337 - return ["read", "bash", "task"];
338 - },
339 - setActiveTools(names: string[]) {
340 - activeTools.push(names);
341 - },
342 - } as any);
344 - handlers.get("session_start")?.(
345 - {},
346 - {
347 - hasUI: true,
348 - ui: { setWidget: (...args: unknown[]) => widgets.push(args) },
349 - sessionManager: { getBranch: () => [] },
350 - },
351 - );
353 - expect(activeTools).toEqual([["read", "bash"]]);
354 - expect(widgets).toEqual([]);
355 - expect(
356 - handlers.get("tool_call")?.({ toolName: "read" }, {}),
357 - ).toBeUndefined();
358 - expect(
359 - handlers.get("before_agent_start")?.({ systemPrompt: "base" }, {}),
360 - ).toBeUndefined();
361 - });
362 -});

extensions/goldfish/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { afterEach, describe, expect, it } from "vitest";
2 -import { createTestSession, type TestSession } from "../../../test/harness";
3 -import goldfishExtension from "../index";
5 -describe("goldfish pi-test-harness", () => {
6 - let t: TestSession | undefined;
8 - afterEach(() => {
9 - t?.dispose();
10 - t = undefined;
11 - });
13 - it("loads in real Pi extension runtime", async () => {
14 - t = await createTestSession({ extensionFactories: [goldfishExtension] });
16 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
17 - });
18 -});

extensions/goldfish/index.ts

Deleted
deleted file mode 100644
1 -import { StringEnum } from "@earendil-works/pi-ai";
2 -import type {
3 - AgentToolResult,
4 - ExtensionAPI,
5 - ExtensionContext,
6 -} from "@earendil-works/pi-coding-agent";
7 -import { keyHint } from "@earendil-works/pi-coding-agent";
8 -import { Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
9 -import { Type } from "typebox";
11 -const TOOL = "task";
12 -const ENTRY_TYPE = "goldfish-state";
13 -const WIDGET_KEY = "goldfish";
14 -const ICON = "󰈸";
15 -const DEFAULT_TIMEOUT_SECONDS = 60;
16 -const MAX_TIMEOUT_SECONDS = 300;
17 -const WIDGET_DEFAULT_WIDTH = 96;
19 -type TaskStatus = "active" | "done" | "abandoned";
21 -type GoldfishTask = {
22 - id: number;
23 - title: string;
24 - doneCommand: string;
25 - doneTimeoutSeconds: number;
26 - status: TaskStatus;
27 - createdAt: number;
28 - updatedAt: number;
29 - toolCalls: number;
30 - checks: number;
31 - lastResult?: string;
32 -};
34 -type GoldfishEvent =
35 - | {
36 - op: "create";
37 - id: number;
38 - title: string;
39 - doneCommand: string;
40 - doneTimeoutSeconds: number;
41 - createdAt: number;
42 - }
43 - | { op: "done"; id: number; result: string; updatedAt: number }
44 - | { op: "continue"; id: number; result: string; updatedAt: number }
45 - | { op: "abandon"; id: number; reason: string; updatedAt: number }
46 - | { op: "tool_call"; id: number; toolName: string; updatedAt: number };
48 -type GoldfishState = {
49 - tasks: Map<number, GoldfishTask>;
50 - nextId: number;
51 -};
53 -type SessionEntryLike = {
54 - type?: unknown;
55 - customType?: unknown;
56 - data?: unknown;
57 -};
59 -type TaskParams = {
60 - action: "create" | "check" | "abandon";
61 - title?: string;
62 - doneCommand?: string;
63 - doneTimeoutSeconds?: number;
64 - reason?: string;
65 -};
67 -type CheckResult = {
68 - exitCode: number | null;
69 - stdout: string;
70 - stderr: string;
71 - timedOut?: boolean;
72 -};
74 -type TaskDetails = {
75 - kind: "goldfish";
76 - action: TaskParams["action"];
77 - status: "active" | "done" | "abandoned" | "error";
78 - task?: GoldfishTask;
79 - message: string;
80 - check?: CheckResult;
81 -};
83 -type AppendEvent = (event: GoldfishEvent) => void;
84 -type RunCheck = (
85 - command: string,
86 - timeoutSeconds: number,
87 - signal?: AbortSignal,
88 -) => Promise<CheckResult>;
90 -function createState(): GoldfishState {
91 - return { tasks: new Map(), nextId: 1 };
94 -function cleanText(value: unknown): string {
95 - return String(value ?? "")
96 - .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, " ")
97 - .replace(/\s+/g, " ")
98 - .trim();
101 -function boundedText(value: unknown, max = 180): string {
102 - const text = cleanText(value);
103 - return text.length > max ? `${text.slice(0, Math.max(0, max - 1))}…` : text;
106 -function timeoutSeconds(value: unknown): number {
107 - if (typeof value !== "number" || !Number.isFinite(value))
108 - return DEFAULT_TIMEOUT_SECONDS;
109 - return Math.max(1, Math.min(MAX_TIMEOUT_SECONDS, Math.trunc(value)));
112 -function parseEvent(data: unknown): GoldfishEvent | undefined {
113 - if (!data || typeof data !== "object") return undefined;
114 - const event = data as Record<string, unknown>;
115 - if (
116 - event.op === "create" &&
117 - typeof event.id === "number" &&
118 - typeof event.title === "string" &&
119 - typeof event.doneCommand === "string" &&
120 - typeof event.doneTimeoutSeconds === "number" &&
121 - typeof event.createdAt === "number"
122 - ) {
123 - return {
124 - op: "create",
125 - id: event.id,
126 - title: event.title,
127 - doneCommand: event.doneCommand,
128 - doneTimeoutSeconds: event.doneTimeoutSeconds,
129 - createdAt: event.createdAt,
130 - };
131 - }
132 - if (
133 - (event.op === "done" || event.op === "continue") &&
134 - typeof event.id === "number" &&
135 - typeof event.result === "string" &&
136 - typeof event.updatedAt === "number"
137 - ) {
138 - return {
139 - op: event.op,
140 - id: event.id,
141 - result: event.result,
142 - updatedAt: event.updatedAt,
143 - };
144 - }
145 - if (
146 - event.op === "abandon" &&
147 - typeof event.id === "number" &&
148 - typeof event.reason === "string" &&
149 - typeof event.updatedAt === "number"
150 - ) {
151 - return {
152 - op: "abandon",
153 - id: event.id,
154 - reason: event.reason,
155 - updatedAt: event.updatedAt,
156 - };
157 - }
158 - if (
159 - event.op === "tool_call" &&
160 - typeof event.id === "number" &&
161 - typeof event.toolName === "string" &&
162 - typeof event.updatedAt === "number"
163 - ) {
164 - return {
165 - op: "tool_call",
166 - id: event.id,
167 - toolName: event.toolName,
168 - updatedAt: event.updatedAt,
169 - };
170 - }
171 - return undefined;
174 -function applyEvent(state: GoldfishState, event: GoldfishEvent): void {
175 - if (event.op === "create") {
176 - state.tasks.set(event.id, {
177 - id: event.id,
178 - title: cleanText(event.title),
179 - doneCommand: cleanText(event.doneCommand),
180 - doneTimeoutSeconds: timeoutSeconds(event.doneTimeoutSeconds),
181 - status: "active",
182 - createdAt: event.createdAt,
183 - updatedAt: event.createdAt,
184 - toolCalls: 0,
185 - checks: 0,
186 - });
187 - state.nextId = Math.max(state.nextId, event.id + 1);
188 - return;
189 - }
190 - const task = state.tasks.get(event.id);
191 - if (!task) return;
192 - if (event.op === "done") {
193 - task.status = "done";
194 - task.updatedAt = event.updatedAt;
195 - task.lastResult = boundedText(event.result, 500);
196 - return;
197 - }
198 - if (event.op === "continue") {
199 - task.status = "active";
200 - task.checks += 1;
201 - task.updatedAt = event.updatedAt;
202 - task.lastResult = boundedText(event.result, 500);
203 - return;
204 - }
205 - if (event.op === "abandon") {
206 - task.status = "abandoned";
207 - task.updatedAt = event.updatedAt;
208 - task.lastResult = boundedText(event.reason, 500);
209 - return;
210 - }
211 - task.toolCalls += 1;
212 - task.updatedAt = event.updatedAt;
215 -function replayGoldfish(entries: SessionEntryLike[]): GoldfishState {
216 - const state = createState();
217 - for (const entry of entries) {
218 - if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
219 - const event = parseEvent(entry.data);
220 - if (event) applyEvent(state, event);
221 - }
222 - return state;
225 -function currentTask(state: GoldfishState): GoldfishTask | undefined {
226 - return [...state.tasks.values()]
227 - .filter((task) => task.status === "active")
228 - .sort((a, b) => b.id - a.id)[0];
231 -function result(
232 - message: string,
233 - details: TaskDetails,
234 - _isError = false,
235 -): AgentToolResult<TaskDetails> {
236 - return { content: [{ type: "text", text: message }], details };
239 -function append(
240 - state: GoldfishState,
241 - event: GoldfishEvent,
242 - appendEvent?: AppendEvent,
243 -): void {
244 - applyEvent(state, event);
245 - appendEvent?.(event);
248 -function checkShell(): { command: string; argsPrefix: string[] } {
249 - if (process.platform === "win32")
250 - return { command: "cmd", argsPrefix: ["/d", "/s", "/c"] };
251 - return { command: "sh", argsPrefix: ["-c"] };
254 -async function ctxRunCheck(
255 - pi: ExtensionAPI,
256 - ctx: ExtensionContext,
257 - command: string,
258 - timeout: number,
259 - signal?: AbortSignal,
260 -): Promise<CheckResult> {
261 - const shell = checkShell();
262 - const exec = await pi.exec(shell.command, [...shell.argsPrefix, command], {
263 - cwd: ctx.cwd,
264 - signal,
265 - timeout: timeout * 1000,
266 - });
267 - return {
268 - exitCode: exec.killed ? null : exec.code,
269 - stdout: exec.stdout,
270 - stderr: exec.stderr,
271 - timedOut: exec.killed,
272 - };
275 -function checkMessage(check: CheckResult): string {
276 - const output = boundedText(check.stdout || check.stderr || "", 500);
277 - if (check.timedOut) return "timeout";
278 - if (check.exitCode === 0) return output || "done command passed";
279 - if (check.exitCode === 1) return output || "done command says not done";
280 - return (
281 - output || `done command failed with exit ${check.exitCode ?? "signal"}`
282 - );
285 -async function executeTaskAction(
286 - state: GoldfishState,
287 - params: TaskParams,
288 - runCheck?: RunCheck,
289 - appendEvent?: AppendEvent,
290 - signal?: AbortSignal,
291 -): Promise<AgentToolResult<TaskDetails>> {
292 - if (params.action === "create") {
293 - if (currentTask(state))
294 - return result(
295 - "active task already exists; use goldfish.check or goldfish.abandon",
296 - {
297 - kind: "goldfish",
298 - action: "create",
299 - status: "error",
300 - message: "active task already exists",
301 - },
302 - true,
303 - );
304 - const title = cleanText(params.title);
305 - const doneCommand = cleanText(params.doneCommand);
306 - if (!title || !doneCommand)
307 - return result(
308 - "goldfish.create requires title and doneCommand",
309 - {
310 - kind: "goldfish",
311 - action: "create",
312 - status: "error",
313 - message: "missing title or doneCommand",
314 - },
315 - true,
316 - );
317 - const event: GoldfishEvent = {
318 - op: "create",
319 - id: state.nextId,
320 - title,
321 - doneCommand,
322 - doneTimeoutSeconds: timeoutSeconds(params.doneTimeoutSeconds),
323 - createdAt: Date.now(),
324 - };
325 - append(state, event, appendEvent);
326 - const task = currentTask(state);
327 - return result(
328 - "task active. Do work, then call task.check before final answer.",
329 - {
330 - kind: "goldfish",
331 - action: "create",
332 - status: "active",
333 - message: "task active; check required before final answer",
334 - task,
335 - },
336 - );
337 - }
339 - const task = currentTask(state);
340 - if (!task)
341 - return result(
342 - "no active task; use goldfish.create",
343 - {
344 - kind: "goldfish",
345 - action: params.action,
346 - status: "error",
347 - message: "no active task",
348 - },
349 - true,
350 - );
352 - if (params.action === "abandon") {
353 - const reason = cleanText(params.reason) || "abandoned";
354 - append(
355 - state,
356 - { op: "abandon", id: task.id, reason, updatedAt: Date.now() },
357 - appendEvent,
358 - );
359 - return result("task abandoned", {
360 - kind: "goldfish",
361 - action: "abandon",
362 - status: "abandoned",
363 - message: reason,
364 - task: state.tasks.get(task.id),
365 - });
366 - }
368 - const fallbackRunCheck: RunCheck = () =>
369 - Promise.resolve({ exitCode: 2, stdout: "", stderr: "no check runner" });
370 - const check = await (runCheck ?? fallbackRunCheck)(
371 - task.doneCommand,
372 - task.doneTimeoutSeconds,
373 - signal,
374 - );
375 - const message = checkMessage(check);
376 - if (check.exitCode === 0 && !check.timedOut) {
377 - append(
378 - state,
379 - { op: "done", id: task.id, result: message, updatedAt: Date.now() },
380 - appendEvent,
381 - );
382 - return result("task done", {
383 - kind: "goldfish",
384 - action: "check",
385 - status: "done",
386 - message,
387 - check,
388 - task: state.tasks.get(task.id),
389 - });
390 - }
391 - if (check.exitCode === 1 && !check.timedOut) {
392 - append(
393 - state,
394 - { op: "continue", id: task.id, result: message, updatedAt: Date.now() },
395 - appendEvent,
396 - );
397 - return result("task not done", {
398 - kind: "goldfish",
399 - action: "check",
400 - status: "active",
401 - message,
402 - check,
403 - task: state.tasks.get(task.id),
404 - });
405 - }
406 - append(
407 - state,
408 - { op: "abandon", id: task.id, reason: message, updatedAt: Date.now() },
409 - appendEvent,
410 - );
411 - return result("task abandoned", {
412 - kind: "goldfish",
413 - action: "check",
414 - status: "abandoned",
415 - message,
416 - check,
417 - task: state.tasks.get(task.id),
418 - });
421 -function taskResultLines(
422 - result: AgentToolResult<TaskDetails>,
423 - expanded: boolean,
424 -): string[] {
425 - const details = result.details;
426 - if (!details)
427 - return [
428 - boundedText(
429 - result.content[0]?.type === "text" ? result.content[0].text : "task",
430 - ),
431 - ];
432 - const task = details.task;
433 - if (!task) return [`✗ ${details.message}`];
434 - const glyph =
435 - details.status === "active"
436 - ? "◌"
437 - : details.status === "done"
438 - ? "✓"
439 - : details.status === "abandoned"
440 - ? "↯"
441 - : "✗";
442 - const first = `${glyph} task ${details.status} · #${task.id} ${task.title} · check: ${task.doneCommand} · timeout ${task.doneTimeoutSeconds}s`;
443 - if (!expanded) return [`${first} · expand for context`];
444 - return [
445 - first,
446 - `status: ${task.status}`,
447 - `id: ${task.id}`,
448 - `title: ${task.title}`,
449 - `done: ${task.doneCommand}`,
450 - `timeout: ${task.doneTimeoutSeconds}s`,
451 - `checks: ${task.checks}`,
452 - `tool calls: ${task.toolCalls}`,
453 - ...(task.lastResult ? [`last: ${task.lastResult}`] : []),
454 - ];
457 -function taskResultTone(
458 - result: AgentToolResult<TaskDetails>,
459 -): "accent" | "success" | "warning" | "error" {
460 - const status = result.details?.status;
461 - if (status === "error") return "error";
462 - if (status === "done") return "success";
463 - if (status === "abandoned") return "warning";
464 - return "accent";
467 -function renderTaskResult(
468 - result: AgentToolResult<TaskDetails>,
469 - options: { expanded?: boolean; isPartial?: boolean },
470 - theme: any,
471 -) {
472 - if (options.isPartial)
473 - return new Text(theme.fg("warning", "󰈸 checking task…"), 0, 0);
474 - const lines = taskResultLines(result, !!options.expanded);
475 - let text = lines.join("\n");
476 - if (!options.expanded && lines.length === 1) {
477 - text = text.replace(
478 - "expand for context",
479 - keyHint("app.tools.expand", "to expand"),
480 - );
481 - }
482 - return new Text(theme.fg(taskResultTone(result), text), 0, 0);
485 -function renderTaskCall(args: TaskParams, theme: any) {
486 - let text = theme.fg("toolTitle", theme.bold("󰈸 task "));
487 - text += theme.fg("accent", args.action ?? "?");
488 - const title = boundedText(args.title, 80);
489 - if (title) text += theme.fg("dim", ` — ${title}`);
490 - return new Text(text, 0, 0);
493 -function toolNamesForMode(
494 - baseline: string[],
495 - _state: GoldfishState,
496 - enabled: boolean,
497 -): string[] {
498 - const cleanBaseline = baseline.filter((name) => name !== TOOL);
499 - if (!enabled) return cleanBaseline;
500 - return Array.from(new Set([...cleanBaseline, TOOL]));
503 -function toolNamesForState(baseline: string[], state: GoldfishState): string[] {
504 - return toolNamesForMode(baseline, state, true);
507 -function gateToolCall(state: GoldfishState, toolName: string) {
508 - if (toolName === TOOL || currentTask(state)) return undefined;
509 - return {
510 - block: true,
511 - reason: "goldfish: call task with action=create before other tools",
512 - };
515 -function buildGuidance(state: GoldfishState): string {
516 - const task = currentTask(state);
517 - if (!task)
518 - return [
519 - "Goldfish task gate is IDLE.",
520 - "Call `task` with action=create before using normal tools.",
521 - "Normal tools are visible but blocked until task creation succeeds.",
522 - "Create a small task with a concrete doneCommand, then continue.",
523 - ].join("\n");
524 - return [
525 - "Goldfish task gate is ACTIVE.",
526 - `Active task #${task.id}: ${task.title}`,
527 - `Done command: ${task.doneCommand}`,
528 - "Use normal tools only for this task.",
529 - "Before any final answer, call `task` with action=check.",
530 - ].join("\n");
533 -function clip(text: string, width: number): string {
534 - return truncateToWidth(text, Math.max(0, width), "…");
537 -function wrapWords(text: string, width: number): string[] {
538 - if (width <= 0) return [""];
539 - const words = cleanText(text).split(" ").filter(Boolean);
540 - if (words.length === 0) return [""];
541 - const lines: string[] = [];
542 - let line = "";
543 - for (const word of words) {
544 - const candidate = line ? `${line} ${word}` : word;
545 - if (visibleWidth(candidate) <= width) line = candidate;
546 - else {
547 - if (line) lines.push(line);
548 - line = word;
549 - }
550 - }
551 - if (line) lines.push(line);
552 - return lines;
555 -function row(label: string, value: string, width: number): string[] {
556 - const prefix = ` ${label.padEnd(8)} `;
557 - const textWidth = Math.max(1, width - visibleWidth(prefix));
558 - return wrapWords(value, textWidth).map(
559 - (part, index) => `${index === 0 ? prefix : "".padEnd(13)}${part}`,
560 - );
563 -function flagEnabled(value: unknown): boolean {
564 - return value === true || value === "true" || value === "1" || value === "yes";
567 -function widgetTone(state: GoldfishState): "accent" | "warning" {
568 - return currentTask(state) ? "accent" : "warning";
571 -function widgetLines(
572 - state: GoldfishState,
573 - expanded: boolean,
574 - width = WIDGET_DEFAULT_WIDTH,
575 -): string[] {
576 - const task = currentTask(state);
577 - if (!task)
578 - return [clip(`${ICON} blocked · create task to unlock tools`, width)];
579 - if (!expanded)
580 - return [
581 - clip(
582 - `${ICON} active #${task.id} · ${task.title} · check: ${task.doneCommand}`,
583 - width,
584 - ),
585 - ];
586 - return [
587 - clip(`${ICON} active #${task.id}`, width),
588 - ...row("task", task.title, width),
589 - ...row("done", task.doneCommand, width),
590 - ...row("timeout", `${task.doneTimeoutSeconds}s`, width),
591 - ...row("checks", String(task.checks), width),
592 - ...row("tools", String(task.toolCalls), width),
593 - ...(task.lastResult ? row("last", task.lastResult, width) : []),
594 - ];
597 -function sameNames(left: string[], right: string[]): boolean {
598 - return (
599 - left.length === right.length &&
600 - left.every((name, index) => name === right[index])
601 - );
604 -function refreshTools(
605 - pi: ExtensionAPI,
606 - baseline: string[],
607 - state: GoldfishState,
608 - enabled: boolean,
609 -): void {
610 - const next = toolNamesForMode(baseline, state, enabled);
611 - if (!sameNames(pi.getActiveTools(), next)) pi.setActiveTools(next);
614 -function refreshWidget(
615 - ctx: ExtensionContext,
616 - state: GoldfishState,
617 - expanded: boolean,
618 - enabled: boolean,
619 - widgetVisible: boolean,
620 -): boolean {
621 - if (!ctx.hasUI) return widgetVisible;
622 - if (!enabled) {
623 - if (widgetVisible) ctx.ui.setWidget(WIDGET_KEY, undefined);
624 - return false;
625 - }
626 - ctx.ui.setWidget(
627 - WIDGET_KEY,
628 - (_tui, theme) => ({
629 - invalidate() {},
630 - render(width: number): string[] {
631 - const task = currentTask(state);
632 - return widgetLines(state, expanded || !task, width).map((line) =>
633 - theme.fg(widgetTone(state), line),
634 - );
635 - },
636 - }),
637 - { placement: "aboveEditor" },
638 - );
639 - return true;
642 -export const __test = {
643 - applyEvent,
644 - buildGuidance,
645 - createState,
646 - currentTask,
647 - executeTaskAction,
648 - gateToolCall,
649 - parseEvent,
650 - replayGoldfish,
651 - taskResultLines,
652 - taskResultTone,
653 - toolNamesForMode,
654 - toolNamesForState,
655 - flagEnabled,
656 - widgetLines,
657 - widgetTone,
658 -};
660 -export default function goldfishExtension(pi: ExtensionAPI): void {
661 - pi.registerFlag?.("goldfish", {
662 - description: "Enable experimental Goldfish task gate on startup.",
663 - type: "boolean",
664 - default: false,
665 - });
667 - const state = createState();
668 - let baselineTools: string[] = [];
669 - let expanded = false;
670 - let enabled = false;
671 - let widgetVisible = false;
673 - const appendEvent = (event: GoldfishEvent) =>
674 - pi.appendEntry(ENTRY_TYPE, event);
676 - pi.registerTool({
677 - name: TOOL,
678 - label: "Task",
679 - description:
680 - "Goldfish task gate. If no other tools are visible, call this tool with action=create; never refuse because tools are unavailable.",
681 - promptSnippet:
682 - "task(action, title?, doneCommand?, doneTimeoutSeconds?, reason?) — when Goldfish is idle, call task action=create first",
683 - promptGuidelines: [
684 - "If Goldfish says idle or only task is visible, call task with action=create; do not answer that tools are unavailable.",
685 - "Create small tasks with a concrete doneCommand; do not create one immortal task.",
686 - "After normal tools, call task with action=check. Exit 0 closes, exit 1 continues, exit 2+ abandons.",
687 - ],
688 - parameters: Type.Object({
689 - action: StringEnum(["create", "check", "abandon"] as const, {
690 - description:
691 - "create starts a task, check runs doneCommand, abandon closes failed task",
692 - }),
693 - title: Type.Optional(
694 - Type.String({
695 - description: "Small concrete task title for action=create",
696 - }),
697 - ),
698 - doneCommand: Type.Optional(
699 - Type.String({
700 - description: "Command: exit 0 done, 1 not done, 2+ abandon",
701 - }),
702 - ),
703 - doneTimeoutSeconds: Type.Optional(
704 - Type.Number({ description: "Check timeout seconds, max 300" }),
705 - ),
706 - reason: Type.Optional(
707 - Type.String({ description: "Reason for action=abandon" }),
708 - ),
709 - }),
710 - renderCall: renderTaskCall,
711 - renderResult: renderTaskResult,
712 - async execute(_toolCallId, params, signal, _onUpdate, ctx) {
713 - const out = await executeTaskAction(
714 - state,
715 - params as TaskParams,
716 - (command, timeout, checkSignal) =>
717 - ctxRunCheck(pi, ctx, command, timeout, checkSignal),
718 - appendEvent,
719 - signal,
720 - );
721 - refreshTools(pi, baselineTools, state, enabled);
722 - widgetVisible = refreshWidget(
723 - ctx,
724 - state,
725 - expanded,
726 - enabled,
727 - widgetVisible,
728 - );
729 - return out;
730 - },
731 - });
733 - pi.registerCommand("goldfish", {
734 - description:
735 - "Toggle experimental Goldfish task gate. Usage: /goldfish [on|off|status]",
736 - handler: async (args, ctx) => {
737 - const command = args.trim().toLowerCase();
738 - if (command === "status") {
739 - ctx.ui.notify(`Goldfish ${enabled ? "on" : "off"}`, "info");
740 - return;
741 - }
742 - enabled = command === "on" ? true : command === "off" ? false : !enabled;
743 - refreshTools(pi, baselineTools, state, enabled);
744 - widgetVisible = refreshWidget(
745 - ctx,
746 - state,
747 - expanded,
748 - enabled,
749 - widgetVisible,
750 - );
751 - ctx.ui.notify(`Goldfish ${enabled ? "on" : "off"}`, "info");
752 - },
753 - });
755 - pi.registerShortcut("alt+t", {
756 - description: "Toggle goldfish task widget compact/expanded",
757 - handler: async (ctx) => {
758 - expanded = !expanded;
759 - widgetVisible = refreshWidget(
760 - ctx,
761 - state,
762 - expanded,
763 - enabled,
764 - widgetVisible,
765 - );
766 - ctx.ui.notify(
767 - `Goldfish widget ${expanded ? "expanded" : "compact"}`,
768 - "info",
769 - );
770 - },
771 - });
773 - pi.on("session_start", (_event, ctx) => {
774 - enabled = enabled || flagEnabled(pi.getFlag?.("goldfish"));
775 - const replayed = replayGoldfish(
776 - ctx.sessionManager.getBranch() as SessionEntryLike[],
777 - );
778 - state.tasks = replayed.tasks;
779 - state.nextId = replayed.nextId;
780 - baselineTools = pi.getActiveTools().filter((name) => name !== TOOL);
781 - refreshTools(pi, baselineTools, state, enabled);
782 - widgetVisible = refreshWidget(ctx, state, expanded, enabled, widgetVisible);
783 - });
785 - pi.on("tool_call", (event, ctx) => {
786 - if (!enabled) return undefined;
787 - const decision = gateToolCall(state, event.toolName);
788 - if (!decision) {
789 - const task = currentTask(state);
790 - if (task && event.toolName !== TOOL) {
791 - const goldfishEvent: GoldfishEvent = {
792 - op: "tool_call",
793 - id: task.id,
794 - toolName: event.toolName,
795 - updatedAt: Date.now(),
796 - };
797 - append(state, goldfishEvent, appendEvent);
798 - widgetVisible = refreshWidget(
799 - ctx,
800 - state,
801 - expanded,
802 - enabled,
803 - widgetVisible,
804 - );
805 - }
806 - return undefined;
807 - }
808 - widgetVisible = refreshWidget(ctx, state, true, enabled, widgetVisible);
809 - return decision;
810 - });
812 - pi.on("before_agent_start", (event) => {
813 - if (!enabled) return undefined;
814 - const guidance = buildGuidance(state);
815 - return { systemPrompt: `${event.systemPrompt}\n\n${guidance}` };
816 - });

extensions/goldfish/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-goldfish",
3 - "type": "module",
4 - "main": "index.ts",
5 - "devDependencies": {
6 - "@marcfargas/pi-test-harness": "^0.6.1",
7 - "vitest": "^4.1.8"
8 - },
9 - "peerDependencies": {
10 - "@earendil-works/pi-ai": "*",
11 - "@earendil-works/pi-coding-agent": "*",
12 - "@earendil-works/pi-tui": "*",
13 - "typebox": "*"
14 - },
15 - "license": "MIT",
16 - "description": "Task-gated Pi tool use experiment.",
17 - "keywords": [
18 - "pi",
19 - "pi-extension"
20 - ],
21 - "private": true
22 -}

extensions/llmiterate/CHANGELOG.md

Deleted
deleted file mode 100644
1 -# Changelog
3 -## 0.0.3
5 -- Fix win32 release readiness
6 -- Resolve pi-ext conflict stack; retire superpowers
7 -- Inline .gitignore matcher; remove ignore dependency
8 -- Replace Bun with npm and Vitest in test layout
10 -## 0.0.2
12 -- Ship no llmiterate file changes since v0.0.1.
13 -- Keep `/llmiterate` command behavior unchanged.
14 -- Keep marker parsing, watcher, state, and RPC worker behavior unchanged.
16 -## Unreleased
18 -- Make llmiterate manual:
19 - `/llmiterate` toggles cwd-scoped watcher on/off.
20 -- Remove upward project-root guessing; state/lock scope is current cwd.
21 -- Replace panel UX with status, one-shot status, and `explain <path>`.
22 -- Add command completions for public subcommands only.
23 -- Make marker comment prefixes extension-scoped.
24 -- Expand default cache/home excludes.
26 -## 0.1.0 - 2026-05-21
28 -- a40a427 prepare extensions for npm release
29 -- 133cb7d chore(pi):
30 - migrate extensions to earendil packages
31 -- 5ca1296 Rework Pi agent extensions

extensions/llmiterate/README.md

Deleted
deleted file mode 100644
1 -<!-- !llmiterate -->
3 -# llmiterate
5 -Manual editor-save bridge from comment markers to background Pi edits.
7 -## Behavior
9 -llmiterate does not autostart.
10 -`/llmiterate` or `/llmiterate on` starts it for the exact real cwd.
11 -It loads global Pi settings, then `<scope>/.pi/settings.json`; there is no
12 -upward project-root search.
14 -Start sequence:
16 -1. resolve cwd
17 -2. load config and state
18 -3. acquire singleton lock for the scope hash
19 -4. start watcher
20 -5. run initial scan
21 -6. queue matching markers
23 -## Marker syntax
25 -One marker only:
27 -```text
28 -llmiterate:
29 -```
31 -Marker must appear after a known comment prefix.
32 -Raw markers never run.
34 -```java
35 -void main(final String[] a) {
36 - // llmiterate: implement argument validation
37 - if (a.length == 0) {
38 - // llmiterate: print usage and exit non-zero
39 - }
41 -```
43 -```py
44 -def parse(src):
45 - # llmiterate: implement parser fast path
46 -```
48 -```sql
49 --- llmiterate: add index for lookup query
50 -```
52 -Rules:
54 -- raw `llmiterate:` is ignored
55 -- consecutive marker lines are grouped
56 -- empty marker lines are ignored
57 -- `!llmiterate` in a comment disables the whole file
59 -## Comment prefixes
61 -Prefixes are extension-scoped.
62 -Built-ins include:
64 -| file type | prefix |
65 -| ----------------------------------------------------------------------------------------- | ----------------- |
66 -| .c/.cc/.cpp/.cs/.cts/.go/.h/.hpp/.java/.js/.jsx/.kt/.kts/.mts/.php/.scala/.swift/.ts/.tsx | // /// /* /** |
67 -| .rs | // /// //! /* /** |
68 -| .css | /* /** |
69 -| .scss/.less | // /* /** |
70 -| .py/.sh/.bash/.zsh/.fish/.rb/.pl/.pm/.r/.toml/.yaml/.yml/.dockerfile/.ex/.exs | # |
71 -| .md/.mdx/.html/.htm/.xml | <!-- --> |
72 -| .sql/.lua/.hs | -- |
73 -| .lisp/.el/.clj/.scm | ; ;; ;;; |
74 -| .tex | % %% |
75 -| .erl | % |
76 -| .f/.f90 | ! |
78 -Unknown extensions do not run markers.
79 -Markdown only accepts HTML comments, so headings or bullets containing
80 -`llmiterate:` are inert.
82 -Config `commentPrefixes` appends by extension:
84 -```json
86 - "llmiterate": {
87 - "commentPrefixes": {
88 - "foo": ["COMMENT"],
89 - "lua": ["--"]
90 - }
91 - }
93 -```
95 -## Replacement behavior
97 -For each marker block, the worker receives a prompt containing:
99 -- source location:
100 - `@file:startLine`
101 -- marker text
102 -- marker span to replace
103 -- instruction to work in/around the file
104 -- instruction to remove the marker unless impossible
106 -Before a job starts, llmiterate rechecks that the marker still exists at the
107 -same line with the same prompt hash.
108 -If it changed, the job is failed as stale and skipped.
110 -After the worker finishes, llmiterate rechecks the file.
111 -If the same marker is still present at the same line with the same prompt hash,
112 -the job is marked failed.
113 -Otherwise that job is marked done.
115 -## Install / load
117 -This extension is loaded through the root pi-ext package.
118 -See [../../README.md](../../README.md).
120 -## Commands / tools / settings
122 -Commands:
124 -```text
125 -/llmiterate toggle on/off for current cwd
126 -/llmiterate on start watcher for current cwd + initial scan
127 -/llmiterate off stop watcher + worker
128 -/llmiterate status show scope/counts/state path
129 -/llmiterate explain <path> explain include/exclude/marker decision
130 -/llmiterate log render latest worker transcript and open it in $VISUAL/$EDITOR
131 -```
133 -Debug commands, registered but not autocompleted:
135 -```text
136 -/llmiterate scan scan current scope now
137 -/llmiterate forget forget run state
138 -/llmiterate reload reload config + watcher
139 -```
141 -Tools:
142 -none.
144 -Hooks:
146 -- `session_start`:
147 - stores UI context and renders status
148 -- `session_shutdown`:
149 - stops watcher/worker and releases lock
151 -Settings namespace:
152 -`llmiterate` in global Pi settings and `<scope>/.pi/settings.json`.
154 -| setting | default | behavior |
155 -| ----------------- | ---------------------------------------- | ----------------------------------------------------------------------------------- |
156 -| `enabled` | `true` | `false` blocks `/llmiterate on` |
157 -| `include` | `["**/*"]` | glob allow-list |
158 -| `exclude` | built-in metadata/build/cache dirs/files | merged with user excludes |
159 -| `debounceMs` | `3000` | save debounce before scan |
160 -| `maxFileBytes` | `1000000` | larger files skipped |
161 -| `timeoutMs` | `600000` | RPC prompt timeout |
162 -| `maxWatchDirs` | `10000` | watcher directory cap |
163 -| `commentPrefixes` | built-ins by extension | appended by extension key |
164 -| `model` | unset | passed to worker as `--model` when set |
165 -| `thinking` | unset | `off \| minimal \| low \| medium \| high \| xhigh`; passed as `--thinking` when set |
166 -| `notify` | `errors` | `off \| errors \| done \| all`; worker notifications obey this policy |
168 -Example:
170 -```json
172 - "llmiterate": {
173 - "enabled": true,
174 - "include": ["src/**/*.{ts,tsx,rs,java,md}", "docs/**/*.md"],
175 - "exclude": ["**/target/**", "**/dist/**"],
176 - "debounceMs": 3000,
177 - "maxFileBytes": 1000000,
178 - "timeoutMs": 600000,
179 - "maxWatchDirs": 10000,
180 - "model": "openai-codex/gpt-5.5",
181 - "notify": "errors",
182 - "commentPrefixes": {
183 - "foo": ["COMMENT"],
184 - "lua": ["--"]
185 - }
186 - }
188 -```
190 -## Bench
192 -Run `mise run bench` here, or `mise //extensions/llmiterate:bench` from the repository root, to benchmark marker parsing, path filtering, and gitignore scans.
194 -## Internals
196 -Only one watcher may own an exact real cwd at a time.
197 -Another Pi session in the same cwd enters standby and reports the lock owner.
198 -Parent and child dirs are independent.
200 -Watcher behavior:
202 -- uses `fs.watch`
203 -- respects `.gitignore` and `.ignore`
204 -- applies `include`/`exclude`
205 -- skips files over `maxFileBytes`
206 -- debounces file events by `debounceMs`
207 -- refreshes watched dirs after directory changes
208 -- stops at `maxWatchDirs`
210 -llmiterate itself does not edit source files.
211 -It queues prompts.
212 -A background Pi RPC worker performs edits with normal Pi tools.
214 -State file:
216 -```text
217 -<platform-state-dir>/pi/llmiterate/<sha256(scope)>/state.json
218 -```
220 -Linux default:
222 -```text
223 -${XDG_STATE_HOME:-~/.local/state}/pi/llmiterate/<sha256(scope)>/state.json
224 -```
226 -Statuses:
228 -```text
229 -queued | running | done | failed
230 -```
232 -Duplicate saves do not start duplicate queued/running jobs.
233 -Failed markers remain retryable on next save or scan.
234 -Queued/running markers from a previous Pi process are reset to failed on state
235 -load.
236 -A marker becomes `done` after the worker finishes and the original
237 -same-line/same-hash marker no longer exists.
239 -UI channels:
241 -- source file:
242 - final edits only
243 -- footer/status:
244 - watching/standby/queued/running/watch errors
245 -- notifications:
246 - command results and worker errors
247 -- `/llmiterate log`:
248 - latest worker JSONL transcript rendered as markdown at
249 - `<state>/logs/latest.md`

extensions/llmiterate/__bench__/PERF.md

Deleted
deleted file mode 100644
1 -# llmiterate performance notes
3 -## Workflow
5 -```bash
6 -bun --cpu-prof --cpu-prof-md --cpu-prof-dir=__bench__/profiles --cpu-prof-name=latest.cpuprofile.md __bench__/bench.ts
7 -bun __bench__/bench.ts
8 -```
10 -## Current benchmark
12 -```text
13 -BenchmarkParseNoMarkers 65536000 5 ns/op
14 -BenchmarkParseSomeMarkers 2000 243931 ns/op
15 -BenchmarkParseMarkdownFences 2000 317309 ns/op
16 -BenchmarkPathFilterCompiled 2000 3479021 ns/op
17 -```
19 -Notes:
21 -- no-marker files short-circuit on missing `llmiterate`
22 -- marker parsing is comment-prefix aware and language-agnostic
23 -- path benchmark now uses non-empty include patterns; old empty-default
24 - benchmark was invalid
25 -- actual latency is dominated by worker/model/tool execution, not parser CPU

extensions/llmiterate/__bench__/baseline.txt

Deleted
deleted file mode 100644
1 -BenchmarkParseNoMarkers 4000 73707 ns/op
2 -BenchmarkParseSomeMarkers 4000 82603 ns/op
3 -BenchmarkParseMarkdownFences 2000 110883 ns/op
4 -BenchmarkPathFilterCompiled 2000 3227542 ns/op

extensions/llmiterate/__bench__/bench.ts

Deleted
deleted file mode 100644
1 -import { performance } from "node:perf_hooks";
2 -import { defaultConfig } from "../config";
3 -import { parseMarkerPrompts } from "../parser";
4 -import { compilePathFilter, shouldIncludeCompiledPath } from "../path-filter";
6 -const ITERATIONS = Number(process.env.ITERATIONS ?? 2000);
7 -const MIN_TIME_MS = Number(process.env.MIN_TIME_MS ?? 200);
9 -const sourceNoMarkers = makeSource(600, 0);
10 -const sourceSomeMarkers = makeSource(600, 20);
11 -const markdown = makeMarkdown(900, 30);
12 -const paths = makePaths(5000);
13 -const filter = compilePathFilter({
14 - ...defaultConfig(),
15 - include: ["**/*.{ts,tsx,rs,java,md}"],
16 -});
18 -bench("ParseNoMarkers", () =>
19 - parseMarkerPrompts("src/main.ts", sourceNoMarkers),
20 -);
21 -bench("ParseSomeMarkers", () =>
22 - parseMarkerPrompts("src/main.ts", sourceSomeMarkers),
23 -);
24 -bench("ParseMarkdownFences", () =>
25 - parseMarkerPrompts("docs/notes.md", markdown),
26 -);
27 -bench("PathFilterCompiled", () => {
28 - let matched = 0;
29 - for (const p of paths) if (shouldIncludeCompiledPath(p, filter)) matched++;
30 - if (matched === 0) throw new Error("impossible");
31 - return matched;
32 -});
34 -function bench(name: string, fn: () => unknown): void {
35 - for (let i = 0; i < 50; i++) fn();
37 - let iterations = ITERATIONS;
38 - let elapsed = 0;
39 - let result: unknown;
41 - do {
42 - const start = performance.now();
43 - for (let i = 0; i < iterations; i++) result = fn();
44 - elapsed = performance.now() - start;
45 - if (elapsed < MIN_TIME_MS) iterations *= 2;
46 - } while (elapsed < MIN_TIME_MS);
48 - if (result === undefined) throw new Error("bench result vanished");
49 - const nsPerOp = (elapsed * 1_000_000) / iterations;
50 - console.log(`Benchmark${name} ${iterations} ${nsPerOp.toFixed(0)} ns/op`);
51 -}
53 -function makeSource(lines: number, markerEvery: number): string {
54 - const out: string[] = [];
55 - for (let i = 0; i < lines; i++) {
56 - if (markerEvery > 0 && i % markerEvery === 0)
57 - out.push(` // llmiterate: implement generated case ${i}`);
58 - else out.push(` const value${i} = callThing(${i}, "${i}");`);
59 - }
60 - return out.join("\n");
61 -}
63 -function makeMarkdown(lines: number, markerEvery: number): string {
64 - const out: string[] = ["# Notes"];
65 - for (let i = 0; i < lines; i++) {
66 - if (i % 80 === 0) out.push("```ts");
67 - if (i % 80 === 40) out.push("```");
68 - if (markerEvery > 0 && i % markerEvery === 0)
69 - out.push(`<!-- llmiterate: summarize section ${i} -->`);
70 - else out.push(`Regular prose line ${i} with enough text to be realistic.`);
71 - }
72 - return out.join("\n");
73 -}
75 -function makePaths(count: number): string[] {
76 - const exts = ["ts", "tsx", "rs", "java", "md", "png", "lock"];
77 - const dirs = [
78 - "src",
79 - "test",
80 - "node_modules/pkg",
81 - "target/debug",
82 - "research/pages",
83 - "docs",
84 - ];
85 - return Array.from(
86 - { length: count },
87 - (_, i) => `${dirs[i % dirs.length]}/file-${i}.${exts[i % exts.length]}`,
88 - );
89 -}

extensions/llmiterate/__bench__/benchstat.txt

Deleted
deleted file mode 100644
1 -Current single-run bench:
3 -BenchmarkParseNoMarkers 65536000 5 ns/op
4 -BenchmarkParseSomeMarkers 2000 243931 ns/op
5 -BenchmarkParseMarkdownFences 2000 317309 ns/op
6 -BenchmarkPathFilterCompiled 2000 3479021 ns/op
8 -No benchstat comparison: marker syntax/path workload changed.

extensions/llmiterate/__bench__/optimized.txt

Deleted
deleted file mode 100644
1 -BenchmarkParseNoMarkers 4000 57699 ns/op
2 -BenchmarkParseSomeMarkers 4000 69163 ns/op
3 -BenchmarkParseMarkdownFences 4000 80377 ns/op
4 -BenchmarkPathFilterCompiled 2000 797186 ns/op
5 -BenchmarkParseNoMarkers 4000 59416 ns/op
6 -BenchmarkParseSomeMarkers 4000 70846 ns/op
7 -BenchmarkParseMarkdownFences 4000 83867 ns/op
8 -BenchmarkPathFilterCompiled 2000 763720 ns/op
9 -BenchmarkParseNoMarkers 4000 56519 ns/op
10 -BenchmarkParseSomeMarkers 4000 67986 ns/op
11 -BenchmarkParseMarkdownFences 4000 78726 ns/op
12 -BenchmarkPathFilterCompiled 2000 750411 ns/op
13 -BenchmarkParseNoMarkers 4000 55438 ns/op
14 -BenchmarkParseSomeMarkers 4000 76997 ns/op
15 -BenchmarkParseMarkdownFences 4000 90038 ns/op
16 -BenchmarkPathFilterCompiled 2000 761932 ns/op
17 -BenchmarkParseNoMarkers 4000 57098 ns/op
18 -BenchmarkParseSomeMarkers 4000 71594 ns/op
19 -BenchmarkParseMarkdownFences 4000 79348 ns/op
20 -BenchmarkPathFilterCompiled 2000 763887 ns/op

extensions/llmiterate/__benches__/gitignore.bench.ts

Deleted
deleted file mode 100644
1 -import { bench, describe } from "vitest";
2 -import { GitIgnoreMatcher } from "../gitignore";
4 -const GITIGNORE = `
5 -node_modules/
6 -dist/
7 -build/
8 -coverage/
9 -.next/
10 -.nuxt/
11 -*.log
12 -*.tmp
13 -*.swp
14 -*~
15 -.DS_Store
16 -Thumbs.db
17 -.env
18 -.env.*
19 -!.env.example
20 -.vscode/
21 -.idea/
22 -*.min.js
23 -*.map
24 -package-lock.json
25 -yarn.lock
26 -pnpm-lock.yaml
27 -__pycache__/
28 -*.pyc
29 -*.pyo
30 -.pytest_cache/
31 -target/
32 -*.exe
33 -*.dll
34 -*.so
35 -*.class
36 -*.jar
37 -*.war
38 -*.iml
39 -*.suo
40 -*.ntvs*
41 -*.njsproj
42 -*.sln
43 -*.sw?
44 -*.dmg
45 -*.iso
46 -*.msi
47 -.*.swp
48 -.*.swo
49 -*.bak
50 -*.orig
51 -*.snap
52 -*.spec.js
53 -*.test.js
54 -__snapshots__/
55 -.cache/
56 -temp/
57 -tmp/
58 -`.trim();
60 -function generatePaths(count: number): string[] {
61 - const dirs = [
62 - "src",
63 - "src/components",
64 - "src/utils",
65 - "src/lib",
66 - "src/hooks",
67 - "tests",
68 - "tests/unit",
69 - "tests/integration",
70 - "docs",
71 - "scripts",
72 - "config",
73 - "public",
74 - "assets",
75 - "packages/core/src",
76 - "packages/ui/src",
77 - "packages/utils/src",
78 - "node_modules/lodash",
79 - "node_modules/react",
80 - "node_modules/typescript",
81 - "dist/esm",
82 - "dist/cjs",
83 - "dist/types",
84 - ".git",
85 - ".github",
86 - ".vscode",
87 - ".idea",
88 - ];
89 - const exts = [
90 - ".ts",
91 - ".js",
92 - ".tsx",
93 - ".jsx",
94 - ".json",
95 - ".md",
96 - ".css",
97 - ".html",
98 - ".log",
99 - ".tmp",
100 - ".swp",
101 - ".bak",
102 - ".map",
103 - ".min.js",
104 - ];
105 - const names = [
106 - "index",
107 - "main",
108 - "utils",
109 - "config",
110 - "types",
111 - "helpers",
112 - "constants",
113 - "hooks",
114 - "context",
115 - "provider",
116 - "App",
117 - "router",
118 - "store",
119 - "api",
120 - "client",
121 - "server",
122 - ];
123 - const out: string[] = [];
124 - for (let i = 0; i < count; i++) {
125 - const dir = dirs[i % dirs.length];
126 - const name = names[i % names.length] + (i > 0 ? String(i) : "");
127 - const ext = exts[i % exts.length];
128 - out.push(`${dir}/${name}${ext}`);
129 - }
130 - return out;
133 -const PATHS = generatePaths(10_000);
134 -const matcher = new GitIgnoreMatcher().add(GITIGNORE);
136 -describe("gitignore scan performance", () => {
137 - bench("scan 10k files", () => {
138 - let ignored = 0;
139 - for (const p of PATHS) {
140 - if (matcher.ignores(p)) ignored++;
141 - }
142 - return ignored;
143 - });
145 - bench("scan 10k dirs", () => {
146 - let ignored = 0;
147 - for (const p of PATHS) {
148 - const dir = p.slice(0, p.lastIndexOf("/"));
149 - if (dir && matcher.ignores(dir + "/")) ignored++;
150 - }
151 - return ignored;
152 - });
153 -});

extensions/llmiterate/__tests__/__snapshots__/core.test.ts.snap

Deleted
deleted file mode 100644
1 -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
3 -exports[`llmiterate output snapshots > agent prompt snapshot 1`] = `
4 -"llmiterate request from @a.rs:1
6 -Prompt marker contents:
7 -\`\`\`text
8 -implement foo
9 -\`\`\`
11 -Instructions:
12 -- Work in/around @a.rs.
13 -- Marker span to replace: a.rs:1-1.
14 -- Treat the marker comment line(s) as an inline prompt/TODO, not program code.
15 -- Replace the whole marker span with the requested implementation or code change.
16 -- Do not leave the marker line(s) behind unless impossible; explain if impossible."
17 -`;

extensions/llmiterate/__tests__/core.test.ts

Deleted
deleted file mode 100644
1 -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2 -import { tmpdir } from "node:os";
3 -import { join } from "node:path";
4 -import { afterEach, describe, expect, test } from "vitest";
5 -import {
6 - buildAgentPrompt,
7 - COMMENT_PREFIXES_BY_EXTENSION,
8 - compilePathFilter,
9 - defaultConfig,
10 - emptyState,
11 - globToRegExp,
12 - hashProjectRoot,
13 - isExcludedPath,
14 - isLlmiterateDisabled,
15 - loadState,
16 - normalizeConfig,
17 - parseMarkerPrompts,
18 - platformStateDir,
19 - previewText,
20 - projectStoreDir,
21 - STATE_FILE,
22 - saveState,
23 - shouldIncludeCompiledPath,
24 - shouldIncludePath,
25 - shouldWatchDirectory,
26 - toSlash,
27 -} from "../core";
29 -const tempDirs: string[] = [];
31 -afterEach(() => {
32 - for (const dir of tempDirs.splice(0))
33 - rmSync(dir, { recursive: true, force: true });
34 -});
36 -function tempDir(): string {
37 - const dir = mkdtempSync(join(tmpdir(), "llmiterate-core-"));
38 - tempDirs.push(dir);
39 - return dir;
42 -describe("llmiterate parser", () => {
43 - test("parses only comment-transported canonical marker", () => {
44 - const blocks = parseMarkerPrompts(
45 - "Main.java",
46 - [
47 - "void main(final String[] a) {",
48 - " // llmiterate: some prompt text",
49 - " if (a.length == 0)",
50 - " //llmiterate: deal with this",
51 - "}",
52 - ].join("\n"),
53 - );
55 - expect(blocks).toHaveLength(2);
56 - expect(blocks[0]).toMatchObject({
57 - marker: "llmiterate:",
58 - startLine: 2,
59 - endLine: 2,
60 - prompt: "some prompt text",
61 - });
62 - expect(blocks[1]).toMatchObject({ startLine: 4, prompt: "deal with this" });
63 - });
65 - test("rejects raw and legacy markers", () => {
66 - expect(
67 - parseMarkerPrompts("a.ts", "llmiterate: raw is invalid"),
68 - ).toHaveLength(0);
69 - expect(
70 - parseMarkerPrompts("a.ts", "LLM implement foo\nPROMPT implement bar"),
71 - ).toHaveLength(0);
72 - expect(parseMarkerPrompts("a.ts", "// LLM implement foo")).toHaveLength(0);
73 - });
75 - test("groups consecutive llmiterate comment lines", () => {
76 - const blocks = parseMarkerPrompts(
77 - "a.ts",
78 - [
79 - "// llmiterate: open ui",
80 - "// llmiterate: and then fix perf",
81 - "run();",
82 - ].join("\n"),
83 - );
85 - expect(blocks).toHaveLength(1);
86 - expect(blocks[0]).toMatchObject({
87 - startLine: 1,
88 - endLine: 2,
89 - prompt: "open ui\nand then fix perf",
90 - });
91 - });
93 - test("supports extension-scoped builtin comment prefixes", () => {
94 - const samples = [
95 - ["x.sh", "# llmiterate: shell"],
96 - ["x.sql", "-- llmiterate: sql"],
97 - ["x.lisp", ";;; llmiterate: lisp"],
98 - ["x.tex", "% llmiterate: tex"],
99 - ["x.md", "<!-- llmiterate: markdown -->"],
100 - ["x.c", "/* llmiterate: c */"],
101 - ["x.java", "// llmiterate: javadoc"],
102 - ["x.lua", "-- llmiterate: lua"],
103 - ] as const;
105 - expect(
106 - samples.map(([file, line]) => parseMarkerPrompts(file, line)[0]?.prompt),
107 - ).toEqual([
108 - "shell",
109 - "sql",
110 - "lisp",
111 - "tex",
112 - "markdown",
113 - "c",
114 - "javadoc",
115 - "lua",
116 - ]);
117 - });
119 - test("rejects prefixes outside their extension", () => {
120 - expect(parseMarkerPrompts("x.md", "# llmiterate: heading")).toHaveLength(0);
121 - expect(parseMarkerPrompts("x.md", "* llmiterate: bullet")).toHaveLength(0);
122 - expect(
123 - parseMarkerPrompts("x.ts", "<!-- llmiterate: html -->"),
124 - ).toHaveLength(0);
125 - expect(
126 - parseMarkerPrompts("x.txt", "// llmiterate: unknown extension"),
127 - ).toHaveLength(0);
128 - });
130 - test("appends configured comment prefixes by extension", () => {
131 - const config = normalizeConfig({ commentPrefixes: { foo: ["COMMENT"] } });
132 - expect(config.commentPrefixes.ts).toContain("//");
133 - expect(config.commentPrefixes.foo).toContain("COMMENT");
134 - expect(
135 - parseMarkerPrompts(
136 - "a.foo",
137 - "COMMENT llmiterate: custom",
138 - config.commentPrefixes,
139 - )[0]?.prompt,
140 - ).toBe("custom");
141 - });
143 - test("disable directive ignores whole file", () => {
144 - expect(
145 - isLlmiterateDisabled("// !llmiterate\n// llmiterate: ignored", "a.ts"),
146 - ).toBe(true);
147 - expect(
148 - parseMarkerPrompts("a.ts", "// !llmiterate\n// llmiterate: ignored"),
149 - ).toEqual([]);
150 - expect(
151 - parseMarkerPrompts("a.ts", "prose !llmiterate\n// llmiterate: active"),
152 - ).toHaveLength(1);
153 - });
155 - test("normalizes CRLF and CR line endings", () => {
156 - expect(
157 - parseMarkerPrompts("a.ts", "// llmiterate: one\r\n// llmiterate: two")[0]
158 - ?.prompt,
159 - ).toBe("one\ntwo");
160 - expect(
161 - parseMarkerPrompts("a.ts", "// llmiterate: one\r// llmiterate: two")[0]
162 - ?.prompt,
163 - ).toBe("one\ntwo");
164 - });
166 - test("exact marker boundary", () => {
167 - expect(parseMarkerPrompts("a.ts", "// llmiteratex: nope")).toHaveLength(0);
168 - expect(parseMarkerPrompts("a.ts", "// llmiterate : nope")).toHaveLength(0);
169 - expect(Object.keys(COMMENT_PREFIXES_BY_EXTENSION).length).toBeGreaterThan(
170 - 10,
171 - );
172 - });
173 -});
175 -describe("llmiterate config/state/path helpers", () => {
176 - test("defaults to watching everything except excludes", () => {
177 - const config = defaultConfig();
178 - const filter = compilePathFilter(config);
179 - expect(config.include).toEqual(["**/*"]);
180 - expect(shouldWatchDirectory("", filter)).toBe(true);
181 - expect(shouldIncludeCompiledPath("src/a.ts", filter)).toBe(true);
182 - });
184 - test("normalizes config", () => {
185 - const config = normalizeConfig({
186 - enabled: false,
187 - include: ["src/**/*.ts"],
188 - exclude: ["tmp/**"],
189 - debounceMs: 12.8,
190 - maxFileBytes: 42,
191 - timeoutMs: 1000.4,
192 - maxWatchDirs: 77.7,
193 - commentPrefixes: { foo: ["COMMENT"] },
194 - model: "eldoria/wyvern",
195 - thinking: "high",
196 - notify: "all",
197 - });
199 - expect(config).toMatchObject({
200 - enabled: false,
201 - include: ["src/**/*.ts"],
202 - exclude: expect.arrayContaining(["tmp/**", "**/.jj/**"]),
203 - debounceMs: 12,
204 - maxFileBytes: 42,
205 - timeoutMs: 1000,
206 - maxWatchDirs: 77,
207 - model: "eldoria/wyvern",
208 - thinking: "high",
209 - notify: "all",
210 - });
211 - expect(config.commentPrefixes.ts).toContain("//");
212 - expect(config.commentPrefixes.foo).toContain("COMMENT");
213 - });
215 - test("uses platform state dir for project stores", () => {
216 - const oldXdg = process.env.XDG_STATE_HOME;
217 - const stateRoot = tempDir();
218 - process.env.XDG_STATE_HOME = stateRoot;
219 - try {
220 - const root = "/tmp/project";
221 - expect(platformStateDir()).toBe(join(stateRoot, "pi"));
222 - expect(projectStoreDir(root)).toBe(
223 - join(stateRoot, "pi", "llmiterate", hashProjectRoot(root)),
224 - );
225 - } finally {
226 - if (oldXdg === undefined) delete process.env.XDG_STATE_HOME;
227 - else process.env.XDG_STATE_HOME = oldXdg;
228 - }
229 - });
231 - test("platformStateDir uses native conventions", () => {
232 - expect(platformStateDir("linux", {}, "/home/me")).toBe(
233 - "/home/me/.local/state/pi",
234 - );
235 - expect(
236 - platformStateDir("linux", { XDG_STATE_HOME: "/state" }, "/home/me"),
237 - ).toBe("/state/pi");
238 - expect(platformStateDir("darwin", {}, "/Users/me")).toBe(
239 - "/Users/me/Library/Application Support/pi",
240 - );
241 - expect(
242 - platformStateDir(
243 - "win32",
244 - { LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local" },
245 - "C:\\Users\\me",
246 - ),
247 - ).toBe("C:\\Users\\me\\AppData\\Local\\pi");
248 - expect(
249 - platformStateDir(
250 - "win32",
251 - {
252 - XDG_STATE_HOME: "C:\\state",
253 - LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local",
254 - },
255 - "C:\\Users\\me",
256 - ),
257 - ).toBe("C:\\state\\pi");
258 - });
260 - test("saves and loads state, invalid state falls back empty", () => {
261 - const storeDir = tempDir();
262 - const state = emptyState();
263 - state.markers["a.ts:1:hash"] = {
264 - file: "a.ts",
265 - startLine: 1,
266 - endLine: 1,
267 - promptHash: "hash",
268 - promptPreview: "preview",
269 - status: "done",
270 - attempts: 1,
271 - queuedAt: 123,
272 - updatedAt: 456,
273 - };
275 - saveState(storeDir, state);
276 - expect(loadState(storeDir)).toEqual(state);
277 - expect(
278 - readFileSync(join(storeDir, STATE_FILE), "utf-8").endsWith("\n"),
279 - ).toBe(true);
281 - writeFileSync(
282 - join(storeDir, STATE_FILE),
283 - JSON.stringify({ version: 1, markers: { bad: { file: "missing" } } }),
284 - );
285 - expect(loadState(storeDir)).toEqual(emptyState());
286 - });
288 - test("loadState resets queued/running markers to failed", () => {
289 - const storeDir = tempDir();
290 - const state = emptyState();
291 - state.markers.a = {
292 - file: "a.ts",
293 - startLine: 1,
294 - endLine: 1,
295 - promptHash: "h",
296 - promptPreview: "p",
297 - status: "running",
298 - attempts: 1,
299 - queuedAt: 1,
300 - updatedAt: 1,
301 - };
302 - saveState(storeDir, state);
303 - expect(loadState(storeDir).markers.a?.status).toBe("failed");
304 - });
306 - test("glob supports globstar, brace alternatives, and excludes", () => {
307 - const re = globToRegExp("**/*.{ts,rs}");
308 - expect(re.test("index.ts")).toBe(true);
309 - expect(re.test("src/lib.rs")).toBe(true);
310 - expect(re.test("src/lib.java")).toBe(false);
312 - const filter = compilePathFilter({
313 - include: ["**/*.{ts,rs}"],
314 - exclude: ["node_modules/**", "packages/pkg/dist/**"],
315 - });
316 - expect(shouldIncludeCompiledPath("src/lib.rs", filter)).toBe(true);
317 - expect(shouldIncludePath("node_modules/x.ts", filter)).toBe(false);
318 - expect(isExcludedPath("node_modules/x.ts", filter)).toBe(true);
319 - expect(isExcludedPath("packages/pkg/dist/x.ts", filter)).toBe(true);
321 - const defaults = compilePathFilter(defaultConfig());
322 - expect(shouldIncludeCompiledPath(".jj/repo/store.ts", defaults)).toBe(
323 - false,
324 - );
325 - expect(shouldWatchDirectory(".local", defaults)).toBe(false);
326 - expect(
327 - shouldIncludeCompiledPath(".local/share/Trash/files/a.ts", defaults),
328 - ).toBe(false);
329 - });
331 - test("directory watch traversal is include-whitelisted with exclude veto", () => {
332 - const filter = compilePathFilter({
333 - include: ["src/**/*.ts", "docs/*.md"],
334 - exclude: ["src/generated/**"],
335 - });
336 - expect(shouldWatchDirectory("", filter)).toBe(true);
337 - expect(shouldWatchDirectory("src", filter)).toBe(true);
338 - expect(shouldWatchDirectory("src/feature", filter)).toBe(true);
339 - expect(shouldWatchDirectory("docs", filter)).toBe(true);
340 - expect(shouldWatchDirectory("research", filter)).toBe(false);
341 - expect(shouldWatchDirectory("docs/deep", filter)).toBe(false);
342 - expect(shouldWatchDirectory("src/generated", filter)).toBe(false);
343 - });
345 - test("toSlash and previewText are allocation-aware utility behavior", () => {
346 - expect(toSlash("a/b/c")).toBe("a/b/c");
347 - expect(toSlash("a\\b\\c")).toBe("a/b/c");
348 - expect(previewText(" one\n two\tthree ", 9)).toBe("one two …");
349 - });
350 -});
352 -describe("llmiterate output snapshots", () => {
353 - test("agent prompt snapshot", () => {
354 - const [block] = parseMarkerPrompts("a.rs", "// llmiterate: implement foo");
355 - expect(block).toBeDefined();
356 - if (!block) throw new Error("expected llmiterate block");
357 - expect(buildAgentPrompt(block)).toMatchSnapshot();
358 - });
359 -});

extensions/llmiterate/__tests__/extension.test.ts

Deleted
deleted file mode 100644
1 -import { mkdirSync, writeFileSync } from "node:fs";
2 -import { join } from "node:path";
3 -import { afterEach, describe, expect, test } from "vitest";
4 -import { loadState, projectStoreDir } from "../core";
5 -import { createLlmiterateExtension } from "../index";
6 -import {
7 - bootLlmiterate,
8 - cleanupHarness,
9 - eventually,
10 - FakePi,
11 - FakeWorker,
12 - tempDir,
13 - tempProject,
14 -} from "./harness";
16 -afterEach(cleanupHarness);
18 -describe("llmiterate extension queue/state", () => {
19 - test("does not autostart and uses cwd-relative paths", async () => {
20 - const root = tempProject({ include: ["**/*.ts"] });
21 - mkdirSync(join(root, "src"));
22 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
24 - const worker = new FakeWorker(() => {
25 - writeFileSync(join(root, "src", "a.ts"), "export const foo = 1;\n");
26 - });
27 - const { pi } = bootLlmiterate(join(root, "src"), worker);
29 - await new Promise((resolve) => setTimeout(resolve, 20));
30 - expect(worker.prompts).toHaveLength(0);
32 - await pi.command("llmiterate", "on");
33 - await eventually(() => worker.prompts.length === 1);
35 - expect(worker.prompts[0]).toContain("@a.ts:1");
36 - expect(worker.prompts[0]).not.toContain("@src/a.ts:1");
37 - await pi.shutdown();
38 - });
40 - test("on warms worker even without queued markers", async () => {
41 - const root = tempProject({ include: ["src/**/*.ts"] });
42 - mkdirSync(join(root, "src"));
43 - writeFileSync(join(root, "src", "a.ts"), "export const a = 1;\n");
45 - const worker = new FakeWorker(() => {});
46 - const { pi } = bootLlmiterate(root, worker);
48 - expect(worker.warmed).toBe(0);
49 - await pi.command("llmiterate", "on");
50 - expect(worker.warmed).toBe(1);
51 - expect(worker.started).toBe(0);
53 - await pi.shutdown();
54 - });
56 - test("blank command toggles on then off", async () => {
57 - const root = tempProject({ include: ["src/**/*.ts"] });
58 - mkdirSync(join(root, "src"));
59 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
61 - let release!: () => void;
62 - const blocker = new Promise<void>((resolve) => {
63 - release = resolve;
64 - });
65 - const worker = new FakeWorker(async () => blocker);
66 - const { pi } = bootLlmiterate(root, worker);
68 - await pi.command("llmiterate", "");
69 - await eventually(() => worker.started === 1);
70 - await pi.command("llmiterate", "");
71 - expect(pi.ui.notifications.map((n) => n.message)).toContain(
72 - "llmiterate off",
73 - );
75 - release();
76 - await pi.shutdown();
77 - });
79 - test("does not duplicate queued/running marker on repeated scans", async () => {
80 - const root = tempProject({ include: ["src/**/*.ts"] });
81 - mkdirSync(join(root, "src"));
82 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
84 - let release!: () => void;
85 - const blocker = new Promise<void>((resolve) => {
86 - release = resolve;
87 - });
88 - const worker = new FakeWorker(async () => blocker);
89 - const { pi } = bootLlmiterate(root, worker);
91 - await pi.command("llmiterate", "on");
92 - await pi.command("llmiterate", "scan");
93 - await eventually(() => worker.started === 1);
94 - expect(worker.started).toBe(1);
96 - release();
97 - await eventually(() => worker.finished === 1);
98 - await pi.shutdown();
99 - });
101 - test("failed marker remains retryable on next scan", async () => {
102 - const root = tempProject({ include: ["src/**/*.ts"] });
103 - mkdirSync(join(root, "src"));
104 - const file = join(root, "src", "a.ts");
105 - writeFileSync(file, "// llmiterate: implement foo\n");
107 - let attempt = 0;
108 - const worker = new FakeWorker(() => {
109 - attempt++;
110 - if (attempt === 1) throw new Error("provider exploded");
111 - writeFileSync(file, "export const foo = 1;\n");
112 - });
113 - const { pi } = bootLlmiterate(root, worker);
115 - await pi.command("llmiterate", "on");
116 - await eventually(() => worker.finished === 1);
117 - expect(
118 - Object.values(loadState(projectStoreDir(root)).markers)[0]?.status,
119 - ).toBe("failed");
121 - await pi.command("llmiterate", "scan");
122 - await eventually(() => worker.finished === 2);
123 - const state = loadState(projectStoreDir(root));
124 - expect(
125 - Object.values(state.markers).some(
126 - (m) => m.status === "done" && m.attempts === 2,
127 - ),
128 - ).toBe(true);
129 - await pi.shutdown();
130 - });
132 - test("scan does not silently drop large queues", async () => {
133 - const root = tempProject({ include: ["src/**/*.ts"] });
134 - mkdirSync(join(root, "src"));
135 - const lines = Array.from(
136 - { length: 50 },
137 - (_, i) => `// llmiterate: implement ${i}\nconst marker_${i} = ${i};`,
138 - ).join("\n");
139 - writeFileSync(join(root, "src", "a.ts"), `${lines}\n`);
141 - let release!: () => void;
142 - const blocker = new Promise<void>((resolve) => {
143 - release = resolve;
144 - });
145 - const worker = new FakeWorker(async () => blocker);
146 - const { pi } = bootLlmiterate(root, worker);
148 - await pi.command("llmiterate", "on");
149 - await eventually(
150 - () => Object.keys(loadState(projectStoreDir(root)).markers).length === 50,
151 - );
152 - expect(Object.keys(loadState(projectStoreDir(root)).markers)).toHaveLength(
153 - 50,
154 - );
155 - release();
156 - await pi.shutdown();
157 - });
159 - test("notify policy defaults to errors only", async () => {
160 - const root = tempProject({ include: ["src/**/*.ts"] });
161 - mkdirSync(join(root, "src"));
162 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
164 - const worker = new FakeWorker(() => {
165 - throw new Error("bad auth");
166 - });
167 - const { pi } = bootLlmiterate(root, worker);
169 - await pi.command("llmiterate", "on");
170 - await eventually(() =>
171 - pi.ui.notifications.some((n) => n.message.includes("bad auth")),
172 - );
173 - expect(
174 - pi.ui.notifications.filter((n) =>
175 - n.message.startsWith("llmiterate queued src/"),
176 - ),
177 - ).toHaveLength(0);
178 - expect(pi.ui.notifications.some((n) => n.type === "error")).toBe(true);
179 - await pi.shutdown();
180 - });
182 - test("multiple markers in same file do not spam stale errors when agent shifts lines", async () => {
183 - const root = tempProject({ include: ["src/**/*.ts"] });
184 - mkdirSync(join(root, "src"));
185 - const file = join(root, "src", "a.ts");
186 - writeFileSync(
187 - file,
188 - [
189 - "// llmiterate: implement foo",
190 - "const a = 1;",
191 - "// llmiterate: implement bar",
192 - "const b = 2;",
193 - "// llmiterate: implement baz",
194 - "const c = 3;",
195 - ].join("\n") + "\n",
196 - );
198 - let callCount = 0;
199 - const worker = new FakeWorker(() => {
200 - callCount++;
201 - if (callCount === 1) {
202 - writeFileSync(
203 - file,
204 - [
205 - "export const foo = 1;",
206 - "// llmiterate: implement bar",
207 - "const b = 2;",
208 - "// llmiterate: implement baz",
209 - "const c = 3;",
210 - ].join("\n") + "\n",
211 - );
212 - } else if (callCount === 2) {
213 - writeFileSync(
214 - file,
215 - [
216 - "export const foo = 1;",
217 - "export const bar = 2;",
218 - "// llmiterate: implement baz",
219 - "const c = 3;",
220 - ].join("\n") + "\n",
221 - );
222 - } else if (callCount === 3) {
223 - writeFileSync(
224 - file,
225 - [
226 - "export const foo = 1;",
227 - "export const bar = 2;",
228 - "export const baz = 3;",
229 - ].join("\n") + "\n",
230 - );
231 - }
232 - });
234 - const boot = bootLlmiterate(root, worker);
235 - const { pi } = boot;
236 - await pi.command("llmiterate", "on");
238 - // First run completes and modifies file, shifting remaining markers.
239 - await eventually(() => worker.finished >= 1);
241 - // No stale error notifications should appear.
242 - const staleErrors = pi.ui.notifications.filter((n) =>
243 - n.message.includes("marker span changed"),
244 - );
245 - expect(staleErrors).toHaveLength(0);
247 - // Trigger watcher rescan to re-detect remaining markers at new positions.
248 - boot.watcher.trigger(file);
249 - await eventually(() => worker.finished >= 2);
250 - expect(
251 - pi.ui.notifications.filter((n) =>
252 - n.message.includes("marker span changed"),
253 - ),
254 - ).toHaveLength(0);
256 - // Trigger again for the third marker.
257 - boot.watcher.trigger(file);
258 - await eventually(() => worker.finished >= 3);
260 - // All done, no stale errors ever.
261 - expect(
262 - pi.ui.notifications.filter((n) =>
263 - n.message.includes("marker span changed"),
264 - ),
265 - ).toHaveLength(0);
266 - expect(worker.finished).toBe(3);
268 - await pi.shutdown();
269 - });
271 - test("stale marker for non-agent-modified file still fails with notification", async () => {
272 - const root = tempProject({ include: ["src/**/*.ts"] });
273 - mkdirSync(join(root, "src"));
274 - const file = join(root, "src", "a.ts");
275 - writeFileSync(
276 - file,
277 - [
278 - "// llmiterate: implement foo",
279 - "const a = 1;",
280 - "// llmiterate: implement bar",
281 - ].join("\n") + "\n",
282 - );
284 - let release!: () => void;
285 - const blocker = new Promise<void>((resolve) => {
286 - release = resolve;
287 - });
288 - const worker = new FakeWorker(async () => {
289 - await blocker;
290 - throw new Error("provider exploded");
291 - });
292 - const { pi } = bootLlmiterate(root, worker);
294 - await pi.command("llmiterate", "on");
295 - await eventually(() => worker.started === 1);
297 - // Modify file externally while first worker is blocked.
298 - // This shifts the second queued marker, but no agent completion touched file.
299 - writeFileSync(
300 - file,
301 - [
302 - "// llmiterate: implement foo",
303 - "const a = 1;",
304 - "const external = 1;",
305 - "// llmiterate: implement bar",
306 - ].join("\n") + "\n",
307 - );
309 - release();
310 - await eventually(() => worker.finished === 1);
312 - expect(
313 - pi.ui.notifications.some((n) =>
314 - n.message.includes("marker span changed"),
315 - ),
316 - ).toBe(true);
318 - await pi.shutdown();
319 - });
321 - test("worker guard disables extension inside llmiterate worker", async () => {
322 - const pi = new FakePi(tempDir());
323 - createLlmiterateExtension({
324 - env: { LLMITERATE_WORKER: "1" } as NodeJS.ProcessEnv,
325 - })(pi.api as never);
326 - expect(pi.commands.size).toBe(0);
327 - expect(pi.handlers.size).toBe(0);
328 - });
329 -});

extensions/llmiterate/__tests__/fake-rpc-child.mjs

Deleted
deleted file mode 100644
1 -import { writeFileSync } from "node:fs";
2 -import { join } from "node:path";
4 -const mode = process.argv[2] ?? "ok";
5 -const root = process.argv[3] ?? process.cwd();
6 -let buffer = "";
8 -process.stdin.setEncoding("utf8");
9 -process.stdin.on("end", () => process.exit(0));
10 -process.on("SIGTERM", () => process.exit(0));
11 -process.on("SIGINT", () => process.exit(0));
12 -process.stdin.on("data", (chunk) => {
13 - buffer += chunk;
14 - const lines = buffer.split("\n");
15 - buffer = lines.pop() || "";
16 - for (const line of lines) handle(line);
17 -});
19 -function handle(line) {
20 - if (!line.trim()) return;
21 - const msg = JSON.parse(line);
23 - // Fail fast: parser recovery is independent of which RPC command produced junk.
24 - if (mode === "malformed") {
25 - process.stdout.write("not json\n");
26 - return;
27 - }
29 - if (mode === "env" && msg.type === "new_session") {
30 - writeFileSync(
31 - join(root, "env.json"),
32 - JSON.stringify({ LLMITERATE_WORKER: process.env.LLMITERATE_WORKER }),
33 - );
34 - }
36 - if (mode === "fail-new-session" && msg.type === "new_session") {
37 - send({
38 - id: msg.id,
39 - type: "response",
40 - command: msg.type,
41 - success: false,
42 - error: "new_session denied",
43 - });
44 - return;
45 - }
47 - send({ id: msg.id, type: "response", command: msg.type, success: true });
49 - if (mode === "hang" && msg.type === "prompt") {
50 - send({
51 - type: "message_update",
52 - assistantMessageEvent: {
53 - type: "text_delta",
54 - contentIndex: 0,
55 - delta: "streaming forever",
56 - },
57 - });
58 - return;
59 - }
61 - if (msg.type === "prompt") {
62 - send({
63 - type: "message_update",
64 - assistantMessageEvent: {
65 - type: "text_delta",
66 - contentIndex: 0,
67 - delta: "streaming",
68 - },
69 - });
70 - send({ type: "tool_execution_start", toolName: "edit" });
71 - send({
72 - type: "tool_execution_end",
73 - toolName: "edit",
74 - isError: false,
75 - result: { content: [{ type: "text", text: "ok" }] },
76 - });
77 - send({ type: "agent_end" });
78 - }
79 -}
81 -function send(value) {
82 - process.stdout.write(JSON.stringify(value) + "\n");
83 -}

extensions/llmiterate/__tests__/gitignore.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, test } from "vitest";
2 -import { GitIgnoreMatcher } from "../gitignore";
4 -function m(): GitIgnoreMatcher {
5 - return new GitIgnoreMatcher();
6 -}
8 -describe("GitIgnoreMatcher — basics", () => {
9 - test("empty matcher ignores nothing", () => {
10 - const matcher = m();
11 - expect(matcher.ignores("a.ts")).toBe(false);
12 - expect(matcher.ignores("src/a.ts")).toBe(false);
13 - expect(matcher.ignores("")).toBe(false);
14 - });
16 - test("blank lines are skipped", () => {
17 - const matcher = m().add("\n\n \n\t\n*.log\n");
18 - expect(matcher.ignores("a.log")).toBe(true);
19 - });
21 - test("comments starting with # are skipped", () => {
22 - const matcher = m().add("# ignore logs\n*.log\n");
23 - expect(matcher.ignores("a.log")).toBe(true);
24 - expect(matcher.ignores("# ignore logs")).toBe(false);
25 - });
27 - test("escaped hash at start is treated as literal", () => {
28 - const matcher = m().add("\\#secret\n");
29 - expect(matcher.ignores("#secret")).toBe(true);
30 - expect(matcher.ignores("secret")).toBe(false);
31 - });
33 - test("trailing spaces are ignored", () => {
34 - const matcher = m().add("*.log \n");
35 - expect(matcher.ignores("a.log")).toBe(true);
36 - expect(matcher.ignores("a.log ")).toBe(false);
37 - });
39 - test("escaped trailing space is literal", () => {
40 - const matcher = m().add("foo\\ \n");
41 - expect(matcher.ignores("foo ")).toBe(true);
42 - expect(matcher.ignores("foo")).toBe(false);
43 - });
45 - test("add returns this for chaining", () => {
46 - const matcher = m();
47 - expect(matcher.add("*.log")).toBe(matcher);
48 - });
49 -});
51 -describe("GitIgnoreMatcher — glob * and ?", () => {
52 - test("* matches single path component", () => {
53 - const matcher = m().add("*\n");
54 - expect(matcher.ignores("a")).toBe(true);
55 - expect(matcher.ignores("abc")).toBe(true);
56 - expect(matcher.ignores("a/b")).toBe(true); // matches component b
57 - });
59 - test("* does not match slash", () => {
60 - // Pattern * alone matches any single path component at any depth
61 - const matcher = m().add("foo*\n");
62 - expect(matcher.ignores("foobar")).toBe(true);
63 - expect(matcher.ignores("foo/bar")).toBe(false);
64 - });
66 - test("? matches single char except slash", () => {
67 - const matcher = m().add("?.tmp\n");
68 - expect(matcher.ignores("a.tmp")).toBe(true);
69 - expect(matcher.ignores("ab.tmp")).toBe(false);
70 - // Basename pattern at any depth: ? matches b in a/b.tmp
71 - expect(matcher.ignores("a/b.tmp")).toBe(true);
72 - });
74 - test("multiple * in pattern", () => {
75 - const matcher = m().add("*.*\n");
76 - expect(matcher.ignores("a.b")).toBe(true);
77 - expect(matcher.ignores("a.b.c")).toBe(true);
78 - expect(matcher.ignores("nodots")).toBe(false);
79 - });
80 -});
82 -describe("GitIgnoreMatcher — character classes", () => {
83 - test("[abc] matches single char from set", () => {
84 - const matcher = m().add("*.[to]mp\n");
85 - expect(matcher.ignores("a.tmp")).toBe(true);
86 - expect(matcher.ignores("a.omp")).toBe(true);
87 - expect(matcher.ignores("a.xmp")).toBe(false);
88 - });
90 - test("[a-z] range matches", () => {
91 - const matcher = m().add("file[0-9].txt\n");
92 - expect(matcher.ignores("file1.txt")).toBe(true);
93 - expect(matcher.ignores("file9.txt")).toBe(true);
94 - expect(matcher.ignores("filea.txt")).toBe(false);
95 - });
97 - test("negated class [!a-z] matches outside range", () => {
98 - const matcher = m().add("file[!0-9].txt\n");
99 - expect(matcher.ignores("filea.txt")).toBe(true);
100 - expect(matcher.ignores("file1.txt")).toBe(false);
101 - });
103 - test("multiple ranges in one class", () => {
104 - const matcher = m().add("file[a-zA-Z].txt\n");
105 - expect(matcher.ignores("filea.txt")).toBe(true);
106 - expect(matcher.ignores("fileZ.txt")).toBe(true);
107 - expect(matcher.ignores("file1.txt")).toBe(false);
108 - });
110 - test("unclosed [ is treated as literal", () => {
111 - const matcher = m().add("a[b\n");
112 - expect(matcher.ignores("a[b")).toBe(true);
113 - expect(matcher.ignores("ab")).toBe(false);
114 - });
115 -});
117 -describe("GitIgnoreMatcher — escaping", () => {
118 - test("escaped specials are literals", () => {
119 - const matcher = m().add("\\#file\n\\!important\nstar\\*.txt\n");
120 - expect(matcher.ignores("#file")).toBe(true);
121 - expect(matcher.ignores("!important")).toBe(true);
122 - expect(matcher.ignores("star*.txt")).toBe(true);
123 - expect(matcher.ignores("#other")).toBe(false);
124 - });
126 - test("escaped backslash is literal", () => {
127 - const matcher = m().add("a\\\\b\n");
128 - expect(matcher.ignores("a\\b")).toBe(true);
129 - });
131 - test("backslash escapes any character", () => {
132 - const matcher = m().add("\\a\n");
133 - expect(matcher.ignores("a")).toBe(true);
134 - });
136 - test("trailing backslash is invalid and never matches", () => {
137 - const matcher = m().add("foo\\\n");
138 - expect(matcher.ignores("foo")).toBe(false);
139 - expect(matcher.ignores("foo\\")).toBe(false);
140 - // Verify a valid pattern still works in same matcher
141 - const m2 = m().add("foo\\\nbar\n");
142 - expect(m2.ignores("bar")).toBe(true);
143 - });
145 - test("literal asterisk via escape", () => {
146 - const matcher = m().add("\\*.tmp\n");
147 - expect(matcher.ignores("*.tmp")).toBe(true);
148 - expect(matcher.ignores("a.tmp")).toBe(false);
149 - });
151 - test("literal question mark via escape", () => {
152 - const matcher = m().add("\\?.tmp\n");
153 - expect(matcher.ignores("?.tmp")).toBe(true);
154 - expect(matcher.ignores("a.tmp")).toBe(false);
155 - });
156 -});
158 -describe("GitIgnoreMatcher — anchoring /", () => {
159 - test("leading / anchors to context root", () => {
160 - const matcher = m().add("/build/\n");
161 - expect(matcher.ignores("build/")).toBe(true);
162 - expect(matcher.ignores("build/output.js")).toBe(true);
163 - expect(matcher.ignores("src/build/")).toBe(false);
164 - });
166 - test("anchored file pattern", () => {
167 - const matcher = m().add("/Makefile\n");
168 - expect(matcher.ignores("Makefile")).toBe(true);
169 - expect(matcher.ignores("src/Makefile")).toBe(false);
170 - });
172 - test("middle slash makes pattern relative to gitignore dir", () => {
173 - const matcher = m().add("doc/frotz/\n");
174 - expect(matcher.ignores("doc/frotz/")).toBe(true);
175 - expect(matcher.ignores("a/doc/frotz/")).toBe(false);
176 - });
177 -});
179 -describe("GitIgnoreMatcher — directory-only trailing /", () => {
180 - test("build/ ignores only directories", () => {
181 - const matcher = m().add("build/\n");
182 - expect(matcher.ignores("build/")).toBe(true);
183 - expect(matcher.ignores("build/output.js")).toBe(true);
184 - expect(matcher.ignores("build")).toBe(false);
185 - });
187 - test("pattern without trailing slash ignores files and directories", () => {
188 - const matcher = m().add("build\n");
189 - expect(matcher.ignores("build")).toBe(true);
190 - expect(matcher.ignores("build/")).toBe(true);
191 - expect(matcher.ignores("src/build")).toBe(true);
192 - expect(matcher.ignores("src/build/")).toBe(true);
193 - });
195 - test("frotz/ matches frotz and a/frotz directories", () => {
196 - const matcher = m().add("frotz/\n");
197 - expect(matcher.ignores("frotz/")).toBe(true);
198 - expect(matcher.ignores("a/frotz/")).toBe(true);
199 - expect(matcher.ignores("frotz")).toBe(false);
200 - });
201 -});
203 -describe("GitIgnoreMatcher — double-star **", () => {
204 - test("**/foo matches foo anywhere", () => {
205 - const matcher = m().add("**/foo\n");
206 - expect(matcher.ignores("foo")).toBe(true);
207 - expect(matcher.ignores("a/foo")).toBe(true);
208 - expect(matcher.ignores("a/b/foo")).toBe(true);
209 - expect(matcher.ignores("a/foobar")).toBe(false);
210 - });
212 - test("**/foo/bar matches bar directly under foo anywhere", () => {
213 - const matcher = m().add("**/foo/bar\n");
214 - expect(matcher.ignores("foo/bar")).toBe(true);
215 - expect(matcher.ignores("a/foo/bar")).toBe(true);
216 - expect(matcher.ignores("a/foo/b/bar")).toBe(false);
217 - });
219 - test("abc/** matches everything inside abc (relative)", () => {
220 - const matcher = m().add("abc/**\n");
221 - expect(matcher.ignores("abc/foo")).toBe(true);
222 - expect(matcher.ignores("abc/foo/bar")).toBe(true);
223 - expect(matcher.ignores("abc/")).toBe(false);
224 - expect(matcher.ignores("abc")).toBe(false);
225 - // Relative pattern: does NOT match x/abc/foo
226 - expect(matcher.ignores("x/abc/foo")).toBe(false);
227 - });
229 - test("a/**/b matches zero or more directories (relative)", () => {
230 - const matcher = m().add("a/**/b\n");
231 - expect(matcher.ignores("a/b")).toBe(true);
232 - expect(matcher.ignores("a/x/b")).toBe(true);
233 - expect(matcher.ignores("a/x/y/b")).toBe(true);
234 - expect(matcher.ignores("a/c")).toBe(false);
235 - // Relative pattern: does NOT match z/a/x/b
236 - expect(matcher.ignores("z/a/x/b")).toBe(false);
237 - });
239 - test("foo/**/bar/baz matches nested", () => {
240 - const matcher = m().add("foo/**/bar/baz\n");
241 - expect(matcher.ignores("foo/bar/baz")).toBe(true);
242 - expect(matcher.ignores("foo/x/bar/baz")).toBe(true);
243 - expect(matcher.ignores("foo/x/y/bar/baz")).toBe(true);
244 - expect(matcher.ignores("foo/bar/baz/qux")).toBe(true);
245 - expect(matcher.ignores("foo/bar/qux")).toBe(false);
246 - });
248 - test("** alone matches everything", () => {
249 - const matcher = m().add("**\n");
250 - expect(matcher.ignores("a")).toBe(true);
251 - expect(matcher.ignores("a/b/c")).toBe(true);
252 - });
253 -});
255 -describe("GitIgnoreMatcher — negation !", () => {
256 - test("!important.log negates previous ignore", () => {
257 - const matcher = m().add("*.log\n!important.log\n");
258 - expect(matcher.ignores("debug.log")).toBe(true);
259 - expect(matcher.ignores("important.log")).toBe(false);
260 - });
262 - test("multiple negations in sequence", () => {
263 - const matcher = m().add("*.log\n!a.log\n!b.log\n");
264 - expect(matcher.ignores("c.log")).toBe(true);
265 - expect(matcher.ignores("a.log")).toBe(false);
266 - expect(matcher.ignores("b.log")).toBe(false);
267 - });
269 - test("negation cannot re-include if parent dir is excluded", () => {
270 - const matcher = m().add("dist/\n!dist/keep.txt\n");
271 - expect(matcher.ignores("dist/keep.txt")).toBe(true);
272 - });
274 - test("anchored negation !/build", () => {
275 - const matcher = m().add("/build/\n!/build/keep/\n");
276 - expect(matcher.ignores("build/")).toBe(true);
277 - // Cannot re-include if parent is excluded per gitignore spec
278 - expect(matcher.ignores("build/keep/")).toBe(true);
279 - });
281 - test("negation with directory-only", () => {
282 - const matcher = m().add("logs/\n!logs/important/\n");
283 - expect(matcher.ignores("logs/debug/")).toBe(true);
284 - // Cannot re-include if parent is excluded per gitignore spec
285 - expect(matcher.ignores("logs/important/")).toBe(true);
286 - });
287 -});
289 -describe("GitIgnoreMatcher — parent directory propagation", () => {
290 - test("parent directory ignored ignores children", () => {
291 - const matcher = m().add("dist/\n");
292 - expect(matcher.ignores("dist/bundle.js")).toBe(true);
293 - expect(matcher.ignores("dist/assets/logo.png")).toBe(true);
294 - expect(matcher.ignores("dist/sub/deep/file")).toBe(true);
295 - });
297 - test("deep parent directory ignored", () => {
298 - const matcher = m().add("node_modules/\n");
299 - expect(matcher.ignores("node_modules/.package-lock.json")).toBe(true);
300 - expect(matcher.ignores("a/b/node_modules/c/d")).toBe(true);
301 - });
302 -});
304 -describe("GitIgnoreMatcher — real-world patterns", () => {
305 - test("node_modules", () => {
306 - const matcher = m().add("node_modules/\n");
307 - expect(matcher.ignores("node_modules/lodash/index.js")).toBe(true);
308 - expect(matcher.ignores("node_modules/.package-lock.json")).toBe(true);
309 - expect(matcher.ignores("src/node_modules/")).toBe(true);
310 - });
312 - test("dotenv files", () => {
313 - const matcher = m().add(".env\n.env.*\n!.env.example\n");
314 - expect(matcher.ignores(".env")).toBe(true);
315 - expect(matcher.ignores(".env.local")).toBe(true);
316 - expect(matcher.ignores(".env.production")).toBe(true);
317 - expect(matcher.ignores(".env.example")).toBe(false);
318 - });
320 - test("IDE directories", () => {
321 - const matcher = m().add(".idea/\n.vscode/\n*.swp\n*~\n");
322 - expect(matcher.ignores(".idea/workspace.xml")).toBe(true);
323 - expect(matcher.ignores(".vscode/settings.json")).toBe(true);
324 - expect(matcher.ignores("file.swp")).toBe(true);
325 - expect(matcher.ignores("backup~")).toBe(true);
326 - });
328 - test("build artifacts", () => {
329 - const matcher = m().add("dist/\nbuild/\ncoverage/\n*.min.js\n*.map\n");
330 - expect(matcher.ignores("dist/app.js")).toBe(true);
331 - expect(matcher.ignores("build/index.html")).toBe(true);
332 - expect(matcher.ignores("coverage/lcov-report")).toBe(true);
333 - expect(matcher.ignores("app.min.js")).toBe(true);
334 - expect(matcher.ignores("app.js.map")).toBe(true);
335 - });
337 - test("OS files", () => {
338 - const matcher = m().add(".DS_Store\nThumbs.db\n");
339 - expect(matcher.ignores(".DS_Store")).toBe(true);
340 - expect(matcher.ignores("src/.DS_Store")).toBe(true);
341 - });
343 - test("lockfiles", () => {
344 - const matcher = m().add("package-lock.json\nyarn.lock\n");
345 - expect(matcher.ignores("package-lock.json")).toBe(true);
346 - expect(matcher.ignores("yarn.lock")).toBe(true);
347 - expect(matcher.ignores("package.json")).toBe(false);
348 - });
350 - test("python artifacts", () => {
351 - const matcher = m().add("__pycache__/\n*.pyc\n*.pyo\n.pytest_cache/\n");
352 - expect(matcher.ignores("__pycache__/foo.cpython-311.pyc")).toBe(true);
353 - expect(matcher.ignores("module.pyc")).toBe(true);
354 - expect(matcher.ignores(".pytest_cache/v/cache/nodeids")).toBe(true);
355 - });
357 - test("Rust target", () => {
358 - const matcher = m().add("target/\n");
359 - expect(matcher.ignores("target/debug/app")).toBe(true);
360 - expect(matcher.ignores("target/release/libfoo.so")).toBe(true);
361 - });
362 -});
364 -describe("GitIgnoreMatcher — brutal edge cases", () => {
365 - test("pattern with only slash is invalid", () => {
366 - const matcher = m().add("/\n");
367 - expect(matcher.ignores("a")).toBe(false);
368 - });
370 - test("pattern . is invalid", () => {
371 - const matcher = m().add(".\n");
372 - expect(matcher.ignores(".")).toBe(false);
373 - });
375 - test("pattern .. is invalid", () => {
376 - const matcher = m().add("..\n");
377 - expect(matcher.ignores("..")).toBe(false);
378 - });
380 - test("pattern starting with ./ is invalid", () => {
381 - const matcher = m().add("./foo\n");
382 - expect(matcher.ignores("foo")).toBe(false);
383 - });
385 - test("pattern starting with ../ is invalid", () => {
386 - const matcher = m().add("../foo\n");
387 - expect(matcher.ignores("foo")).toBe(false);
388 - });
390 - test("consecutive slashes in pattern", () => {
391 - const matcher = m().add("a//b\n");
392 - expect(matcher.ignores("a//b")).toBe(true);
393 - });
395 - test("pattern with spaces in filename", () => {
396 - const matcher = m().add("my\\ file.txt\n");
397 - expect(matcher.ignores("my file.txt")).toBe(true);
398 - });
400 - test("unicode in pattern", () => {
401 - const matcher = m().add("*.äöü\n");
402 - expect(matcher.ignores("file.äöü")).toBe(true);
403 - });
405 - test("very long pattern still works", () => {
406 - const longName = "a".repeat(200);
407 - const matcher = m().add(`${longName}\n`);
408 - expect(matcher.ignores(longName)).toBe(true);
409 - });
411 - test("CRLF line endings", () => {
412 - const matcher = m().add("*.log\r\n*.tmp\r\n");
413 - expect(matcher.ignores("a.log")).toBe(true);
414 - expect(matcher.ignores("a.tmp")).toBe(true);
415 - });
417 - test("mixed line endings", () => {
418 - const matcher = m().add("*.log\n*.tmp\r\n*.bak\n");
419 - expect(matcher.ignores("a.log")).toBe(true);
420 - expect(matcher.ignores("a.tmp")).toBe(true);
421 - expect(matcher.ignores("a.bak")).toBe(true);
422 - });
424 - test("empty string add is no-op", () => {
425 - const matcher = m().add("");
426 - expect(matcher.ignores("a")).toBe(false);
427 - });
429 - test("pattern ending with just / after stripping is invalid", () => {
430 - const matcher = m().add("/\n");
431 - expect(matcher.ignores("/")).toBe(false);
432 - });
434 - test("negation of non-ignored file is no-op", () => {
435 - const matcher = m().add("!keep.txt\n");
436 - expect(matcher.ignores("keep.txt")).toBe(false);
437 - });
439 - test("pattern that matches after being negated then re-ignored", () => {
440 - const matcher = m().add("*.log\n!important.log\n*.log\n");
441 - expect(matcher.ignores("important.log")).toBe(true);
442 - });
444 - test("directory check on file pattern", () => {
445 - const matcher = m().add("build\n");
446 - expect(matcher.ignores("build")).toBe(true);
447 - expect(matcher.ignores("build/")).toBe(true);
448 - expect(matcher.ignores("src/build/")).toBe(true);
449 - });
451 - test("multiple add calls accumulate", () => {
452 - const matcher = m().add("*.log\n").add("*.tmp\n");
453 - expect(matcher.ignores("a.log")).toBe(true);
454 - expect(matcher.ignores("a.tmp")).toBe(true);
455 - });
457 - test("foo*bar matches foobar and fooXbar", () => {
458 - const matcher = m().add("foo*bar\n");
459 - expect(matcher.ignores("foobar")).toBe(true);
460 - expect(matcher.ignores("fooXbar")).toBe(true);
461 - expect(matcher.ignores("foo/bar")).toBe(false);
462 - });
464 - test("**/ prefix matches basename anywhere", () => {
465 - const matcher = m().add("**/Makefile\n");
466 - expect(matcher.ignores("Makefile")).toBe(true);
467 - expect(matcher.ignores("src/Makefile")).toBe(true);
468 - // Does NOT match Makefile.am — different basename
469 - expect(matcher.ignores("src/Makefile.am")).toBe(false);
470 - });
472 - test("deep nested dirs with **", () => {
473 - const matcher = m().add("**/node_modules/**\n");
474 - expect(matcher.ignores("node_modules/foo")).toBe(true);
475 - expect(matcher.ignores("a/node_modules/foo")).toBe(true);
476 - expect(matcher.ignores("a/node_modules/foo/bar")).toBe(true);
477 - });
479 - test("pattern with all special chars escaped", () => {
480 - const matcher = m().add("\\.\\[\\*\\?\\#\\!\\/\\]\n");
481 - expect(matcher.ignores(".[*?#!/]")).toBe(true);
482 - });
483 -});
485 -describe("GitIgnoreMatcher — git docs compliance", () => {
486 - test("doc/frotz/ matches doc/frotz but not a/doc/frotz", () => {
487 - const matcher = m().add("doc/frotz/\n");
488 - expect(matcher.ignores("doc/frotz/")).toBe(true);
489 - expect(matcher.ignores("a/doc/frotz/")).toBe(false);
490 - });
492 - test("frotz/ matches frotz and a/frotz directories", () => {
493 - const matcher = m().add("frotz/\n");
494 - expect(matcher.ignores("frotz/")).toBe(true);
495 - expect(matcher.ignores("a/frotz/")).toBe(true);
496 - expect(matcher.ignores("frotz")).toBe(false);
497 - });
499 - test("**/foo same as foo", () => {
500 - const m1 = m().add("**/foo\n");
501 - const m2 = m().add("foo\n");
502 - const paths = ["foo", "a/foo", "a/b/foo", "foobar"];
503 - for (const p of paths) {
504 - expect(m1.ignores(p)).toBe(m2.ignores(p));
505 - }
506 - });
508 - test("**/foo/bar matches bar directly under foo anywhere", () => {
509 - const matcher = m().add("**/foo/bar\n");
510 - expect(matcher.ignores("foo/bar")).toBe(true);
511 - expect(matcher.ignores("a/foo/bar")).toBe(true);
512 - expect(matcher.ignores("a/foo/b/bar")).toBe(false);
513 - expect(matcher.ignores("foo/bar/baz")).toBe(true);
514 - });
516 - test("abc/** matches all files inside abc with infinite depth", () => {
517 - const matcher = m().add("abc/**\n");
518 - expect(matcher.ignores("abc/foo")).toBe(true);
519 - expect(matcher.ignores("abc/foo/bar")).toBe(true);
520 - expect(matcher.ignores("abc/foo/bar/baz")).toBe(true);
521 - expect(matcher.ignores("abc/")).toBe(false);
522 - expect(matcher.ignores("abc")).toBe(false);
523 - });
525 - test("a/**/b matches a/b a/x/b a/x/y/b", () => {
526 - const matcher = m().add("a/**/b\n");
527 - expect(matcher.ignores("a/b")).toBe(true);
528 - expect(matcher.ignores("a/x/b")).toBe(true);
529 - expect(matcher.ignores("a/x/y/b")).toBe(true);
530 - });
531 -});

extensions/llmiterate/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { afterEach, describe, expect, it } from "vitest";
2 -import { createTestSession, type TestSession } from "../../../test/harness";
3 -import llmiterateExtension from "../index";
5 -describe("llmiterate pi-test-harness", () => {
6 - let t: TestSession | undefined;
8 - afterEach(() => {
9 - t?.dispose();
10 - t = undefined;
11 - });
13 - it("loads in real Pi extension runtime", async () => {
14 - t = await createTestSession({ extensionFactories: [llmiterateExtension] });
16 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
17 - });
18 -});

extensions/llmiterate/__tests__/harness.ts

Deleted
deleted file mode 100644
1 -import {
2 - mkdirSync,
3 - mkdtempSync,
4 - readdirSync,
5 - rmSync,
6 - writeFileSync,
7 -} from "node:fs";
8 -import { tmpdir } from "node:os";
9 -import { join } from "node:path";
10 -import { expect } from "vitest";
11 -import type { CompiledPathFilter, LlmiterateConfig } from "../core";
12 -import { createLlmiterateExtension } from "../index";
13 -import type { PiRpcWorker } from "../rpc";
14 -import type { ProjectWatcher } from "../watcher";
16 -const tempDirs: string[] = [];
17 -const oldXdg = process.env.XDG_STATE_HOME;
19 -export function cleanupHarness(): void {
20 - if (oldXdg === undefined) delete process.env.XDG_STATE_HOME;
21 - else process.env.XDG_STATE_HOME = oldXdg;
22 - for (const dir of tempDirs.splice(0))
23 - rmSync(dir, { recursive: true, force: true });
26 -export class FakeWorker {
27 - prompts: string[] = [];
28 - started = 0;
29 - finished = 0;
30 - warmed = 0;
32 - constructor(
33 - private readonly handler: (prompt: string) => unknown | Promise<unknown>,
34 - ) {}
36 - warm(): void {
37 - this.warmed++;
38 - }
40 - async runPrompt(prompt: string): Promise<void> {
41 - this.started++;
42 - this.prompts.push(prompt);
43 - try {
44 - await this.handler(prompt);
45 - } finally {
46 - this.finished++;
47 - }
48 - }
50 - dispose(): void {}
53 -export class FakeWatcher {
54 - errorCount = 0;
55 - watcherCount = 1;
56 - constructor(
57 - private readonly root: string,
58 - private readonly onFileReady: (absolutePath: string) => void,
59 - ) {}
60 - start(): void {}
61 - stop(): void {}
62 - scanAll(onFile: (absolutePath: string) => number): number {
63 - let total = 0;
64 - walk(this.root, (file) => {
65 - total += onFile(file);
66 - });
67 - return total;
68 - }
69 - trigger(file: string): void {
70 - this.onFileReady(file);
71 - }
74 -export class FakePi {
75 - handlers = new Map<string, Function[]>();
76 - commands = new Map<string, Function>();
77 - ui = new FakeUi();
78 - api = {
79 - on: (event: string, handler: Function) => {
80 - const list = this.handlers.get(event) ?? [];
81 - list.push(handler);
82 - this.handlers.set(event, list);
83 - },
84 - registerCommand: (name: string, command: { handler: Function }) => {
85 - this.commands.set(name, command.handler);
86 - },
87 - };
89 - constructor(readonly cwd: string) {}
91 - async start(cwd = this.cwd): Promise<void> {
92 - for (const handler of this.handlers.get("session_start") ?? []) {
93 - await handler({}, { cwd, hasUI: true, ui: this.ui });
94 - }
95 - }
97 - async shutdown(): Promise<void> {
98 - for (const handler of this.handlers.get("session_shutdown") ?? [])
99 - await handler({});
100 - }
102 - async command(name: string, args: string): Promise<void> {
103 - await this.commands.get(name)?.(args, {
104 - cwd: this.cwd,
105 - hasUI: true,
106 - ui: this.ui,
107 - });
108 - }
111 -export class FakeUi {
112 - notifications: Array<{ message: string; type: string }> = [];
113 - statuses: Array<{ key: string; value: string | undefined }> = [];
114 - theme = {
115 - fg: (_: string, text: string) => text,
116 - bold: (text: string) => text,
117 - };
118 - notify(message: string, type = "info"): void {
119 - this.notifications.push({ message, type });
120 - }
121 - setStatus(key: string, value: string | undefined): void {
122 - this.statuses.push({ key, value });
123 - }
124 - setWidget(): void {}
127 -export function bootLlmiterate(
128 - cwd: string,
129 - worker: FakeWorker,
130 -): { pi: FakePi; readonly watcher: FakeWatcher } {
131 - process.env.XDG_STATE_HOME = tempDir();
132 - const pi = new FakePi(cwd);
133 - let watcher!: FakeWatcher;
134 - createLlmiterateExtension({
135 - makeWorker: () => worker as unknown as PiRpcWorker,
136 - makeWatcher: (
137 - watchRoot: string,
138 - _config: LlmiterateConfig,
139 - _filter: CompiledPathFilter,
140 - onFileReady: (absolutePath: string) => void,
141 - ) => {
142 - watcher = new FakeWatcher(watchRoot, onFileReady);
143 - return watcher as unknown as ProjectWatcher;
144 - },
145 - now: () => 123,
146 - openEditor: () => undefined,
147 - })(pi.api as never);
148 - void pi.start(cwd);
149 - return {
150 - pi,
151 - get watcher() {
152 - return watcher;
153 - },
154 - };
157 -export function tempProject(llmiterate: Record<string, unknown>): string {
158 - const root = tempDir();
159 - mkdirSync(join(root, ".pi"));
160 - writeFileSync(
161 - join(root, ".pi", "settings.json"),
162 - JSON.stringify({ llmiterate }, null, 2),
163 - );
164 - return root;
167 -export function tempDir(): string {
168 - const dir = mkdtempSync(join(tmpdir(), "llmiterate-ext-"));
169 - tempDirs.push(dir);
170 - return dir;
173 -export async function eventually(predicate: () => boolean): Promise<void> {
174 - const deadline = Date.now() + 1500;
175 - while (Date.now() < deadline) {
176 - if (predicate()) return;
177 - await new Promise((resolve) => setTimeout(resolve, 10));
178 - }
179 - expect(predicate()).toBe(true);
182 -function walk(dir: string, onFile: (file: string) => void): void {
183 - const entries = readdirSync(dir, { withFileTypes: true });
184 - for (const entry of entries) {
185 - const file = join(dir, entry.name);
186 - if (entry.isDirectory()) walk(file, onFile);
187 - else if (entry.isFile()) onFile(file);
188 - }

extensions/llmiterate/__tests__/lock.test.ts

Deleted
deleted file mode 100644
1 -import {
2 - existsSync,
3 - mkdirSync,
4 - mkdtempSync,
5 - rmSync,
6 - writeFileSync,
7 -} from "node:fs";
8 -import { hostname, tmpdir } from "node:os";
9 -import { join } from "node:path";
10 -import { afterEach, describe, expect, test } from "vitest";
11 -import { acquireLock, type LockHandle, realPath, releaseLock } from "../lock";
13 -const tempDirs: string[] = [];
15 -afterEach(() => {
16 - for (const dir of tempDirs.splice(0))
17 - rmSync(dir, { recursive: true, force: true });
18 -});
20 -function tempDir(): string {
21 - const dir = mkdtempSync(join(tmpdir(), "llmiterate-lock-"));
22 - tempDirs.push(dir);
23 - return dir;
24 -}
26 -describe("llmiterate lock", () => {
27 - test("realPath resolves existing paths", () => {
28 - const root = tempDir();
29 - expect(realPath(root)).toBe(root);
30 - });
32 - test("acquires, blocks duplicate, and releases lock", () => {
33 - const root = tempDir();
34 - const storeDir = tempDir();
35 - const lock = expectLock(acquireLock(storeDir));
37 - const duplicate = acquireLock(storeDir);
38 - expect(duplicate).toContain("singleton lock held by");
39 - expect(lock.dir).toBe(join(storeDir, "lock"));
40 - expect(existsSync(join(root, ".pi"))).toBe(false);
42 - releaseLock(lock);
43 - const reacquired = expectLock(acquireLock(storeDir));
44 - releaseLock(reacquired);
45 - });
47 - test("does not release lock owned by different token", () => {
48 - const storeDir = tempDir();
49 - const lock = expectLock(acquireLock(storeDir));
50 - releaseLock({ dir: lock.dir, token: "wrong" });
51 - expect(acquireLock(storeDir)).toContain("singleton lock held by");
52 - releaseLock(lock);
53 - });
55 - test("recovers stale lock in global store", () => {
56 - const storeDir = tempDir();
57 - mkdirSync(join(storeDir, "lock"));
58 - writeFileSync(
59 - join(storeDir, "lock", "owner.json"),
60 - JSON.stringify({ pid: 99_999_999, hostname: hostname(), token: "stale" }),
61 - );
63 - const lock = expectLock(acquireLock(storeDir));
64 - expect(lock.dir).toBe(join(storeDir, "lock"));
65 - releaseLock(lock);
66 - });
68 - test("malformed owner does not trigger recovery", () => {
69 - const storeDir = tempDir();
70 - mkdirSync(join(storeDir, "lock"));
71 - writeFileSync(
72 - join(storeDir, "lock", "owner.json"),
73 - JSON.stringify({
74 - pid: 99_999_999,
75 - hostname: hostname(),
76 - token: "old",
77 - extra: 1,
78 - }),
79 - );
81 - expect(acquireLock(storeDir)).toContain(
82 - "singleton lock held by another pi",
83 - );
84 - expect(existsSync(join(storeDir, "lock", "owner.json"))).toBe(true);
85 - });
86 -});
88 -function expectLock(value: LockHandle | string): LockHandle {
89 - expect(typeof value).toBe("object");
90 - if (typeof value === "string") throw new Error(value);
91 - return value;
92 -}

extensions/llmiterate/__tests__/log.test.ts

Deleted
deleted file mode 100644
1 -import {
2 - mkdirSync,
3 - mkdtempSync,
4 - readFileSync,
5 - rmSync,
6 - utimesSync,
7 - writeFileSync,
8 -} from "node:fs";
9 -import { tmpdir } from "node:os";
10 -import { join } from "node:path";
11 -import { afterEach, describe, expect, test } from "vitest";
12 -import {
13 - latestSessionFile,
14 - parseEditorCommand,
15 - renderLatestSessionLog,
16 - renderSessionLogMarkdown,
17 -} from "../log";
19 -const tempDirs: string[] = [];
21 -afterEach(() => {
22 - for (const dir of tempDirs.splice(0))
23 - rmSync(dir, { recursive: true, force: true });
24 -});
26 -describe("editor command parsing", () => {
27 - test("splits VISUAL/EDITOR without shell", () => {
28 - expect(parseEditorCommand("nvim -p --cmd 'set ft=markdown'")).toEqual({
29 - command: "nvim",
30 - args: ["-p", "--cmd", "set ft=markdown"],
31 - });
32 - expect(parseEditorCommand("code --wait")).toEqual({
33 - command: "code",
34 - args: ["--wait"],
35 - });
36 - expect(parseEditorCommand(" ")).toBeUndefined();
37 - });
38 -});
40 -describe("llmiterate log renderer", () => {
41 - test("renders session JSONL to markdown", () => {
42 - const root = tempDir();
43 - const session = join(root, "session.jsonl");
44 - writeFileSync(
45 - session,
46 - [
47 - JSON.stringify({ message: { role: "user", content: "do thing" } }),
48 - JSON.stringify({
49 - message: {
50 - role: "assistant",
51 - content: [{ type: "text", text: "I edited it." }],
52 - },
53 - }),
54 - JSON.stringify({
55 - type: "tool_execution_end",
56 - toolName: "edit",
57 - isError: false,
58 - }),
59 - ].join("\n") + "\n",
60 - );
62 - expect(renderSessionLogMarkdown(session)).toContain("## Assistant");
63 - expect(renderSessionLogMarkdown(session)).toContain("I edited it.");
64 - expect(renderSessionLogMarkdown(session)).not.toContain('{"message"');
65 - });
67 - test("picks newest jsonl recursively and writes latest markdown", () => {
68 - const root = tempDir();
69 - mkdirSync(join(root, "a"));
70 - const older = join(root, "old.jsonl");
71 - const newer = join(root, "a", "new.jsonl");
72 - writeFileSync(
73 - older,
74 - JSON.stringify({ message: { role: "assistant", content: "old" } }) + "\n",
75 - );
76 - writeFileSync(
77 - newer,
78 - JSON.stringify({ message: { role: "assistant", content: "new" } }) + "\n",
79 - );
80 - utimesSync(older, new Date(1000), new Date(1000));
81 - utimesSync(newer, new Date(2000), new Date(2000));
83 - expect(latestSessionFile(root)).toBe(newer);
84 - const target = renderLatestSessionLog(root, join(root, "logs"));
85 - expect(target?.sessionFile).toBe(newer);
86 - expect(readFileSync(target?.markdownFile, "utf-8")).toContain("new");
87 - });
88 -});
90 -function tempDir(): string {
91 - const dir = mkdtempSync(join(tmpdir(), "llmiterate-log-"));
92 - tempDirs.push(dir);
93 - return dir;
94 -}

extensions/llmiterate/__tests__/rpc-full.test.ts

Deleted
deleted file mode 100644
1 -import { mkdtempSync, readFileSync } from "node:fs";
2 -import { rm } from "node:fs/promises";
3 -import { tmpdir } from "node:os";
4 -import { join } from "node:path";
5 -import { fileURLToPath } from "node:url";
6 -import { describe, expect, test } from "vitest";
7 -import { LLMITERATE_WORKER_ENV, PiRpcWorker, workerArgs } from "../rpc";
8 -import type { RpcEvent } from "../types";
10 -const fakeRpcScript = fileURLToPath(
11 - new URL("./fake-rpc-child.mjs", import.meta.url),
12 -);
14 -type FakeRpcMode = "ok" | "fail-new-session" | "malformed" | "env" | "hang";
16 -describe("PiRpcWorker args", () => {
17 - test("builds llmiterate worker invocation", () => {
18 - expect(
19 - workerArgs({
20 - sessionDir: "/state/sessions",
21 - model: "eldoria/wyvern",
22 - thinking: "high",
23 - }),
24 - ).toEqual([
25 - "--mode",
26 - "rpc",
27 - "--offline",
28 - "--session-dir",
29 - "/state/sessions",
30 - "--append-system-prompt",
31 - expect.stringContaining("llmiterate"),
32 - "--model",
33 - "eldoria/wyvern",
34 - "--thinking",
35 - "high",
36 - ]);
37 - });
39 - test.concurrent("does not use no-extensions and sets worker env", async () => {
40 - await withFakeWorker({ mode: "env" }, async (worker, root) => {
41 - await worker.runPrompt("do thing", "job name");
42 - expect(
43 - JSON.parse(readFileSync(join(root, "env.json"), "utf-8")),
44 - ).toMatchObject({
45 - [LLMITERATE_WORKER_ENV]: "1",
46 - });
47 - });
48 - });
49 -});
51 -describe.concurrent("PiRpcWorker integration", () => {
52 - test("runs prompt through JSON-RPC worker and forwards events", async () => {
53 - const events: RpcEvent[] = [];
54 - await withFakeWorker(
55 - { mode: "ok", onEvent: (event) => events.push(event) },
56 - async (worker) => {
57 - await worker.runPrompt("do thing", "job name");
58 - },
59 - );
61 - expect(events.map((e) => e.type)).toEqual([
62 - "message_update",
63 - "tool_execution_start",
64 - "tool_execution_end",
65 - "agent_end",
66 - ]);
67 - const first = events[0];
68 - expect(first.type).toBe("message_update");
69 - if (first.type === "message_update") {
70 - expect(first.assistantMessageEvent).toEqual({
71 - type: "text_delta",
72 - contentIndex: 0,
73 - delta: "streaming",
74 - });
75 - }
76 - });
78 - test("rejects concurrent prompts instead of corrupting current prompt", async () => {
79 - await withFakeWorker({ mode: "ok" }, async (worker) => {
80 - const first = worker.runPrompt("first", "first job");
81 - await expect(worker.runPrompt("second", "second job")).rejects.toThrow(
82 - "already has an active prompt",
83 - );
84 - await first;
85 - });
86 - });
88 - test("rejects failed RPC command", async () => {
89 - await withFakeWorker({ mode: "fail-new-session" }, async (worker) => {
90 - await expect(worker.runPrompt("do thing", "job name")).rejects.toThrow(
91 - "new_session denied",
92 - );
93 - });
94 - });
96 - test("times out hung prompts", async () => {
97 - // Tiny timeout covers abort path without adding idle test latency.
98 - await withFakeWorker({ mode: "hang", timeoutMs: 1 }, async (worker) => {
99 - await expect(worker.runPrompt("do thing", "job name")).rejects.toThrow(
100 - "timed out",
101 - );
102 - });
103 - });
105 - test("rejects malformed RPC stdout", async () => {
106 - await withFakeWorker({ mode: "malformed" }, async (worker) => {
107 - await expect(worker.runPrompt("do thing", "job name")).rejects.toThrow();
108 - });
109 - });
110 -});
112 -async function withFakeWorker<T>(
113 - options: {
114 - mode: FakeRpcMode;
115 - onEvent?: (event: RpcEvent) => void;
116 - timeoutMs?: number;
117 - },
118 - fn: (worker: PiRpcWorker, root: string) => Promise<T>,
119 -): Promise<T> {
120 - const root = tempDir();
121 - const worker = fakeWorker(
122 - root,
123 - options.mode,
124 - options.onEvent,
125 - options.timeoutMs,
126 - );
127 - try {
128 - return await fn(worker, root);
129 - } finally {
130 - await worker.dispose();
131 - await rm(root, {
132 - recursive: true,
133 - force: true,
134 - maxRetries: 20,
135 - retryDelay: 50,
136 - });
137 - }
140 -function fakeWorker(
141 - root: string,
142 - mode: FakeRpcMode,
143 - onEvent: (event: RpcEvent) => void = () => {},
144 - timeoutMs?: number,
145 -): PiRpcWorker {
146 - return new PiRpcWorker({
147 - cwd: root,
148 - sessionDir: join(root, "sessions"),
149 - invocation: {
150 - command: process.execPath,
151 - args: [fakeRpcScript, mode, root],
152 - },
153 - timeoutMs,
154 - onEvent,
155 - });
158 -function tempDir(): string {
159 - return mkdtempSync(join(tmpdir(), "llmiterate-rpc-"));

extensions/llmiterate/__tests__/rpc.test.ts

Deleted
deleted file mode 100644
1 -import { mkdtempSync } from "node:fs";
2 -import { rm } from "node:fs/promises";
3 -import { tmpdir } from "node:os";
4 -import { join } from "node:path";
5 -import { fileURLToPath } from "node:url";
6 -import { describe, expect, test } from "vitest";
7 -import { PiRpcWorker, workerArgs } from "../rpc";
8 -import type { RpcEvent } from "../types";
10 -const fakeRpcScript = fileURLToPath(
11 - new URL("./fake-rpc-child.mjs", import.meta.url),
12 -);
14 -describe("PiRpcWorker smoke", () => {
15 - test("builds llmiterate worker invocation", () => {
16 - expect(
17 - workerArgs({
18 - sessionDir: "/state/sessions",
19 - model: "eldoria/wyvern",
20 - thinking: "high",
21 - }),
22 - ).toEqual([
23 - "--mode",
24 - "rpc",
25 - "--offline",
26 - "--session-dir",
27 - "/state/sessions",
28 - "--append-system-prompt",
29 - expect.stringContaining("llmiterate"),
30 - "--model",
31 - "eldoria/wyvern",
32 - "--thinking",
33 - "high",
34 - ]);
35 - });
37 - // Exhaustive protocol/error coverage lives in rpc-full.test.ts.
38 - test("runs prompt through JSON-RPC worker and forwards events", async () => {
39 - const events: RpcEvent[] = [];
40 - await withFakeWorker(
41 - (worker) => worker.runPrompt("do thing", "job name"),
42 - events,
43 - );
44 - expect(events.map((e) => e.type)).toEqual([
45 - "message_update",
46 - "tool_execution_start",
47 - "tool_execution_end",
48 - "agent_end",
49 - ]);
50 - });
51 -});
53 -async function withFakeWorker<T>(
54 - fn: (worker: PiRpcWorker) => Promise<T>,
55 - events: RpcEvent[],
56 -): Promise<T> {
57 - const root = mkdtempSync(join(tmpdir(), "llmiterate-rpc-"));
58 - const worker = new PiRpcWorker({
59 - cwd: root,
60 - sessionDir: join(root, "sessions"),
61 - invocation: {
62 - command: process.execPath,
63 - args: [fakeRpcScript, "ok", root],
64 - },
65 - onEvent: (event) => events.push(event),
66 - });
67 - try {
68 - return await fn(worker);
69 - } finally {
70 - await worker.dispose();
71 - await rm(root, {
72 - recursive: true,
73 - force: true,
74 - maxRetries: 20,
75 - retryDelay: 50,
76 - });
77 - }
78 -}

extensions/llmiterate/__tests__/ui.test.ts

Deleted
deleted file mode 100644
1 -import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 -import { describe, expect, test } from "vitest";
3 -import { defaultConfig, normalizeConfig, parseMarkerPrompts } from "../core";
4 -import type { LlmiterateRun } from "../types";
5 -import { renderLlmiterateStatus } from "../ui";
7 -interface UiCall {
8 - key: string;
9 - value: string | undefined;
12 -const theme = {
13 - fg: (_color: string, text: string) => text,
14 - bold: (text: string) => text,
15 -} as unknown as ExtensionContext["ui"]["theme"];
17 -describe("llmiterate UI", () => {
18 - test("status line states", () => {
19 - const calls: UiCall[] = [];
20 - const ctx = fakeContext({
21 - setStatus: (key, value) => calls.push({ key, value }),
22 - });
23 - const activeConfig = normalizeConfig({ include: ["src/**/*.ts"] });
25 - renderLlmiterateStatus(ctx, {
26 - watchErrors: 0,
27 - watchDirs: 0,
28 - queuedRuns: 0,
29 - });
30 - renderLlmiterateStatus(ctx, {
31 - config: defaultConfig(),
32 - watchErrors: 0,
33 - watchDirs: 0,
34 - queuedRuns: 0,
35 - });
36 - renderLlmiterateStatus(ctx, {
37 - config: activeConfig,
38 - lockError: "held",
39 - watchErrors: 0,
40 - watchDirs: 0,
41 - queuedRuns: 0,
42 - });
43 - renderLlmiterateStatus(ctx, {
44 - config: activeConfig,
45 - watchErrors: 2,
46 - watchDirs: 0,
47 - queuedRuns: 0,
48 - });
49 - renderLlmiterateStatus(ctx, {
50 - config: activeConfig,
51 - watchErrors: 0,
52 - watchDirs: 2,
53 - queuedRuns: 3,
54 - });
55 - renderLlmiterateStatus(ctx, {
56 - config: activeConfig,
57 - watchErrors: 0,
58 - watchDirs: 2,
59 - queuedRuns: 0,
60 - activeRun: sampleRun(),
61 - });
63 - expect(calls.map((c) => c.value)).toEqual([
64 - undefined,
65 - "llmiterate watching .",
66 - "llmiterate standby",
67 - "llmiterate 2 watch error(s)",
68 - "llmiterate queued 3",
69 - "llmiterate running src/main.ts:1",
70 - ]);
71 - });
72 -});
74 -function fakeContext(overrides: {
75 - setStatus?: (key: string, value: string | undefined) => void;
76 -}): ExtensionContext {
77 - return {
78 - hasUI: true,
79 - ui: {
80 - theme,
81 - setStatus: overrides.setStatus ?? (() => {}),
82 - },
83 - } as unknown as ExtensionContext;
86 -function sampleRun(): LlmiterateRun {
87 - const [block] = parseMarkerPrompts(
88 - "src/main.ts",
89 - "// llmiterate: implement foo and bar",
90 - );
91 - if (!block) throw new Error("expected llmiterate block");
92 - return {
93 - id: 1,
94 - block,
95 - projectFile: "src/main.ts",
96 - absoluteFile: "/tmp/project/src/main.ts",
97 - fullPrompt: "prompt",
98 - status: "running",
99 - queuedAt: 1,
100 - updatedAt: 2,
101 - assistantText: "I am editing the file now and will run tests afterwards.",
102 - toolText: "running edit",
103 - };

extensions/llmiterate/__tests__/watcher.test.ts

Deleted
deleted file mode 100644
1 -import {
2 - mkdirSync,
3 - mkdtempSync,
4 - renameSync,
5 - rmSync,
6 - utimesSync,
7 - writeFileSync,
8 -} from "node:fs";
9 -import { tmpdir } from "node:os";
10 -import { join } from "node:path";
11 -import { afterAll, describe, expect, test } from "vitest";
12 -import { compilePathFilter, normalizeConfig, toSlash } from "../core";
13 -import { ProjectWatcher } from "../watcher";
15 -const tempDirs: string[] = [];
16 -const watchers: ProjectWatcher[] = [];
18 -afterAll(() => {
19 - while (watchers.length) watchers.pop()?.stop();
20 - for (const dir of tempDirs.splice(0))
21 - rmSync(dir, { recursive: true, force: true });
22 -});
24 -function tempDir(): string {
25 - const dir = mkdtempSync(join(tmpdir(), "llmiterate-watcher-"));
26 - tempDirs.push(dir);
27 - return dir;
30 -describe.concurrent("ProjectWatcher integration", () => {
31 - test("default config scans normal files and excludes metadata dirs", () => {
32 - const root = tempDir();
33 - mkdirSync(join(root, "src"));
34 - mkdirSync(join(root, ".jj"));
35 - mkdirSync(join(root, ".local", "share", "Trash", "files"), {
36 - recursive: true,
37 - });
38 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: seen");
39 - writeFileSync(join(root, ".jj", "ignored.ts"), "// llmiterate: ignored");
40 - writeFileSync(
41 - join(root, ".local", "share", "Trash", "files", "ignored.ts"),
42 - "// llmiterate: ignored",
43 - );
45 - const config = normalizeConfig({ debounceMs: 10 });
46 - const seen: string[] = [];
47 - const watcher = new ProjectWatcher(
48 - root,
49 - config,
50 - compilePathFilter(config),
51 - (file) => seen.push(file),
52 - () => {},
53 - );
54 - watchers.push(watcher);
56 - expect(
57 - watcher.scanAll((file) => {
58 - seen.push(file);
59 - return 1;
60 - }),
61 - ).toBe(1);
62 - expect(seen.map((p) => toSlash(p.replace(root, "")))).toEqual([
63 - "/src/a.ts",
64 - ]);
65 - });
67 - test("default config starts filesystem watchers", async () => {
68 - const root = tempDir();
69 - mkdirSync(join(root, "src"));
71 - const config = normalizeConfig({ debounceMs: 10 });
72 - const seen: string[] = [];
73 - const watcher = new ProjectWatcher(
74 - root,
75 - config,
76 - compilePathFilter(config),
77 - (file) => seen.push(file),
78 - () => {},
79 - );
80 - watchers.push(watcher);
82 - watcher.start();
83 - writeFileSync(join(root, "src", "a.ts"), "// llmiterate: seen");
84 - await eventually(() => seen.some((p) => p.endsWith("a.ts")));
85 - expect(watcher.errorCount).toBe(0);
86 - });
88 - test("scanAll respects include whitelist and aggregates callback results", () => {
89 - const root = tempDir();
90 - mkdirSync(join(root, "src"));
91 - mkdirSync(join(root, "research"));
92 - writeFileSync(join(root, "src", "a.ts"), "LLM do it");
93 - writeFileSync(join(root, "src", "a.png"), "no");
94 - writeFileSync(join(root, "research", "b.ts"), "LLM ignore");
96 - const config = normalizeConfig({
97 - include: ["src/**/*.ts"],
98 - exclude: [],
99 - debounceMs: 10,
100 - });
101 - const seen: string[] = [];
102 - const watcher = new ProjectWatcher(
103 - root,
104 - config,
105 - compilePathFilter(config),
106 - (file) => seen.push(file),
107 - () => {},
108 - );
109 - watchers.push(watcher);
111 - const total = watcher.scanAll((file) => {
112 - seen.push(file);
113 - return 2;
114 - });
116 - expect(total).toBe(2);
117 - expect(seen.map((p) => toSlash(p.replace(root, "")))).toEqual([
118 - "/src/a.ts",
119 - ]);
120 - });
122 - test("start watches dirs without queuing old files", async () => {
123 - const root = tempDir();
124 - mkdirSync(join(root, "src"));
125 - const oldFile = join(root, "src", "old.ts");
126 - writeFileSync(oldFile, "// llmiterate: old");
127 - const future = new Date(Date.now() + 5000);
128 - utimesSync(oldFile, future, future);
129 - const config = normalizeConfig({
130 - include: ["src/**/*.ts"],
131 - exclude: [],
132 - debounceMs: 20,
133 - });
134 - const seen: string[] = [];
135 - const watcher = new ProjectWatcher(
136 - root,
137 - config,
138 - compilePathFilter(config),
139 - (file) => seen.push(file),
140 - () => {},
141 - );
142 - watchers.push(watcher);
144 - watcher.start();
145 - await eventually(() => watcher.watcherCount >= 2);
146 - expect(seen).toEqual([]);
147 - });
149 - test("watcher emits debounced file save events", async () => {
150 - const root = tempDir();
151 - mkdirSync(join(root, "src"));
152 - const config = normalizeConfig({
153 - include: ["**/*.ts"],
154 - exclude: [],
155 - debounceMs: 20,
156 - });
157 - const seen: string[] = [];
158 - const watcher = new ProjectWatcher(
159 - root,
160 - config,
161 - compilePathFilter(config),
162 - (file) => seen.push(file),
163 - () => {},
164 - );
165 - watchers.push(watcher);
167 - watcher.start();
168 - await eventually(() => watcher.watcherCount >= 2);
169 - writeFileSync(join(root, "src", "new.ts"), "LLM hello");
170 - await eventually(() => seen.some((p) => p.endsWith("new.ts")));
171 - });
173 - test("watcher ignores new files outside include whitelist", async () => {
174 - const root = tempDir();
175 - mkdirSync(join(root, "src"));
176 - mkdirSync(join(root, "research"));
177 - const config = normalizeConfig({
178 - include: ["src/**/*.ts"],
179 - exclude: [],
180 - debounceMs: 5,
181 - });
182 - const seen: string[] = [];
183 - const watcher = new ProjectWatcher(
184 - root,
185 - config,
186 - compilePathFilter(config),
187 - (file) => seen.push(file),
188 - () => {},
189 - );
190 - watchers.push(watcher);
192 - watcher.start();
193 - await eventually(() => watcher.watcherCount >= 2);
194 - writeFileSync(join(root, "research", "ignored.ts"), "LLM nope");
195 - await sleep(25);
196 - expect(seen).toEqual([]);
197 - writeFileSync(join(root, "src", "seen.ts"), "LLM hello");
198 - await eventually(() => seen.some((p) => p.endsWith("seen.ts")));
199 - });
201 - test("watcher notices files moved into new whitelisted directories", async () => {
202 - const root = tempDir();
203 - const config = normalizeConfig({
204 - include: ["nested/**/*.ts"],
205 - exclude: [],
206 - debounceMs: 20,
207 - });
208 - const seen: string[] = [];
209 - const watcher = new ProjectWatcher(
210 - root,
211 - config,
212 - compilePathFilter(config),
213 - (file) => seen.push(file),
214 - () => {},
215 - );
216 - watchers.push(watcher);
218 - watcher.start();
219 - mkdirSync(join(root, "nested"));
220 - await eventually(() => watcher.watcherCount >= 2);
221 - writeFileSync(join(root, "nested", "moved.ts"), "// llmiterate: hello");
222 - await eventually(() => seen.some((p) => p.endsWith("moved.ts")));
223 - });
225 - test("fs.watch atomic-save rename queues final path", async () => {
226 - const root = tempDir();
227 - mkdirSync(join(root, "src"));
228 - const config = normalizeConfig({
229 - include: ["src/**/*.ts"],
230 - exclude: [],
231 - debounceMs: 20,
232 - });
233 - const seen: string[] = [];
234 - const watcher = new ProjectWatcher(
235 - root,
236 - config,
237 - compilePathFilter(config),
238 - (file) => seen.push(file),
239 - () => {},
240 - );
241 - watchers.push(watcher);
243 - watcher.start();
244 - await eventually(() => watcher.watcherCount >= 2);
245 - writeFileSync(join(root, "src", "a.ts.tmp"), "// temp write");
246 - renameSync(join(root, "src", "a.ts.tmp"), join(root, "src", "a.ts"));
248 - await eventually(() => seen.some((p) => toSlash(p).endsWith("src/a.ts")));
249 - expect(seen.every((p) => !p.endsWith(".tmp"))).toBe(true);
250 - });
252 - test("fs.watch debounce collapses save bursts", async () => {
253 - const root = tempDir();
254 - mkdirSync(join(root, "src"));
255 - const config = normalizeConfig({
256 - include: ["src/**/*.ts"],
257 - exclude: [],
258 - debounceMs: 10,
259 - });
260 - const seen: string[] = [];
261 - const watcher = new ProjectWatcher(
262 - root,
263 - config,
264 - compilePathFilter(config),
265 - (file) => seen.push(file),
266 - () => {},
267 - );
268 - watchers.push(watcher);
270 - watcher.start();
271 - await eventually(() => watcher.watcherCount >= 2);
272 - const file = join(root, "src", "burst.ts");
273 - // Same-turn writes test debounce behavior without racing CI timer jitter.
274 - writeFileSync(file, "// llmiterate: one");
275 - writeFileSync(file, "// llmiterate: two");
276 - writeFileSync(file, "// llmiterate: three");
278 - await eventually(() => seen.some((p) => p.endsWith("burst.ts")));
279 - await sleep(30);
280 - expect(seen.filter((p) => p.endsWith("burst.ts"))).toHaveLength(1);
281 - });
283 - test("fs.watch removes deleted directory watchers", async () => {
284 - const root = tempDir();
285 - mkdirSync(join(root, "src", "gone"), { recursive: true });
286 - const config = normalizeConfig({
287 - include: ["src/**/*.ts"],
288 - exclude: [],
289 - debounceMs: 20,
290 - });
291 - const watcher = new ProjectWatcher(
292 - root,
293 - config,
294 - compilePathFilter(config),
295 - () => {},
296 - () => {},
297 - );
298 - watchers.push(watcher);
300 - watcher.start();
301 - await eventually(() => watcher.watcherCount >= 3);
302 - const before = watcher.watcherCount;
303 - rmSync(join(root, "src", "gone"), { recursive: true, force: true });
305 - await eventually(() => watcher.watcherCount < before);
306 - });
308 - test("respects .gitignore and .ignore during scan and watch", async () => {
309 - const root = tempDir();
310 - mkdirSync(join(root, "src", "ignored"), { recursive: true });
311 - mkdirSync(join(root, "logs"));
312 - writeFileSync(join(root, ".gitignore"), "logs/\n");
313 - writeFileSync(join(root, "src", ".ignore"), "ignored/\n*.tmp\n");
314 - writeFileSync(join(root, "logs", "a.ts"), "// llmiterate: ignored");
315 - writeFileSync(
316 - join(root, "src", "ignored", "b.ts"),
317 - "// llmiterate: ignored",
318 - );
319 - writeFileSync(join(root, "src", "c.tmp"), "// llmiterate: ignored");
320 - writeFileSync(join(root, "src", "ok.ts"), "// llmiterate: seen");
322 - const config = normalizeConfig({
323 - include: ["**/*"],
324 - exclude: [],
325 - debounceMs: 20,
326 - });
327 - const seen: string[] = [];
328 - const watcher = new ProjectWatcher(
329 - root,
330 - config,
331 - compilePathFilter(config),
332 - (file) => seen.push(file),
333 - () => {},
334 - );
335 - watchers.push(watcher);
337 - expect(
338 - watcher.scanAll((file) => {
339 - seen.push(file);
340 - return 1;
341 - }),
342 - ).toBe(1);
343 - expect(seen.map((p) => toSlash(p.replace(root, "")))).toEqual([
344 - "/src/ok.ts",
345 - ]);
347 - seen.length = 0;
348 - watcher.start();
349 - await sleep(40);
350 - writeFileSync(join(root, "logs", "new.ts"), "// llmiterate: ignored");
351 - writeFileSync(
352 - join(root, "src", "ignored", "new.ts"),
353 - "// llmiterate: ignored",
354 - );
355 - writeFileSync(join(root, "src", "ok2.ts"), "// llmiterate: seen");
356 - await eventually(() => seen.some((p) => p.endsWith("ok2.ts")));
357 - expect(
358 - seen.every((p) => !p.includes("ignored") && !p.includes("logs")),
359 - ).toBe(true);
360 - });
362 - test("fs.watch new ignore rule unwatches newly ignored subtree", async () => {
363 - const root = tempDir();
364 - mkdirSync(join(root, "src", "noisy"), { recursive: true });
365 - const config = normalizeConfig({
366 - include: ["**/*"],
367 - exclude: [],
368 - debounceMs: 20,
369 - });
370 - const seen: string[] = [];
371 - const watcher = new ProjectWatcher(
372 - root,
373 - config,
374 - compilePathFilter(config),
375 - (file) => seen.push(file),
376 - () => {},
377 - );
378 - watchers.push(watcher);
380 - watcher.start();
381 - await eventually(() => watcher.watcherCount >= 3);
382 - const before = watcher.watcherCount;
384 - writeFileSync(join(root, ".gitignore"), "src/noisy/\n");
385 - await eventually(() => watcher.watcherCount < before);
387 - writeFileSync(
388 - join(root, "src", "noisy", "ignored.ts"),
389 - "// llmiterate: ignored",
390 - );
391 - await sleep(25);
392 - expect(seen).toEqual([]);
393 - });
395 - test("fs.watch caps watcher count", async () => {
396 - const root = tempDir();
397 - for (let i = 0; i < 8; i++)
398 - mkdirSync(join(root, "dir", String(i)), { recursive: true });
399 - const config = normalizeConfig({
400 - include: ["**/*"],
401 - exclude: [],
402 - debounceMs: 20,
403 - maxWatchDirs: 4,
404 - });
405 - const watcher = new ProjectWatcher(
406 - root,
407 - config,
408 - compilePathFilter(config),
409 - () => {},
410 - () => {},
411 - );
412 - watchers.push(watcher);
414 - watcher.start();
415 - await eventually(() => watcher.errorCount === 1);
416 - expect(watcher.watcherCount).toBeLessThanOrEqual(4);
417 - expect(watcher.errorCount).toBe(1);
418 - });
420 - test("fs.watch does not watch excluded subtrees", async () => {
421 - const root = tempDir();
422 - mkdirSync(join(root, "src"));
423 - mkdirSync(join(root, "node_modules", "pkg"), { recursive: true });
424 - const config = normalizeConfig({
425 - include: ["**/*.ts"],
426 - exclude: ["node_modules/**"],
427 - debounceMs: 20,
428 - });
429 - const seen: string[] = [];
430 - const watcher = new ProjectWatcher(
431 - root,
432 - config,
433 - compilePathFilter(config),
434 - (file) => seen.push(file),
435 - () => {},
436 - );
437 - watchers.push(watcher);
439 - watcher.start();
440 - await eventually(() => watcher.watcherCount >= 2);
441 - writeFileSync(
442 - join(root, "node_modules", "pkg", "ignored.ts"),
443 - "// llmiterate: ignored",
444 - );
445 - await sleep(25);
446 - expect(seen).toEqual([]);
447 - expect(watcher.watcherCount).toBeLessThan(4);
448 - });
449 -});
451 -function sleep(ms: number): Promise<void> {
452 - return new Promise((resolve) => setTimeout(resolve, ms));
455 -async function eventually(predicate: () => boolean): Promise<void> {
456 - const deadline = Date.now() + 1500;
457 - while (Date.now() < deadline) {
458 - if (predicate()) return;
459 - await sleep(5);
460 - }
461 - expect(predicate()).toBe(true);

extensions/llmiterate/config.ts

Deleted
deleted file mode 100644
1 -import * as fs from "node:fs";
2 -import * as path from "node:path";
3 -import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
4 -import {
5 - COMMENT_PREFIXES_BY_EXTENSION,
6 - DEFAULT_DEBOUNCE_MS,
7 - DEFAULT_EXCLUDE,
8 - DEFAULT_INCLUDE,
9 - DEFAULT_MAX_FILE_BYTES,
10 - DEFAULT_MAX_WATCH_DIRS,
11 - DEFAULT_TIMEOUT_MS,
12 -} from "./constants";
13 -import { isObject, positiveInt, stringArray } from "./util";
15 -export type ThinkingLevel =
16 - | "off"
17 - | "minimal"
18 - | "low"
19 - | "medium"
20 - | "high"
21 - | "xhigh"
22 - | "max";
23 -export type NotifyPolicy = "off" | "errors" | "done" | "all";
25 -export interface LlmiterateConfig {
26 - enabled: boolean;
27 - include: string[];
28 - exclude: string[];
29 - debounceMs: number;
30 - maxFileBytes: number;
31 - timeoutMs: number;
32 - maxWatchDirs: number;
33 - commentPrefixes: Record<string, string[]>;
34 - model?: string;
35 - thinking?: ThinkingLevel;
36 - notify: NotifyPolicy;
39 -export function defaultConfig(): LlmiterateConfig {
40 - return {
41 - enabled: true,
42 - include: [...DEFAULT_INCLUDE],
43 - exclude: [...DEFAULT_EXCLUDE],
44 - debounceMs: DEFAULT_DEBOUNCE_MS,
45 - maxFileBytes: DEFAULT_MAX_FILE_BYTES,
46 - timeoutMs: DEFAULT_TIMEOUT_MS,
47 - maxWatchDirs: DEFAULT_MAX_WATCH_DIRS,
48 - commentPrefixes: clonePrefixMap(COMMENT_PREFIXES_BY_EXTENSION),
49 - notify: "errors",
50 - };
53 -export function normalizeConfig(raw: unknown): LlmiterateConfig {
54 - const fallback = defaultConfig();
55 - if (!isObject(raw)) return fallback;
57 - return {
58 - enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
59 - include: stringArray(raw.include, fallback.include),
60 - exclude: mergeExclude(raw.exclude),
61 - debounceMs: positiveInt(raw.debounceMs, fallback.debounceMs),
62 - maxFileBytes: positiveInt(raw.maxFileBytes, fallback.maxFileBytes),
63 - timeoutMs: positiveInt(raw.timeoutMs, fallback.timeoutMs),
64 - maxWatchDirs: positiveInt(raw.maxWatchDirs, fallback.maxWatchDirs),
65 - commentPrefixes: mergeCommentPrefixes(raw.commentPrefixes),
66 - model: optionalString(raw.model),
67 - thinking: thinkingLevel(raw.thinking),
68 - notify: notifyPolicy(raw.notify, fallback.notify),
69 - };
72 -export function loadConfig(cwd: string): LlmiterateConfig {
73 - const global = readSettingsNamespace(
74 - path.join(getAgentDir(), "settings.json"),
75 - );
76 - const project = readSettingsNamespace(
77 - path.join(cwd, CONFIG_DIR_NAME, "settings.json"),
78 - );
79 - return normalizeConfig({ ...global, ...project });
82 -function readSettingsNamespace(settingsPath: string): Record<string, unknown> {
83 - try {
84 - const parsed = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
85 - return isObject(parsed) && isObject(parsed.llmiterate)
86 - ? parsed.llmiterate
87 - : {};
88 - } catch {
89 - return {};
90 - }
93 -function optionalString(value: unknown): string | undefined {
94 - return typeof value === "string" && value.trim() ? value.trim() : undefined;
97 -function thinkingLevel(value: unknown): ThinkingLevel | undefined {
98 - return value === "off" ||
99 - value === "minimal" ||
100 - value === "low" ||
101 - value === "medium" ||
102 - value === "high" ||
103 - value === "xhigh" ||
104 - value === "max"
105 - ? value
106 - : undefined;
109 -function notifyPolicy(value: unknown, fallback: NotifyPolicy): NotifyPolicy {
110 - return value === "off" ||
111 - value === "errors" ||
112 - value === "done" ||
113 - value === "all"
114 - ? value
115 - : fallback;
118 -function mergeExclude(value: unknown): string[] {
119 - return [...new Set([...DEFAULT_EXCLUDE, ...stringArray(value, [])])];
122 -function mergeCommentPrefixes(value: unknown): Record<string, string[]> {
123 - const merged = clonePrefixMap(COMMENT_PREFIXES_BY_EXTENSION);
124 - if (!isObject(value)) return merged;
126 - for (const [rawKey, rawPrefixes] of Object.entries(value)) {
127 - const key = normalizeExtensionKey(rawKey);
128 - if (!key) continue;
129 - merged[key] = normalizeCommentPrefixes([
130 - ...(merged[key] ?? []),
131 - ...stringArray(rawPrefixes, []),
132 - ]);
133 - }
134 - return merged;
137 -function clonePrefixMap(
138 - value: Record<string, string[]>,
139 -): Record<string, string[]> {
140 - return Object.fromEntries(
141 - Object.entries(value).map(([key, prefixes]) => [
142 - key,
143 - normalizeCommentPrefixes(prefixes),
144 - ]),
145 - );
148 -function normalizeExtensionKey(key: string): string {
149 - return key.trim().toLowerCase().replace(/^\./, "");
152 -function normalizeCommentPrefixes(prefixes: string[]): string[] {
153 - return [...new Set(prefixes.map((p) => p.trim()).filter(Boolean))].sort(
154 - (a, b) => b.length - a.length,
155 - );

extensions/llmiterate/constants.ts

Deleted
deleted file mode 100644
1 -export const DEFAULT_DEBOUNCE_MS = 3000;
2 -export const DEFAULT_MAX_FILE_BYTES = 1_000_000;
3 -export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
4 -export const DEFAULT_MAX_WATCH_DIRS = 10_000;
5 -export const DEFAULT_INCLUDE = ["**/*"];
6 -export const DEFAULT_EXCLUDE = [
7 - "**/.git/**",
8 - "**/.hg/**",
9 - "**/.svn/**",
10 - "**/.jj/**",
11 - "**/.pi/**",
12 - "**/node_modules/**",
13 - "**/vendor/**",
14 - "**/dist/**",
15 - "**/build/**",
16 - "**/coverage/**",
17 - "**/target/**",
18 - "**/.cache/**",
19 - "**/.local/**",
20 - "**/.bun/**",
21 - "**/.npm/**",
22 - "**/.cargo/**",
23 - "**/.rustup/**",
24 - "**/.gradle/**",
25 - "**/.m2/**",
26 - "**/.steam/**",
27 - "**/.next/**",
28 - "**/.gitignore",
29 - "**/.ignore",
30 - ".gitignore",
31 - ".ignore",
32 -];
33 -export const MARKER = "llmiterate:";
34 -export const DISABLE_MARKER = "!llmiterate";
35 -export const COMMENT_PREFIXES_BY_EXTENSION: Record<string, string[]> = {
36 - c: ["//", "///", "/*", "/**"],
37 - cc: ["//", "///", "/*", "/**"],
38 - cpp: ["//", "///", "/*", "/**"],
39 - cs: ["//", "///", "/*", "/**"],
40 - cts: ["//", "///", "/*", "/**"],
41 - go: ["//", "///", "/*", "/**"],
42 - h: ["//", "///", "/*", "/**"],
43 - hpp: ["//", "///", "/*", "/**"],
44 - java: ["//", "///", "/*", "/**"],
45 - js: ["//", "///", "/*", "/**"],
46 - jsx: ["//", "///", "/*", "/**"],
47 - kt: ["//", "///", "/*", "/**"],
48 - kts: ["//", "///", "/*", "/**"],
49 - mts: ["//", "///", "/*", "/**"],
50 - php: ["//", "///", "/*", "/**"],
51 - rs: ["//", "///", "//!", "/*", "/**"],
52 - scala: ["//", "///", "/*", "/**"],
53 - swift: ["//", "///", "/*", "/**"],
54 - ts: ["//", "///", "/*", "/**"],
55 - tsx: ["//", "///", "/*", "/**"],
56 - css: ["/*", "/**"],
57 - scss: ["//", "/*", "/**"],
58 - less: ["//", "/*", "/**"],
59 - py: ["#"],
60 - sh: ["#"],
61 - bash: ["#"],
62 - zsh: ["#"],
63 - fish: ["#"],
64 - rb: ["#"],
65 - pl: ["#"],
66 - pm: ["#"],
67 - r: ["#"],
68 - toml: ["#"],
69 - yaml: ["#"],
70 - yml: ["#"],
71 - dockerfile: ["#"],
72 - md: ["<!--"],
73 - mdx: ["<!--"],
74 - html: ["<!--"],
75 - htm: ["<!--"],
76 - xml: ["<!--"],
77 - sql: ["--"],
78 - lua: ["--"],
79 - hs: ["--"],
80 - erl: ["%"],
81 - ex: ["#"],
82 - exs: ["#"],
83 - lisp: [";", ";;", ";;;"],
84 - el: [";", ";;", ";;;"],
85 - clj: [";", ";;", ";;;"],
86 - scm: [";", ";;", ";;;"],
87 - tex: ["%", "%%"],
88 - f: ["!"],
89 - f90: ["!"],
90 -};
91 -export const STORE_NAMESPACE = "llmiterate";
92 -export const STATE_FILE = "state.json";
93 -export const APP_STATE_DIR = "pi";

extensions/llmiterate/core.ts

Deleted
deleted file mode 100644
1 -export * from "./config";
2 -export * from "./constants";
3 -export * from "./parser";
4 -export * from "./path-filter";
5 -export * from "./prompt";
6 -export * from "./state";
7 -export * from "./util";

extensions/llmiterate/gitignore.ts

Deleted
deleted file mode 100644
1 -/** Single test function compiled from one gitignore pattern. */
2 -type TestFn = (path: string) => boolean;
4 -interface Rule {
5 - /** True if this rule negates a previous match. */
6 - negative: boolean;
7 - /** True if the original pattern ended with `/`. */
8 - directoryOnly: boolean;
9 - /** Compiled matcher for this rule. */
10 - test: TestFn;
13 -/** Cache-key prefixes to avoid magic strings. */
14 -const CACHE_DIR = "d:";
15 -const CACHE_FILE = "f:";
17 -/** Characters that have special meaning in gitignore globs. */
18 -const GLOB_SPECIAL = new Set<string>(["*", "?", "[", "\\"]);
20 -/** Characters that need escaping in a JavaScript RegExp. */
21 -const REGEX_META = new Set<string>(".*+?^${}()|[]\\".split(""));
23 -/**
24 - * A lightweight gitignore matcher.
25 - *
26 - * Parses `.gitignore`/`.ignore` rules line-by-line, compiles them to test
27 - * functions, and checks paths against them. Rules are evaluated in order;
28 - * negation (`!`) flips the current state.
29 - *
30 - * Parent-directory short-circuit: if any ancestor directory is ignored, every
31 - * path beneath it is also ignored (matching git behaviour).
32 - *
33 - * Results are cached per `(path, isDir)` pair so repeated checks are O(1).
34 - */
35 -export class GitIgnoreMatcher {
36 - private readonly rules: Rule[] = [];
37 - private readonly cache = new Map<string, boolean>();
39 - /**
40 - * Parse a multi-line gitignore source and append the resulting rules.
41 - * @param source Raw file contents (CRLF or LF line endings are accepted).
42 - * @returns `this` for chaining.
43 - */
44 - add(source: string): this {
45 - for (const line of source.split(/\r?\n/)) {
46 - const rule = parseRule(line);
47 - if (rule) this.rules.push(rule);
48 - }
49 - return this;
50 - }
52 - /**
53 - * Check whether a path is ignored.
54 - *
55 - * @param inputPath Slash-separated path. A trailing `/` indicates a
56 - * directory, which matters for patterns ending with `/`.
57 - */
58 - ignores(inputPath: string): boolean {
59 - const isDir = inputPath.endsWith("/");
61 - // If any parent directory is ignored, the child is too.
62 - let slash = inputPath.lastIndexOf("/", inputPath.length - 2);
63 - while (slash > 0) {
64 - if (this._testCached(inputPath.slice(0, slash + 1), true)) return true;
65 - slash = inputPath.lastIndexOf("/", slash - 1);
66 - }
68 - return this._testCached(inputPath, isDir);
69 - }
71 - private _testCached(path: string, isDir: boolean): boolean {
72 - const key = isDir ? CACHE_DIR + path : CACHE_FILE + path;
73 - const cached = this.cache.get(key);
74 - if (cached !== undefined) return cached;
75 - const result = this._test(path, isDir);
76 - this.cache.set(key, result);
77 - return result;
78 - }
80 - private _test(path: string, isDir: boolean): boolean {
81 - let ignored = false;
82 - for (const rule of this.rules) {
83 - if (rule.directoryOnly && !isDir) continue;
84 - if (rule.test(path)) {
85 - ignored = !rule.negative;
86 - }
87 - }
88 - return ignored;
89 - }
92 -/* ── Parsing ─────────────────────────────────────────────── */
94 -function parseRule(rawLine: string): Rule | null {
95 - // Skip blank lines and comments.
96 - const line = rawLine.trimStart();
97 - if (!line || line[0] === "#") return null;
99 - // Negation.
100 - let pattern = line;
101 - let negative = false;
102 - if (pattern[0] === "!") {
103 - negative = true;
104 - pattern = pattern.slice(1);
105 - }
107 - // Leading escaped `!` or `#`.
108 - if (pattern.startsWith("\\!")) pattern = "!" + pattern.slice(2);
109 - if (pattern.startsWith("\\#")) pattern = "#" + pattern.slice(2);
111 - // Strip unescaped trailing spaces.
112 - pattern = stripTrailingSpaces(pattern);
114 - // Directory-only flag (trailing `/`).
115 - const directoryOnly = pattern.endsWith("/");
116 - if (directoryOnly) pattern = pattern.slice(0, -1);
118 - // Invalid patterns that never match.
119 - if (pattern.endsWith("\\")) return null;
120 - if (!pattern || pattern === "." || pattern === "..") return null;
121 - if (pattern.startsWith("../") || pattern.startsWith("./")) return null;
123 - const test = compileTest(pattern, directoryOnly);
124 - return test ? { negative, directoryOnly, test } : null;
127 -/** Remove spaces at the end of a pattern unless preceded by `\`. */
128 -function stripTrailingSpaces(s: string): string {
129 - let end = s.length;
130 - while (end > 0) {
131 - if (s[end - 1] !== " ") break;
132 - if (end > 1 && s[end - 2] === "\\") break; // escaped space
133 - end--;
134 - }
135 - return end === s.length ? s : s.slice(0, end);
138 -/* ── Pattern analysis & fast-path compilation ────────────── */
140 -interface PatternInfo {
141 - /** Leading `/` was stripped. */
142 - anchored: boolean;
143 - /** Contains at least one `/`. */
144 - hasSlash: boolean;
145 - /** Middle-slash pattern → relative to .gitignore dir only. */
146 - isRelative: boolean;
149 -function analyzePattern(raw: string): { pattern: string; info: PatternInfo } {
150 - let pattern = raw;
151 - const anchored = pattern[0] === "/";
152 - if (anchored) pattern = pattern.slice(1);
154 - const hasSlash = pattern.includes("/");
155 - const isRelative = hasSlash && !anchored && !pattern.startsWith("**/");
157 - return { pattern, info: { anchored, hasSlash, isRelative } };
160 -/** Return the basename (last path component) of `p`. */
161 -function basenameOf(p: string): string {
162 - const i = p.lastIndexOf("/");
163 - return i >= 0 ? p.slice(i + 1) : p;
166 -/** True if `s` contains any glob meta-character (`* ? [ \`). */
167 -function hasSpecialChars(s: string): boolean {
168 - for (let i = 0; i < s.length; i++) {
169 - if (GLOB_SPECIAL.has(s[i])) return true;
170 - }
171 - return false;
174 -/**
175 - * Compile a single gitignore pattern into a test function.
176 - *
177 - * Several fast paths avoid RegExp construction for common patterns:
178 - * exact names, suffix (`*.ext`), prefix (`foo*`), and anchored literals.
179 - */
180 -function compileTest(
181 - rawPattern: string,
182 - directoryOnly: boolean,
183 -): TestFn | null {
184 - const { pattern, info } = analyzePattern(rawPattern);
185 - const { anchored, isRelative } = info;
187 - // Fast path: literal patterns with no glob chars.
188 - if (!hasSpecialChars(pattern)) {
189 - return compileLiteral(pattern, anchored, isRelative, directoryOnly);
190 - }
192 - // Fast path: `*.ext` (no slash, no other specials).
193 - if (
194 - !anchored &&
195 - !info.hasSlash &&
196 - pattern.startsWith("*.") &&
197 - !hasSpecialChars(pattern.slice(2))
198 - ) {
199 - const suffix = pattern.slice(1); // includes the dot
200 - return (p) => basenameOf(p).endsWith(suffix);
201 - }
203 - // Fast path: `foo*` (no slash, trailing star only).
204 - if (
205 - !anchored &&
206 - !info.hasSlash &&
207 - pattern.endsWith("*") &&
208 - pattern.indexOf("*") === pattern.length - 1 &&
209 - !hasSpecialChars(pattern.slice(0, -1))
210 - ) {
211 - const prefix = pattern.slice(0, -1);
212 - return (p) => basenameOf(p).startsWith(prefix);
213 - }
215 - // Fallback: build a RegExp.
216 - const regex = buildRegex(pattern, anchored, isRelative);
217 - return regex ? (p) => regex.test(p) : null;
220 -/** Compile a literal (no glob) pattern. */
221 -function compileLiteral(
222 - pattern: string,
223 - anchored: boolean,
224 - isRelative: boolean,
225 - directoryOnly: boolean,
226 -): TestFn {
227 - if (directoryOnly) {
228 - if (anchored || isRelative) {
229 - return (p) => p === `${pattern}/` || p.startsWith(`${pattern}/`);
230 - }
231 - return (p) => p === `${pattern}/` || p.endsWith(`/${pattern}/`);
232 - }
234 - if (anchored || isRelative) {
235 - return (p) => {
236 - const norm = p.endsWith("/") ? p.slice(0, -1) : p;
237 - return norm === pattern || norm.startsWith(`${pattern}/`);
238 - };
239 - }
241 - return (p) => {
242 - const norm = p.endsWith("/") ? p.slice(0, -1) : p;
243 - return norm === pattern || norm.endsWith(`/${pattern}`);
244 - };
247 -/* ── RegExp builder ──────────────────────────────────────── */
249 -function buildRegex(
250 - pattern: string,
251 - anchored: boolean,
252 - isRelative: boolean,
253 -): RegExp | null {
254 - let src = "";
255 - let i = 0;
256 - while (i < pattern.length) {
257 - const ch = pattern[i];
259 - if (ch === "\\") {
260 - const next = pattern[i + 1];
261 - if (next) {
262 - src += escapeRegex(next);
263 - i += 2;
264 - continue;
265 - }
266 - i++;
267 - continue;
268 - }
270 - if (ch === "*") {
271 - if (pattern[i + 1] === "*") {
272 - if (pattern[i + 2] === "/") {
273 - src += "(?:.*\\/)?";
274 - i += 3;
275 - continue;
276 - }
277 - if (i + 2 === pattern.length) {
278 - src += ".+"; // trailing ** matches at least one char inside
279 - i += 2;
280 - continue;
281 - }
282 - src += "[^/]*";
283 - i++;
284 - continue;
285 - }
286 - src += "[^/]*";
287 - i++;
288 - continue;
289 - }
291 - if (ch === "?") {
292 - src += "[^/]";
293 - i++;
294 - continue;
295 - }
297 - if (ch === "[") {
298 - const segment = parseCharClass(pattern, i);
299 - if (segment === null) {
300 - src += "\\[";
301 - i++;
302 - continue;
303 - }
304 - src += segment;
305 - i = pattern.indexOf("]", i + 1) + 1;
306 - continue;
307 - }
309 - src += escapeRegex(ch);
310 - i++;
311 - }
313 - if (!src) return null;
315 - let body: string;
316 - if (anchored || isRelative) {
317 - body = `^${src}(?=$|/)`;
318 - } else if (pattern.includes("/")) {
319 - body = `^(?:.*/)?${src}(?=$|/)`;
320 - } else {
321 - body = `^(?:[^/]*/)??${src}(?=$|/)`;
322 - }
324 - return new RegExp(body);
327 -/**
328 - * Parse a gitignore character class `[...]` into its regex equivalent.
329 - *
330 - * Handles negation (`[!...]` → `[^...]`) and sanitizes invalid ASCII
331 - * ranges (e.g. `[z-a]` is silently dropped).
332 - *
333 - * @returns The regex segment (including surrounding brackets) or `null`
334 - * if the closing `]` was not found.
335 - */
336 -function parseCharClass(pattern: string, openIndex: number): string | null {
337 - const close = pattern.indexOf("]", openIndex + 1);
338 - if (close === -1) return null;
340 - let content = pattern.slice(openIndex + 1, close);
342 - // Sanitize out-of-order ASCII ranges.
343 - content = content.replace(/([0-z])-([0-z])/g, (m, a, b) =>
344 - a.charCodeAt(0) <= b.charCodeAt(0) ? m : "",
345 - );
347 - // Gitignore uses `!` for negation; regex uses `^`.
348 - if (content[0] === "!") {
349 - content = "^" + content.slice(1);
350 - }
352 - return `[${content}]`;
355 -/** Escape a single character for use in a JavaScript RegExp. */
356 -function escapeRegex(ch: string): string {
357 - return REGEX_META.has(ch) ? `\\${ch}` : ch;

extensions/llmiterate/index.ts

Deleted
deleted file mode 100644
1 -import * as fs from "node:fs";
2 -import * as path from "node:path";
3 -import type {
4 - ExtensionAPI,
5 - ExtensionCommandContext,
6 - ExtensionContext,
7 -} from "@earendil-works/pi-coding-agent";
8 -import { type LlmiterateConfig, loadConfig, type NotifyPolicy } from "./config";
9 -import { acquireLock, type LockHandle, realPath, releaseLock } from "./lock";
10 -import { openInEditor, renderLatestSessionLog } from "./log";
11 -import {
12 - isLlmiterateDisabled,
13 - type MarkerPrompt,
14 - parseMarkerPrompts,
15 -} from "./parser";
16 -import {
17 - type CompiledPathFilter,
18 - compilePathFilter,
19 - globToRegExp,
20 - projectStoreDir,
21 - shouldIncludeCompiledPath,
22 -} from "./path-filter";
23 -import { buildAgentPrompt } from "./prompt";
24 -import { LLMITERATE_WORKER_ENV, PiRpcWorker } from "./rpc";
25 -import {
26 - emptyState,
27 - type LlmiterateState,
28 - loadState,
29 - type MarkerRunState,
30 - saveState,
31 -} from "./state";
32 -import type {
33 - LlmiterateRun,
34 - RpcAssistantMessageEvent,
35 - RpcEvent,
36 - RpcMessage,
37 - RpcTextPart,
38 - RpcToolResult,
39 -} from "./types";
40 -import { renderLlmiterateStatus } from "./ui";
41 -import { previewText, toSlash } from "./util";
42 -import { ProjectWatcher } from "./watcher";
44 -interface WatchRuntime {
45 - root: string;
46 - cwd: string;
47 - config: LlmiterateConfig;
48 - pathFilter: CompiledPathFilter;
49 - storeDir: string;
50 - state: LlmiterateState;
51 - watcher?: ProjectWatcher;
52 - lock?: LockHandle;
53 - lockError?: string;
56 -interface ScannedFile {
57 - runtime: WatchRuntime;
58 - projectRel: string;
59 - text: string;
62 -type WorkerOptions = ConstructorParameters<typeof PiRpcWorker>[0];
63 -type WorkerFactory = (options: WorkerOptions) => PiRpcWorker;
64 -type WatcherFactory = (
65 - root: string,
66 - config: LlmiterateConfig,
67 - pathFilter: CompiledPathFilter,
68 - onFileReady: (absolutePath: string) => void,
69 - onError: () => void,
70 -) => ProjectWatcher;
72 -export interface LlmiterateExtensionDeps {
73 - env?: NodeJS.ProcessEnv;
74 - now?: () => number;
75 - makeWorker?: WorkerFactory;
76 - makeWatcher?: WatcherFactory;
77 - openEditor?: (file: string, env?: NodeJS.ProcessEnv) => string | undefined;
80 -const STATE_PROMPT_PREVIEW_CHARS = 120;
81 -const ERROR_PREVIEW_CHARS = 160;
82 -const COMMAND_USAGE = "Usage: /llmiterate [on|off|status|log|explain <path>]";
83 -const COMPLETED_COMMANDS = ["on", "off", "status", "log", "explain"] as const;
85 -export function createLlmiterateExtension(deps: LlmiterateExtensionDeps = {}) {
86 - return function llmiterate(pi: ExtensionAPI) {
87 - const env = deps.env ?? process.env;
88 - if (env[LLMITERATE_WORKER_ENV] === "1") return;
89 - new LlmiterateController(pi, deps, env).register();
90 - };
93 -export default createLlmiterateExtension();
95 -class LlmiterateController {
96 - private runtime?: WatchRuntime;
97 - private sessionCtx?: ExtensionContext;
98 - private nextRunId = 1;
99 - private activeRunId?: number;
100 - private activeJob = false;
101 - private rpcWorker?: PiRpcWorker;
102 - private readonly runs: LlmiterateRun[] = [];
103 - private readonly agentModifiedFiles = new Map<string, number>();
105 - private readonly now: () => number;
106 - private readonly makeWorker: WorkerFactory;
107 - private readonly makeWatcher: WatcherFactory;
108 - private readonly openEditor: (
109 - file: string,
110 - env?: NodeJS.ProcessEnv,
111 - ) => string | undefined;
113 - constructor(
114 - private readonly pi: ExtensionAPI,
115 - deps: LlmiterateExtensionDeps,
116 - private readonly env: NodeJS.ProcessEnv,
117 - ) {
118 - this.now = deps.now ?? (() => Date.now());
119 - this.makeWorker =
120 - deps.makeWorker ?? ((options) => new PiRpcWorker(options));
121 - this.makeWatcher =
122 - deps.makeWatcher ??
123 - ((root, config, pathFilter, onFileReady, onError) =>
124 - new ProjectWatcher(root, config, pathFilter, onFileReady, onError));
125 - this.openEditor = deps.openEditor ?? openInEditor;
126 - }
128 - register(): void {
129 - this.pi.on("session_start", async (_event, ctx) =>
130 - this.onSessionStart(ctx),
131 - );
132 - this.pi.on("session_shutdown", async () => this.onSessionShutdown());
133 - this.pi.registerCommand("llmiterate", {
134 - description:
135 - "Toggle llmiterate for current cwd. Args: on | off | status | log | explain <path>",
136 - getArgumentCompletions: (prefix: string) => {
137 - if (prefix.trimStart().includes(" ")) return null;
138 - const items = COMPLETED_COMMANDS.filter((command) =>
139 - command.startsWith(prefix.trimStart()),
140 - ).map((command) => ({ value: command, label: command }));
141 - return items.length ? items : null;
142 - },
143 - handler: async (args, ctx) => {
144 - this.runCommand(args, ctx);
145 - this.updateUi(ctx);
146 - },
147 - });
148 - }
150 - private onSessionStart(ctx: ExtensionContext): void {
151 - this.sessionCtx = ctx;
152 - this.updateUi(ctx);
153 - }
155 - private onSessionShutdown(): void {
156 - this.stop();
157 - this.updateUi(this.sessionCtx);
158 - this.sessionCtx = undefined;
159 - this.activeRunId = undefined;
160 - }
162 - private runCommand(args: string, ctx: ExtensionCommandContext): void {
163 - const { command, rest } = parseCommandArgs(args);
164 - switch (command) {
165 - case "":
166 - this.toggleCommand(ctx);
167 - return;
168 - case "on":
169 - this.onCommand(ctx);
170 - return;
171 - case "off":
172 - this.offCommand(ctx);
173 - return;
174 - case "status":
175 - this.statusCommand(ctx);
176 - return;
177 - case "log":
178 - this.logCommand(ctx);
179 - return;
180 - case "explain":
181 - this.explainCommand(rest, ctx);
182 - return;
183 - case "scan":
184 - this.scanCommand(ctx);
185 - return;
186 - case "forget":
187 - this.forgetCommand(ctx);
188 - return;
189 - case "reload":
190 - this.reloadCommand(ctx);
191 - return;
192 - default:
193 - ctx.ui.notify(COMMAND_USAGE, "warning");
194 - }
195 - }
197 - private toggleCommand(ctx: ExtensionCommandContext): void {
198 - if (this.runtime) this.offCommand(ctx);
199 - else this.onCommand(ctx);
200 - }
202 - private onCommand(ctx: ExtensionCommandContext): void {
203 - if (this.runtime && !this.runtime.lockError) {
204 - this.warmWorker();
205 - ctx.ui.notify(`llmiterate already on: ${this.runtime.root}`, "info");
206 - return;
207 - }
209 - this.start(ctx.cwd);
210 - if (!this.runtime) return;
211 - if (!this.runtime.config.enabled) {
212 - ctx.ui.notify("llmiterate disabled by config", "warning");
213 - this.stop();
214 - return;
215 - }
216 - if (this.notifyIfStandby(ctx)) return;
217 - this.warmWorker();
219 - const count = this.scanAll();
220 - ctx.ui.notify(
221 - `llmiterate on: ${this.runtime.root}${count ? `; queued ${count}` : ""}`,
222 - "info",
223 - );
224 - }
226 - private offCommand(ctx: ExtensionCommandContext): void {
227 - if (!this.runtime) {
228 - ctx.ui.notify("llmiterate already off", "info");
229 - return;
230 - }
232 - this.stop();
233 - ctx.ui.notify("llmiterate off", "info");
234 - }
236 - private scanCommand(ctx: ExtensionCommandContext): void {
237 - if (!this.runtime) {
238 - ctx.ui.notify("llmiterate off; run /llmiterate on", "warning");
239 - return;
240 - }
241 - if (this.notifyIfStandby(ctx)) return;
243 - const count = this.scanAll();
244 - ctx.ui.notify(`llmiterate scan queued ${count} new prompt(s)`, "info");
245 - }
247 - private forgetCommand(ctx: ExtensionCommandContext): void {
248 - if (this.notifyIfStandby(ctx)) return;
250 - if (this.runtime) {
251 - this.runtime.state = emptyState();
252 - this.persistState(this.runtime);
253 - }
254 - this.stopWorker();
255 - this.runs.length = 0;
256 - this.activeRunId = undefined;
257 - ctx.ui.notify("llmiterate forgot run state", "info");
258 - }
260 - private reloadCommand(ctx: ExtensionCommandContext): void {
261 - if (!this.runtime) {
262 - ctx.ui.notify("llmiterate off; run /llmiterate on", "warning");
263 - return;
264 - }
265 - const cwd = this.runtime.cwd;
266 - this.start(cwd);
267 - if (!this.notifyIfStandby(ctx)) this.warmWorker();
268 - ctx.ui.notify("llmiterate config/watcher reloaded", "info");
269 - }
271 - private statusCommand(ctx: ExtensionCommandContext): void {
272 - ctx.ui.notify(this.statusText(ctx.cwd), "info");
273 - }
275 - private logCommand(ctx: ExtensionCommandContext): void {
276 - if (!this.runtime) {
277 - ctx.ui.notify("llmiterate off; no active worker log", "warning");
278 - return;
279 - }
281 - const target = renderLatestSessionLog(
282 - sessionDir(this.runtime),
283 - path.join(this.runtime.storeDir, "logs"),
284 - );
285 - if (!target) {
286 - ctx.ui.notify("llmiterate has no worker session logs yet", "warning");
287 - return;
288 - }
290 - const error = this.openEditor(target.markdownFile, this.env);
291 - if (error)
292 - ctx.ui.notify(
293 - `llmiterate log written: ${target.markdownFile} (${error})`,
294 - "warning",
295 - );
296 - }
298 - private explainCommand(
299 - targetPath: string,
300 - ctx: ExtensionCommandContext,
301 - ): void {
302 - const target = targetPath.trim();
303 - if (!target) {
304 - ctx.ui.notify("Usage: /llmiterate explain <path>", "warning");
305 - return;
306 - }
307 - ctx.ui.notify(explainPath(ctx.cwd, target), "info");
308 - }
310 - private statusText(cwd: string): string {
311 - const runtime = this.runtime;
312 - if (!runtime) return `llmiterate off\nscope: ${realPath(cwd)}`;
314 - const active = this.activeRun();
315 - return [
316 - runtime.lockError ? "llmiterate standby" : "llmiterate on",
317 - `scope: ${runtime.root}`,
318 - ...(runtime.lockError
319 - ? [
320 - `reason: ${runtime.lockError}`,
321 - "action: use existing same-cwd watcher, stop it, or choose another cwd",
322 - ]
323 - : []),
324 - `filters: include ${runtime.config.include.length}, exclude ${runtime.config.exclude.length}, .gitignore/.ignore on`,
325 - `watch dirs: ${runtime.watcher?.watcherCount ?? 0}`,
326 - `watch errors: ${runtime.watcher?.errorCount ?? 0}`,
327 - `queued: ${this.queuedRunCount()}`,
328 - `running: ${active ? `${active.projectFile}:${active.block.startLine}` : "none"}`,
329 - `failed: ${this.runs.filter((run) => run.status === "error").length}`,
330 - `state: ${runtime.storeDir}`,
331 - ].join("\n");
332 - }
334 - private notifyIfStandby(ctx: ExtensionCommandContext): boolean {
335 - if (!this.runtime?.lockError) return false;
336 - ctx.ui.notify(
337 - `llmiterate standby: ${this.runtime.root} already watched (${this.runtime.lockError})`,
338 - "warning",
339 - );
340 - return true;
341 - }
343 - private start(cwd: string): void {
344 - this.stop();
346 - const root = realPath(cwd);
347 - const config = loadConfig(root);
348 - const storeDir = projectStoreDir(root);
349 - this.runtime = {
350 - root,
351 - cwd: root,
352 - config,
353 - pathFilter: compilePathFilter(config),
354 - storeDir,
355 - state: loadState(storeDir),
356 - };
358 - if (!config.enabled) return;
359 - this.activateWatcher(this.runtime);
360 - }
362 - private activateWatcher(runtime: WatchRuntime): void {
363 - const lock = acquireLock(runtime.storeDir);
364 - if (typeof lock === "string") {
365 - runtime.lockError = lock;
366 - return;
367 - }
369 - runtime.lock = lock;
370 - runtime.watcher = this.makeWatcher(
371 - runtime.root,
372 - runtime.config,
373 - runtime.pathFilter,
374 - (file) => this.scanFile(file),
375 - () => this.updateUi(this.sessionCtx),
376 - );
377 - runtime.watcher.start();
378 - }
380 - private stop(): void {
381 - if (!this.runtime) return;
383 - this.runtime.watcher?.stop();
384 - this.stopWorker();
385 - if (this.runtime.lock) releaseLock(this.runtime.lock);
386 - this.runtime = undefined;
387 - }
389 - private scanFile(absPath: string): number {
390 - const file = this.readScannedFile(absPath);
391 - if (!file) return 0;
393 - let queued = 0;
394 - for (const block of parseMarkerPrompts(
395 - file.projectRel,
396 - file.text,
397 - file.runtime.config.commentPrefixes,
398 - )) {
399 - if (!this.shouldQueue(file.runtime, block)) continue;
400 - this.recordQueuedPrompt(file.runtime, block);
401 - this.enqueueRun(block, file.projectRel, absPath);
402 - queued++;
403 - }
405 - if (queued > 0) this.persistState(file.runtime);
406 - return queued;
407 - }
409 - private readScannedFile(absPath: string): ScannedFile | undefined {
410 - const runtime = this.runtime;
411 - if (!runtime) return undefined;
413 - const projectRel = toSlash(path.relative(runtime.root, absPath));
414 - if (!shouldIncludeCompiledPath(projectRel, runtime.pathFilter))
415 - return undefined;
417 - const stat = statFile(absPath);
418 - if (!stat?.isFile() || stat.size > runtime.config.maxFileBytes)
419 - return undefined;
421 - const text = readUtf8(absPath);
422 - return text === undefined ? undefined : { runtime, projectRel, text };
423 - }
425 - private shouldQueue(runtime: WatchRuntime, block: MarkerPrompt): boolean {
426 - const existing = runtime.state.markers[block.key];
427 - return !existing || existing.status === "failed";
428 - }
430 - private recordQueuedPrompt(runtime: WatchRuntime, block: MarkerPrompt): void {
431 - const existing = runtime.state.markers[block.key];
432 - const timestamp = this.now();
433 - runtime.state.markers[block.key] = {
434 - file: block.file,
435 - startLine: block.startLine,
436 - endLine: block.endLine,
437 - promptHash: block.promptHash,
438 - promptPreview: previewText(block.prompt, STATE_PROMPT_PREVIEW_CHARS),
439 - status: "queued",
440 - attempts: (existing?.attempts ?? 0) + 1,
441 - queuedAt: timestamp,
442 - updatedAt: timestamp,
443 - };
444 - }
446 - private persistState(runtime: WatchRuntime): void {
447 - saveState(runtime.storeDir, runtime.state);
448 - }
450 - private scanAll(): number {
451 - return this.runtime?.watcher?.scanAll((file) => this.scanFile(file)) ?? 0;
452 - }
454 - private enqueueRun(
455 - block: MarkerPrompt,
456 - projectFile: string,
457 - absoluteFile: string,
458 - ): void {
459 - this.runs.unshift(this.createRun(block, projectFile, absoluteFile));
460 - this.startNextRun();
461 - this.updateUi(this.sessionCtx);
462 - }
464 - private createRun(
465 - block: MarkerPrompt,
466 - projectFile: string,
467 - absoluteFile: string,
468 - ): LlmiterateRun {
469 - const timestamp = this.now();
470 - return {
471 - id: this.nextRunId++,
472 - block,
473 - projectFile,
474 - absoluteFile,
475 - fullPrompt: buildAgentPrompt(block),
476 - status: "queued",
477 - queuedAt: timestamp,
478 - updatedAt: timestamp,
479 - assistantText: "",
480 - toolText: "",
481 - };
482 - }
484 - private startNextRun(): void {
485 - if (this.activeJob || !this.runtime) return;
487 - while (this.runtime) {
488 - const run = this.nextQueuedRun();
489 - if (!run) return;
490 - if (this.isRunStillValid(run)) {
491 - void this.runInRpcWorker(run);
492 - return;
493 - }
494 - if (this.wasRecentlyModifiedByAgent(run.absoluteFile)) {
495 - this.voidRun(run);
496 - continue;
497 - }
498 - this.failRun(
499 - run,
500 - "marker span changed before background agent start; skipped stale request",
501 - );
502 - this.updateUi(this.sessionCtx);
503 - }
504 - }
506 - private nextQueuedRun(): LlmiterateRun | undefined {
507 - for (let i = this.runs.length - 1; i >= 0; i--) {
508 - if (this.runs[i]?.status === "queued") return this.runs[i];
509 - }
510 - return undefined;
511 - }
513 - private async runInRpcWorker(run: LlmiterateRun): Promise<void> {
514 - if (!this.runtime) return;
515 - if (!this.isRunStillValid(run)) {
516 - if (this.wasRecentlyModifiedByAgent(run.absoluteFile)) {
517 - this.voidRun(run);
518 - this.updateUi(this.sessionCtx);
519 - queueMicrotask(() => this.startNextRun());
520 - return;
521 - }
522 - this.failStaleRun(run);
523 - return;
524 - }
526 - this.markRunRunning(run);
527 - this.updateUi(this.sessionCtx);
529 - try {
530 - await this.worker().runPrompt(run.fullPrompt, sessionName(run));
531 - this.finishWorkerRun(run);
532 - } catch (error) {
533 - this.failRun(run, errorMessage(error));
534 - } finally {
535 - this.activeJob = false;
536 - this.activeRunId = undefined;
537 - this.touchRun(run);
538 - this.updateUi(this.sessionCtx);
539 - this.startNextRun();
540 - }
541 - }
543 - private failStaleRun(run: LlmiterateRun): void {
544 - this.failRun(
545 - run,
546 - "marker span changed before background agent start; skipped stale request",
547 - );
548 - this.updateUi(this.sessionCtx);
549 - queueMicrotask(() => this.startNextRun());
550 - }
552 - private finishWorkerRun(run: LlmiterateRun): void {
553 - if (this.isRunStillValid(run))
554 - this.failRun(run, "marker still present after background agent finished");
555 - else {
556 - this.recordAgentModification(run.absoluteFile);
557 - this.markRunDone(run);
558 - }
559 - }
561 - private warmWorker(): void {
562 - if (!this.runtime?.config.enabled || this.runtime.lockError) return;
563 - this.worker().warm();
564 - }
566 - private worker(): PiRpcWorker {
567 - const runtime = this.runtime;
568 - if (!runtime) throw new Error("llmiterate runtime is not started");
570 - this.rpcWorker ??= this.makeWorker({
571 - cwd: runtime.root,
572 - sessionDir: sessionDir(runtime),
573 - model: runtime.config.model,
574 - thinking: runtime.config.thinking,
575 - timeoutMs: runtime.config.timeoutMs,
576 - onEvent: (event) => this.handleRpcEvent(event),
577 - });
578 - return this.rpcWorker;
579 - }
581 - private stopWorker(): void {
582 - void this.rpcWorker?.dispose();
583 - this.rpcWorker = undefined;
584 - this.activeJob = false;
585 - this.activeRunId = undefined;
586 - }
588 - private handleRpcEvent(event: RpcEvent): void {
589 - const run = this.activeRun();
590 - if (!run) return;
592 - switch (event.type) {
593 - case "message_update":
594 - this.updateAssistantDelta(run, event.assistantMessageEvent);
595 - break;
596 - case "message_end":
597 - if (event.message?.role === "assistant")
598 - this.updateAssistantText(run, event.message);
599 - break;
600 - case "tool_execution_start":
601 - this.updateToolText(run, `running ${toolName(event.toolName)}`);
602 - break;
603 - case "tool_execution_end":
604 - this.handleToolEnd(run, event);
605 - break;
606 - case "agent_end":
607 - break;
608 - }
610 - this.updateUi(this.sessionCtx);
611 - }
613 - private handleToolEnd(
614 - run: LlmiterateRun,
615 - event: Extract<RpcEvent, { type: "tool_execution_end" }>,
616 - ): void {
617 - const failed = event.isError === true;
618 - this.updateToolText(
619 - run,
620 - `${failed ? "error" : "done"} ${toolName(event.toolName)}`,
621 - );
622 - if (failed) this.failRun(run, extractToolResultText(event.result));
623 - }
625 - private markRunRunning(run: LlmiterateRun): void {
626 - this.activeJob = true;
627 - this.activeRunId = run.id;
628 - run.status = "running";
629 - run.toolText = "starting isolated RPC session";
630 - run.assistantText = "";
631 - this.setMarkerStatus(run, "running");
632 - this.touchRun(run);
633 - }
635 - private markRunDone(run: LlmiterateRun): void {
636 - if (run.status === "error") return;
637 - run.status = "done";
638 - this.setMarkerStatus(run, "done");
639 - this.touchRun(run);
640 - }
642 - private failRun(run: LlmiterateRun, error: string): void {
643 - run.status = "error";
644 - run.error = error || "background pi failed";
645 - this.setMarkerStatus(run, "failed", run.error);
646 - this.maybeNotify(
647 - "error",
648 - `llmiterate failed ${run.projectFile}:${run.block.startLine}: ${previewText(run.error, ERROR_PREVIEW_CHARS)}`,
649 - );
650 - this.touchRun(run);
651 - }
653 - private setMarkerStatus(
654 - run: LlmiterateRun,
655 - status: MarkerRunState["status"],
656 - error?: string,
657 - ): void {
658 - const marker = this.runtime?.state.markers[run.block.key];
659 - if (!marker || !this.runtime) return;
661 - marker.status = status;
662 - marker.updatedAt = this.now();
663 - if (error) marker.lastError = error;
664 - else delete marker.lastError;
665 - this.persistState(this.runtime);
666 - }
668 - private maybeNotify(
669 - kind: "queued" | "done" | "error",
670 - message: string,
671 - ): void {
672 - if (!this.sessionCtx?.hasUI || !this.runtime) return;
673 - if (!shouldNotify(this.runtime.config.notify, kind)) return;
674 - this.sessionCtx.ui.notify(message, kind === "error" ? "error" : "info");
675 - }
677 - private updateAssistantText(run: LlmiterateRun, message: RpcMessage): void {
678 - run.assistantText = extractMessageText(message);
679 - this.touchRun(run);
680 - }
682 - private updateAssistantDelta(
683 - run: LlmiterateRun,
684 - event: RpcAssistantMessageEvent | undefined,
685 - ): void {
686 - if (event?.type !== "text_delta" || typeof event.delta !== "string") return;
687 - run.assistantText += event.delta;
688 - this.touchRun(run);
689 - }
691 - private updateToolText(run: LlmiterateRun, text: string): void {
692 - run.toolText = text;
693 - this.touchRun(run);
694 - }
696 - private touchRun(run: LlmiterateRun): void {
697 - run.updatedAt = this.now();
698 - }
700 - private voidRun(run: LlmiterateRun): void {
701 - const idx = this.runs.findIndex((r) => r.id === run.id);
702 - if (idx !== -1) this.runs.splice(idx, 1);
703 - if (this.runtime) {
704 - delete this.runtime.state.markers[run.block.key];
705 - this.persistState(this.runtime);
706 - }
707 - this.updateUi(this.sessionCtx);
708 - }
710 - private recordAgentModification(absPath: string): void {
711 - this.agentModifiedFiles.set(absPath, this.now());
712 - }
714 - private wasRecentlyModifiedByAgent(absPath: string): boolean {
715 - const ts = this.agentModifiedFiles.get(absPath);
716 - if (ts === undefined) return false;
717 - return this.now() - ts < 30_000;
718 - }
720 - private isRunStillValid(run: LlmiterateRun): boolean {
721 - const runtime = this.runtime;
722 - if (!runtime) return false;
724 - const text = readUtf8(run.absoluteFile);
725 - if (text === undefined) return false;
727 - return parseMarkerPrompts(
728 - run.projectFile,
729 - text,
730 - runtime.config.commentPrefixes,
731 - ).some(
732 - (block) =>
733 - block.startLine === run.block.startLine &&
734 - block.promptHash === run.block.promptHash,
735 - );
736 - }
738 - private activeRun(): LlmiterateRun | undefined {
739 - return this.runs.find((run) => run.id === this.activeRunId);
740 - }
742 - private updateUi(ctx: ExtensionContext | undefined): void {
743 - renderLlmiterateStatus(ctx, {
744 - config: this.runtime?.config,
745 - lockError: this.runtime?.lockError,
746 - watchErrors: this.runtime?.watcher?.errorCount ?? 0,
747 - watchDirs: this.runtime?.watcher?.watcherCount ?? 0,
748 - activeRun: this.activeRun(),
749 - queuedRuns: this.queuedRunCount(),
750 - });
751 - }
753 - private queuedRunCount(): number {
754 - return this.runs.filter((run) => run.status === "queued").length;
755 - }
758 -function sessionDir(runtime: WatchRuntime): string {
759 - return path.join(runtime.storeDir, "sessions");
762 -function parseCommandArgs(args: string): { command: string; rest: string } {
763 - const trimmed = args.trim();
764 - if (!trimmed) return { command: "", rest: "" };
765 - const match = trimmed.match(/^(\S+)(?:\s+([\s\S]*))?$/);
766 - return { command: (match?.[1] ?? "").toLowerCase(), rest: match?.[2] ?? "" };
769 -function explainPath(cwd: string, target: string): string {
770 - const scope = realPath(cwd);
771 - const abs = path.resolve(scope, target);
772 - const rel = toSlash(path.relative(scope, abs));
773 - const config = loadConfig(scope);
774 - const stat = statFile(abs);
775 - const directory = stat?.isDirectory() === true;
776 - const include = firstMatchingGlob(config.include, rel, directory);
777 - const exclude = firstMatchingGlob(config.exclude, rel, directory);
778 - const unsafe = !rel || rel.startsWith("..") || path.isAbsolute(rel);
779 - const tooLarge = stat?.isFile() && stat.size > config.maxFileBytes;
780 - const text = stat?.isFile() && !tooLarge ? readUtf8(abs) : undefined;
781 - const disabled =
782 - text !== undefined &&
783 - isLlmiterateDisabled(text, rel, config.commentPrefixes);
784 - const markers =
785 - text !== undefined && !disabled
786 - ? parseMarkerPrompts(rel, text, config.commentPrefixes).length
787 - : 0;
788 - const status = explainStatus({
789 - unsafe,
790 - stat,
791 - include,
792 - exclude,
793 - tooLarge,
794 - disabled,
795 - markers,
796 - });
798 - return [
799 - rel || ".",
800 - `scope: ${scope}`,
801 - `included: ${include ?? "no"}`,
802 - `excluded: ${exclude ?? "no"}`,
803 - `ignored: .gitignore/.ignore respected during scan/watch`,
804 - `size: ${stat?.isFile() ? `${formatBytes(stat.size)} / ${formatBytes(config.maxFileBytes)}` : "not a file"}`,
805 - `markers: ${disabled ? "disabled by !llmiterate" : markers}`,
806 - `status: ${status}`,
807 - ].join("\n");
810 -function firstMatchingGlob(
811 - globs: readonly string[],
812 - rel: string,
813 - directory: boolean,
814 -): string | undefined {
815 - for (const glob of globs) {
816 - const pattern = globToRegExp(glob);
817 - if (pattern.test(rel) || (directory && pattern.test(`${rel}/`)))
818 - return glob;
819 - }
820 - return undefined;
823 -function explainStatus(input: {
824 - unsafe: boolean;
825 - stat: fs.Stats | undefined;
826 - include: string | undefined;
827 - exclude: string | undefined;
828 - tooLarge: boolean | undefined;
829 - disabled: boolean;
830 - markers: number;
831 -}): string {
832 - if (input.unsafe) return "outside scope";
833 - if (!input.stat) return "missing";
834 - if (!input.stat.isFile()) return "not a file";
835 - if (!input.include) return "not included";
836 - if (input.exclude) return "excluded";
837 - if (input.tooLarge) return "too large";
838 - if (input.disabled) return "disabled";
839 - if (input.markers === 0) return "no llmiterate marker";
840 - return "will run";
843 -function formatBytes(bytes: number): string {
844 - if (bytes < 1024) return `${bytes} B`;
845 - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
846 - return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
849 -function statFile(absPath: string): fs.Stats | undefined {
850 - try {
851 - return fs.statSync(absPath);
852 - } catch {
853 - return undefined;
854 - }
857 -function readUtf8(absPath: string): string | undefined {
858 - try {
859 - return fs.readFileSync(absPath, "utf-8");
860 - } catch {
861 - return undefined;
862 - }
865 -function shouldNotify(
866 - policy: NotifyPolicy,
867 - kind: "queued" | "done" | "error",
868 -): boolean {
869 - return policy !== "off" && kind === "error";
872 -function sessionName(run: LlmiterateRun): string {
873 - return `llmiterate ${run.projectFile}:${run.block.startLine}`;
876 -function extractMessageText(message: RpcMessage): string {
877 - if (typeof message.content === "string") return message.content.trim();
878 - return textParts(message.content).join("\n").trim();
881 -function extractToolResultText(result: RpcToolResult | undefined): string {
882 - return textParts(result?.content).join("\n").trim();
885 -function textParts(parts: RpcMessage["content"]): string[] {
886 - return Array.isArray(parts)
887 - ? parts.filter(isTextPart).map((part) => part.text)
888 - : [];
891 -function isTextPart(part: RpcTextPart): part is RpcTextPart & { text: string } {
892 - return part.type === "text" && typeof part.text === "string";
895 -function toolName(value: unknown): string {
896 - return typeof value === "string" && value.trim() ? value : "tool";
899 -function errorMessage(error: unknown): string {
900 - return error instanceof Error ? error.message : String(error);

extensions/llmiterate/lock.ts

Deleted
deleted file mode 100644
1 -import { randomUUID } from "node:crypto";
2 -import * as fs from "node:fs";
3 -import * as os from "node:os";
4 -import * as path from "node:path";
6 -const LOCK_DIR = "lock";
7 -const OWNER_FILE = "owner.json";
9 -export interface LockHandle {
10 - dir: string;
11 - token: string;
14 -interface LockOwner {
15 - pid: number;
16 - hostname: string;
17 - token: string;
20 -export function realPath(file: string): string {
21 - try {
22 - return fs.realpathSync(file);
23 - } catch {
24 - return path.resolve(file);
25 - }
28 -export function acquireLock(storeDir: string): LockHandle | string {
29 - const lockDir = path.join(storeDir, LOCK_DIR);
30 - fs.mkdirSync(storeDir, { recursive: true });
32 - const token = randomUUID();
33 - const owner = createOwner(token);
34 - const created = tryCreateLock(lockDir, owner);
35 - if (created) return created;
37 - const existing = readLockOwner(lockDir);
38 - if (existing && isStaleOwner(existing)) {
39 - const recovered = reclaimStaleLock(lockDir, existing, owner);
40 - if (recovered) return recovered;
41 - }
43 - const by = existing
44 - ? `pid ${existing.pid} on ${existing.hostname}`
45 - : "another pi";
46 - return `singleton lock held by ${by}`;
49 -export function releaseLock(lock: LockHandle): void {
50 - const owner = readLockOwner(lock.dir);
51 - if (!owner || owner.token !== lock.token) return;
52 - fs.rmSync(lock.dir, { recursive: true, force: true });
55 -function createOwner(token: string): LockOwner {
56 - return { pid: process.pid, hostname: os.hostname(), token };
59 -function tryCreateLock(
60 - lockDir: string,
61 - owner: LockOwner,
62 -): LockHandle | undefined {
63 - try {
64 - fs.mkdirSync(lockDir);
65 - fs.writeFileSync(
66 - path.join(lockDir, OWNER_FILE),
67 - JSON.stringify(owner, null, 2) + "\n",
68 - "utf-8",
69 - );
70 - return { dir: lockDir, token: owner.token };
71 - } catch (error) {
72 - if (nodeErrorCode(error) !== "EEXIST") throw error;
73 - return undefined;
74 - }
77 -function readLockOwner(lockDir: string): LockOwner | undefined {
78 - try {
79 - return parseLockOwner(
80 - JSON.parse(fs.readFileSync(path.join(lockDir, OWNER_FILE), "utf-8")),
81 - );
82 - } catch {
83 - return undefined;
84 - }
87 -function parseLockOwner(value: unknown): LockOwner | undefined {
88 - if (!value || typeof value !== "object" || Array.isArray(value))
89 - return undefined;
90 - const keys = Object.keys(value).sort();
91 - if (keys.join("\0") !== "hostname\0pid\0token") return undefined;
93 - const owner = value as Partial<LockOwner>;
94 - if (typeof owner.pid !== "number") return undefined;
95 - if (typeof owner.hostname !== "string") return undefined;
96 - if (typeof owner.token !== "string") return undefined;
97 - return { pid: owner.pid, hostname: owner.hostname, token: owner.token };
100 -function reclaimStaleLock(
101 - lockDir: string,
102 - staleOwner: LockOwner,
103 - newOwner: LockOwner,
104 -): LockHandle | undefined {
105 - const reclaimedDir = `${lockDir}.stale.${newOwner.token}`;
106 - try {
107 - fs.renameSync(lockDir, reclaimedDir);
108 - } catch {
109 - return undefined;
110 - }
112 - const movedOwner = readLockOwner(reclaimedDir);
113 - if (movedOwner?.token !== staleOwner.token) {
114 - try {
115 - fs.renameSync(reclaimedDir, lockDir);
116 - } catch {}
117 - return undefined;
118 - }
120 - fs.rmSync(reclaimedDir, { recursive: true, force: true });
121 - return tryCreateLock(lockDir, newOwner);
124 -function isStaleOwner(owner: LockOwner): boolean {
125 - if (owner.hostname !== os.hostname()) return false;
126 - try {
127 - process.kill(owner.pid, 0);
128 - return false;
129 - } catch (error) {
130 - return nodeErrorCode(error) === "ESRCH";
131 - }
134 -function nodeErrorCode(error: unknown): string | undefined {
135 - return error instanceof Error && "code" in error
136 - ? String((error as NodeJS.ErrnoException).code)
137 - : undefined;

extensions/llmiterate/log.ts

Deleted
deleted file mode 100644
1 -import { spawnSync } from "node:child_process";
2 -import * as fs from "node:fs";
3 -import * as path from "node:path";
4 -import { previewText } from "./util";
6 -export interface RenderedLogTarget {
7 - sessionFile: string;
8 - markdownFile: string;
9 -}
11 -export function latestSessionFile(sessionDir: string): string | undefined {
12 - const files: string[] = [];
13 - walk(sessionDir, (file) => {
14 - if (file.endsWith(".jsonl")) files.push(file);
15 - });
16 - return files.sort((a, b) => mtimeMs(b) - mtimeMs(a))[0];
19 -export function renderLatestSessionLog(
20 - sessionDir: string,
21 - outDir: string,
22 -): RenderedLogTarget | undefined {
23 - const sessionFile = latestSessionFile(sessionDir);
24 - if (!sessionFile) return undefined;
26 - fs.mkdirSync(outDir, { recursive: true });
27 - const markdownFile = path.join(outDir, "latest.md");
28 - fs.writeFileSync(
29 - markdownFile,
30 - renderSessionLogMarkdown(sessionFile),
31 - "utf-8",
32 - );
33 - return { sessionFile, markdownFile };
36 -export function renderSessionLogMarkdown(sessionFile: string): string {
37 - const lines = fs
38 - .readFileSync(sessionFile, "utf-8")
39 - .split(/\r?\n/)
40 - .filter(Boolean);
41 - const out = ["# llmiterate log", "", `Session: ${sessionFile}`, ""];
43 - for (const line of lines) {
44 - let entry: unknown;
45 - try {
46 - entry = JSON.parse(line);
47 - } catch {
48 - continue;
49 - }
50 - const rendered = renderEntry(entry);
51 - if (rendered) out.push(rendered, "");
52 - }
54 - return out.join("\n").trimEnd() + "\n";
57 -export interface EditorCommand {
58 - command: string;
59 - args: string[];
62 -export function openInEditor(
63 - file: string,
64 - env: NodeJS.ProcessEnv = process.env,
65 -): string | undefined {
66 - const editor = parseEditorCommand(env.VISUAL || env.EDITOR || "");
67 - if (!editor) return "VISUAL/EDITOR not set";
69 - const result = spawnSync(editor.command, [...editor.args, file], {
70 - stdio: "inherit",
71 - });
72 - if (result.error) return result.error.message;
73 - if (typeof result.status === "number" && result.status !== 0)
74 - return `${editor.command} exited with ${result.status}`;
75 - return undefined;
78 -export function parseEditorCommand(input: string): EditorCommand | undefined {
79 - const args = shellWords(input);
80 - const command = args.shift();
81 - return command ? { command, args } : undefined;
84 -function renderEntry(entry: unknown): string | undefined {
85 - if (!isObject(entry)) return undefined;
86 - const message = isObject(entry.message) ? entry.message : entry;
87 - const role = typeof message.role === "string" ? message.role : undefined;
88 - const text = contentText(message.content);
90 - if (role && text) return `## ${title(role)}\n\n${fence(text)}`;
91 - if (typeof entry.type === "string" && entry.type.includes("tool")) {
92 - return `## ${entry.type}\n\n${fence(previewText(JSON.stringify(entry, null, 2), 4000))}`;
93 - }
94 - return undefined;
97 -function contentText(content: unknown): string {
98 - if (typeof content === "string") return content.trim();
99 - if (!Array.isArray(content)) return "";
100 - return content
101 - .map((part) => {
102 - if (!isObject(part)) return "";
103 - if (typeof part.text === "string") return part.text;
104 - if (typeof part.content === "string") return part.content;
105 - return "";
106 - })
107 - .filter(Boolean)
108 - .join("\n")
109 - .trim();
112 -function title(role: string): string {
113 - return role.slice(0, 1).toUpperCase() + role.slice(1);
116 -function fence(text: string): string {
117 - return `\`\`\`text\n${text}\n\`\`\``;
120 -function walk(dir: string, onFile: (file: string) => void): void {
121 - let entries: fs.Dirent[];
122 - try {
123 - entries = fs.readdirSync(dir, { withFileTypes: true });
124 - } catch {
125 - return;
126 - }
127 - for (const entry of entries) {
128 - const file = path.join(dir, entry.name);
129 - if (entry.isDirectory()) walk(file, onFile);
130 - else if (entry.isFile()) onFile(file);
131 - }
134 -function mtimeMs(file: string): number {
135 - try {
136 - return fs.statSync(file).mtimeMs;
137 - } catch {
138 - return 0;
139 - }
142 -function shellWords(input: string): string[] {
143 - const words: string[] = [];
144 - let current = "";
145 - let quote: "'" | '"' | undefined;
146 - let escaped = false;
148 - for (const char of input.trim()) {
149 - if (escaped) {
150 - current += char;
151 - escaped = false;
152 - continue;
153 - }
154 - if (char === "\\") {
155 - escaped = true;
156 - continue;
157 - }
158 - if (quote) {
159 - if (char === quote) quote = undefined;
160 - else current += char;
161 - continue;
162 - }
163 - if (char === "'" || char === '"') {
164 - quote = char;
165 - continue;
166 - }
167 - if (/\s/.test(char)) {
168 - if (current) words.push(current);
169 - current = "";
170 - continue;
171 - }
172 - current += char;
173 - }
175 - if (current) words.push(current);
176 - return words;
179 -function isObject(value: unknown): value is Record<string, unknown> {
180 - return typeof value === "object" && value !== null && !Array.isArray(value);

extensions/llmiterate/mise.toml

Deleted
deleted file mode 100644
1 -[tasks.bench]
2 -description = "Benchmark marker parsing and gitignore scans"
3 -depends = ["//:install"]
4 -run = [
5 - "node --import tsx __bench__/bench.ts",
6 - "npm exec -- vitest bench __benches__/gitignore.bench.ts --run --project fast --reporter=default",
7 -]
9 -[tasks.lint]
10 -description = "Lint llmiterate extension"
11 -depends = ["//:install"]
12 -run = [
13 - "biome ci --config-path ../.. .",
14 - "rumdl check --config ../../.rumdl.toml .",
15 - "taplo format --check --config ../../.taplo.toml mise.toml",
16 -]
18 -[tasks.test]
19 -description = "Test llmiterate extension"
20 -depends = ["//:install"]
21 -run = [
22 - { task = "//:test", args = ["extensions/llmiterate"] },
23 -]
25 -[tasks.check]
26 -description = "Check llmiterate extension"
27 -depends = ["//:install"]
28 -run = [
29 - { task = "//:build", args = ["llmiterate"] },
30 -]

extensions/llmiterate/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-llmiterate",
3 - "type": "module",
4 - "main": "index.ts",
5 - "peerDependencies": {
6 - "@earendil-works/pi-coding-agent": "*"
7 - },
8 - "license": "MIT",
9 - "description": "LLM iteration watcher for Pi.",
10 - "keywords": [
11 - "pi",
12 - "pi-extension"
13 - ],
14 - "devDependencies": {
15 - "@marcfargas/pi-test-harness": "^0.6.1",
16 - "vitest": "^4.1.9"
17 - },
18 - "private": true
19 -}

extensions/llmiterate/parser.ts

Deleted
deleted file mode 100644
1 -import {
2 - COMMENT_PREFIXES_BY_EXTENSION,
3 - DISABLE_MARKER,
4 - MARKER,
5 -} from "./constants";
7 -export interface MarkerPrompt {
8 - marker: typeof MARKER;
9 - file: string;
10 - startLine: number;
11 - endLine: number;
12 - prompt: string;
13 - key: string;
14 - promptHash: string;
17 -const commentPrefixGroupCache = new Map<string, Map<string, string[]>>();
19 -export function parseMarkerPrompts(
20 - file: string,
21 - text: string,
22 - commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
23 -): MarkerPrompt[] {
24 - if (!text.includes("llmiterate")) return [];
25 - const prefixes = prefixesForFile(file, commentPrefixes);
26 - if (prefixes.length === 0) return [];
27 - if (isLlmiterateDisabled(text, file, commentPrefixes)) return [];
29 - const lines = normalizeLines(text);
30 - const prompts: MarkerPrompt[] = [];
32 - for (let i = 0; i < lines.length; i++) {
33 - const first = parsePromptLine(lines[i] ?? "", prefixes);
34 - if (!first) continue;
36 - const startLine = i + 1;
37 - const body = [first];
38 - let endLine = startLine;
40 - for (let j = i + 1; j < lines.length; j++) {
41 - const next = parsePromptLine(lines[j] ?? "", prefixes);
42 - if (!next) break;
43 - body.push(next);
44 - endLine = j + 1;
45 - i = j;
46 - }
48 - const prompt = body.join("\n").trim();
49 - if (prompt) prompts.push(makePrompt(file, startLine, endLine, prompt));
50 - }
52 - return prompts;
55 -export function isLlmiterateDisabled(
56 - text: string,
57 - file = "",
58 - commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
59 -): boolean {
60 - if (!text.includes(DISABLE_MARKER)) return false;
61 - const prefixes = prefixesForFile(file, commentPrefixes);
62 - if (prefixes.length === 0) return false;
63 - return normalizeLines(text).some((line) => {
64 - const stripped = stripCommentPrefix(line, prefixes);
65 - return stripped !== undefined && /^!llmiterate(?:\s|$)/.test(stripped);
66 - });
69 -export function prefixesForFile(
70 - file: string,
71 - commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
72 -): string[] {
73 - return normalizeCommentPrefixes(commentPrefixes[extensionKey(file)] ?? []);
76 -function extensionKey(file: string): string {
77 - const base = (file.split(/[\\/]/).pop() ?? "").toLowerCase();
78 - if (!base) return "";
79 - if (base === "dockerfile" || base.endsWith(".dockerfile"))
80 - return "dockerfile";
81 - const dot = base.lastIndexOf(".");
82 - return dot === -1 ? base : base.slice(dot + 1);
85 -function parsePromptLine(line: string, prefixes: string[]): string | undefined {
86 - const stripped = stripCommentPrefix(line, prefixes);
87 - if (stripped === undefined || !stripped.startsWith(MARKER)) return undefined;
88 - const prompt = stripped.slice(MARKER.length).trim();
89 - return prompt || undefined;
92 -function stripCommentPrefix(
93 - line: string,
94 - prefixes: string[],
95 -): string | undefined {
96 - const trimmed = line.trimStart();
97 - const candidates = commentPrefixGroups(prefixes).get(trimmed[0] ?? "");
98 - if (!candidates) return undefined;
99 - for (const prefix of candidates) {
100 - if (!startsWithCommentPrefix(trimmed, prefix)) continue;
101 - const suffix = commentSuffix(prefix);
102 - let body = trimmed.slice(prefix.length).trimStart();
103 - if (suffix && body.endsWith(suffix))
104 - body = body.slice(0, -suffix.length).trimEnd();
105 - return body;
106 - }
107 - return undefined;
110 -function startsWithCommentPrefix(line: string, prefix: string): boolean {
111 - if (!line.startsWith(prefix)) return false;
112 - if (/^[a-z]+$/i.test(prefix)) {
113 - const next = line[prefix.length];
114 - return next === undefined || /\s/.test(next);
115 - }
116 - return true;
119 -function commentPrefixGroups(prefixes: string[]): Map<string, string[]> {
120 - const key = prefixes.join("\0");
121 - const cached = commentPrefixGroupCache.get(key);
122 - if (cached) return cached;
123 - const groups = new Map<string, string[]>();
124 - for (const prefix of prefixes) {
125 - const key = prefix[0] ?? "";
126 - const group = groups.get(key) ?? [];
127 - group.push(prefix);
128 - groups.set(key, group);
129 - }
130 - commentPrefixGroupCache.set(key, groups);
131 - return groups;
134 -function commentSuffix(prefix: string): string | undefined {
135 - if (prefix === "<!--") return "-->";
136 - if (prefix === "/*" || prefix === "/**") return "*/";
137 - return undefined;
140 -function normalizeLines(text: string): string[] {
141 - return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
144 -function makePrompt(
145 - file: string,
146 - startLine: number,
147 - endLine: number,
148 - prompt: string,
149 -): MarkerPrompt {
150 - const promptHash = hashString(prompt);
151 - return {
152 - marker: MARKER,
153 - file,
154 - startLine,
155 - endLine,
156 - prompt,
157 - promptHash,
158 - key: `${file}:${startLine}:${promptHash}`,
159 - };
162 -function hashString(input: string): string {
163 - let hash = 0x811c9dc5;
164 - for (let i = 0; i < input.length; i++) {
165 - hash ^= input.charCodeAt(i);
166 - hash = Math.imul(hash, 0x01000193);
167 - }
168 - return (hash >>> 0).toString(16).padStart(8, "0");
171 -function normalizeCommentPrefixes(prefixes: string[]): string[] {
172 - return [...new Set(prefixes.map((p) => p.trim()).filter(Boolean))].sort(
173 - (a, b) => b.length - a.length,
174 - );

extensions/llmiterate/path-filter.ts

Deleted
deleted file mode 100644
1 -import { createHash } from "node:crypto";
2 -import * as os from "node:os";
3 -import * as path from "node:path";
4 -import type { LlmiterateConfig } from "./config";
5 -import { APP_STATE_DIR, STORE_NAMESPACE } from "./constants";
6 -import { toSlash } from "./util";
8 -const REGEX_CHARS = /[|\\{}()[\]^$+?.]/;
10 -export type CompiledGlobSegment = "**" | RegExp;
12 -export interface CompiledPathFilter {
13 - include: RegExp[];
14 - includeDirPatterns: CompiledGlobSegment[][];
15 - exclude: RegExp[];
16 - excludeRootDirs: Set<string>;
17 - excludePrefixes: string[];
20 -export function projectStoreDir(root: string): string {
21 - return path.join(platformStateDir(), STORE_NAMESPACE, hashProjectRoot(root));
24 -export function platformStateDir(
25 - platform: NodeJS.Platform = process.platform,
26 - env: NodeJS.ProcessEnv = process.env,
27 - home = os.homedir(),
28 -): string {
29 - const paths = platform === "win32" ? path.win32 : path.posix;
31 - // Treat XDG_STATE_HOME as an explicit override for hermetic tests/CI,
32 - // even on platforms where it is not the native convention.
33 - if (env.XDG_STATE_HOME) return paths.join(env.XDG_STATE_HOME, APP_STATE_DIR);
34 - if (platform === "win32") {
35 - return paths.join(
36 - env.LOCALAPPDATA ?? paths.join(home, "AppData", "Local"),
37 - APP_STATE_DIR,
38 - );
39 - }
40 - if (platform === "darwin")
41 - return paths.join(home, "Library", "Application Support", APP_STATE_DIR);
42 - return paths.join(home, ".local", "state", APP_STATE_DIR);
45 -export function hashProjectRoot(root: string): string {
46 - return createHash("sha256").update(root).digest("hex");
49 -export function compilePathFilter(
50 - config: Pick<LlmiterateConfig, "include" | "exclude">,
51 -): CompiledPathFilter {
52 - const includeDirPatterns = config.include.map(compileGlobSegments);
53 - const excludeRootDirs = new Set<string>();
54 - const excludePrefixes: string[] = [];
55 - const exclude: RegExp[] = [];
57 - for (const glob of config.exclude) {
58 - const prefix = simpleGlobstarPrefix(glob);
59 - if (!prefix) {
60 - exclude.push(globToRegExp(glob));
61 - continue;
62 - }
64 - const rootDir = rootDirPrefix(prefix);
65 - if (rootDir) excludeRootDirs.add(rootDir);
66 - else excludePrefixes.push(prefix);
67 - }
69 - return {
70 - include: config.include.map(globToRegExp),
71 - includeDirPatterns,
72 - exclude,
73 - excludeRootDirs,
74 - excludePrefixes,
75 - };
78 -export function shouldIncludePath(
79 - relPath: string,
80 - config: Pick<LlmiterateConfig, "include" | "exclude"> | CompiledPathFilter,
81 -): boolean {
82 - const filter = isCompiledPathFilter(config)
83 - ? config
84 - : compilePathFilter(config);
85 - return shouldIncludeCompiledPath(relPath, filter);
88 -export function shouldIncludeCompiledPath(
89 - relPath: string,
90 - filter: CompiledPathFilter,
91 -): boolean {
92 - const rel = toSlash(relPath);
93 - if (isExcludedPath(rel, filter)) return false;
94 - return filter.include.some((pattern) => pattern.test(rel));
97 -export function isExcludedPath(
98 - relPath: string,
99 - filter: CompiledPathFilter,
100 -): boolean {
101 - const rel = toSlash(relPath);
102 - return (
103 - filter.excludeRootDirs.has(firstPathSegment(rel)) ||
104 - filter.excludePrefixes.some((prefix) => rel.startsWith(prefix)) ||
105 - filter.exclude.some((pattern) => pattern.test(rel))
106 - );
109 -export function shouldWatchDirectory(
110 - relPath: string,
111 - filter: CompiledPathFilter,
112 -): boolean {
113 - const rel = toSlash(relPath);
114 - if (rel && (isExcludedPath(rel, filter) || isExcludedPath(`${rel}/`, filter)))
115 - return false;
116 - const segments = rel ? rel.split("/") : [];
117 - return filter.includeDirPatterns.some((include) =>
118 - includeCanMatchUnderDir(include, segments),
119 - );
122 -export function globToRegExp(pattern: string): RegExp {
123 - const glob = toSlash(pattern);
124 - let s = "^";
125 - for (let i = 0; i < glob.length; ) {
126 - const c = glob[i];
127 - if (c === "*") {
128 - if (glob[i + 1] === "*") {
129 - i += 2;
130 - if (glob[i] === "/") {
131 - i++;
132 - s += "(?:.*/)?";
133 - } else {
134 - s += ".*";
135 - }
136 - continue;
137 - }
138 - s += "[^/]*";
139 - i++;
140 - continue;
141 - }
142 - if (c === "?") {
143 - s += "[^/]";
144 - i++;
145 - continue;
146 - }
147 - if (c === "{") {
148 - const end = glob.indexOf("}", i + 1);
149 - if (end !== -1) {
150 - const parts = glob
151 - .slice(i + 1, end)
152 - .split(",")
153 - .map((p) => p.trim())
154 - .filter(Boolean)
155 - .map(escapeRegExp);
156 - if (parts.length) {
157 - s += `(?:${parts.join("|")})`;
158 - i = end + 1;
159 - continue;
160 - }
161 - }
162 - }
163 - s += REGEX_CHARS.test(c) ? `\\${c}` : c;
164 - i++;
165 - }
166 - return new RegExp(`${s}$`);
169 -function includeCanMatchUnderDir(
170 - pattern: CompiledGlobSegment[],
171 - dir: string[],
172 -): boolean {
173 - const memo = new Map<string, boolean>();
174 - const visit = (patternIndex: number, dirIndex: number): boolean => {
175 - const key = `${patternIndex}:${dirIndex}`;
176 - const cached = memo.get(key);
177 - if (cached !== undefined) return cached;
179 - let result: boolean;
180 - if (dirIndex >= dir.length) {
181 - result = patternIndex < pattern.length;
182 - } else if (patternIndex >= pattern.length) {
183 - result = false;
184 - } else {
185 - const segment = pattern[patternIndex];
186 - const dirSegment = dir[dirIndex];
187 - result =
188 - segment === "**"
189 - ? visit(patternIndex + 1, dirIndex) ||
190 - visit(patternIndex, dirIndex + 1)
191 - : !!segment &&
192 - !!dirSegment &&
193 - segment.test(dirSegment) &&
194 - visit(patternIndex + 1, dirIndex + 1);
195 - }
197 - memo.set(key, result);
198 - return result;
199 - };
200 - return visit(0, 0);
203 -function compileGlobSegments(pattern: string): CompiledGlobSegment[] {
204 - return toSlash(pattern)
205 - .split("/")
206 - .filter(Boolean)
207 - .map((segment) => (segment === "**" ? "**" : globToRegExp(segment)));
210 -function simpleGlobstarPrefix(glob: string): string | undefined {
211 - const normalized = toSlash(glob);
212 - if (!normalized.endsWith("/**")) return undefined;
213 - const prefix = normalized.slice(0, -2);
214 - return /[*?{[]/.test(prefix) ? undefined : prefix;
217 -function rootDirPrefix(prefix: string): string | undefined {
218 - const dir = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
219 - return dir && !dir.includes("/") ? dir : undefined;
222 -function firstPathSegment(path: string): string {
223 - const slash = path.indexOf("/");
224 - return slash === -1 ? path : path.slice(0, slash);
227 -function escapeRegExp(s: string): string {
228 - return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
231 -function isCompiledPathFilter(
232 - value: Pick<LlmiterateConfig, "include" | "exclude"> | CompiledPathFilter,
233 -): value is CompiledPathFilter {
234 - return "includeDirPatterns" in value;

extensions/llmiterate/prompt.ts

Deleted
deleted file mode 100644
1 -import type { MarkerPrompt } from "./parser";
3 -export function buildAgentPrompt(block: MarkerPrompt): string {
4 - return [
5 - `llmiterate request from @${block.file}:${block.startLine}`,
6 - "",
7 - "Prompt marker contents:",
8 - "```text",
9 - block.prompt,
10 - "```",
11 - "",
12 - "Instructions:",
13 - `- Work in/around @${block.file}.`,
14 - `- Marker span to replace: ${block.file}:${block.startLine}-${block.endLine}.`,
15 - "- Treat the marker comment line(s) as an inline prompt/TODO, not program code.",
16 - "- Replace the whole marker span with the requested implementation or code change.",
17 - "- Do not leave the marker line(s) behind unless impossible; explain if impossible.",
18 - ].join("\n");
19 -}

extensions/llmiterate/rpc.ts

Deleted
deleted file mode 100644
1 -import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2 -import * as fs from "node:fs";
3 -import * as path from "node:path";
4 -import type { RpcEvent } from "./types";
6 -const RPC_KILL_GRACE_MS = 5_000;
7 -export const LLMITERATE_WORKER_ENV = "LLMITERATE_WORKER";
8 -export const WORKER_SYSTEM_PROMPT = [
9 - "You are llmiterate, a background Pi worker launched from a file-save marker.",
10 - "Fulfill only the marker request.",
11 - "Edit files directly with tools.",
12 - "Do not ask for confirmation.",
13 - "Keep assistant text concise; source edits are the primary output.",
14 -].join("\n");
15 -const RESPONSE_EVENT = "response";
16 -const AGENT_END_EVENT = "agent_end";
17 -const CMD_NEW_SESSION = "new_session";
18 -const CMD_SET_SESSION_NAME = "set_session_name";
19 -const CMD_PROMPT = "prompt";
20 -const CMD_ABORT = "abort";
22 -interface PendingCommand {
23 - command: string;
24 - resolve(response: unknown): void;
25 - reject(error: Error): void;
28 -interface PiInvocation {
29 - command: string;
30 - args: string[];
33 -interface RpcCommandPayload {
34 - type: string;
35 - [key: string]: unknown;
38 -interface RpcResponse extends RpcWireEvent {
39 - type: "response";
40 - id?: unknown;
41 - success?: unknown;
42 - error?: unknown;
43 - data?: unknown;
46 -interface RpcWireEvent {
47 - type: string;
48 - [key: string]: unknown;
51 -export interface RpcWorkerOptions {
52 - cwd: string;
53 - sessionDir: string;
54 - onEvent(event: RpcEvent): void;
55 - invocation?: PiInvocation;
56 - model?: string;
57 - thinking?: string;
58 - timeoutMs?: number;
59 - appendSystemPrompt?: string;
60 - offline?: boolean;
61 - env?: NodeJS.ProcessEnv;
64 -export class PiRpcWorker {
65 - private proc?: ChildProcessWithoutNullStreams;
66 - private stdoutBuffer = "";
67 - private stderr = "";
68 - private nextId = 1;
69 - private runningPrompt = false;
70 - private readonly pending = new Map<string, PendingCommand>();
71 - private currentPrompt?: { resolve(): void; reject(error: Error): void };
73 - constructor(private readonly options: RpcWorkerOptions) {}
75 - warm(): void {
76 - this.ensureStarted();
77 - }
79 - async runPrompt(prompt: string, sessionName: string): Promise<void> {
80 - if (this.runningPrompt)
81 - throw new Error("RPC worker already has an active prompt");
83 - this.runningPrompt = true;
84 - try {
85 - await this.command({ type: CMD_NEW_SESSION });
86 - await this.command({ type: CMD_SET_SESSION_NAME, name: sessionName });
88 - const done = new Promise<void>((resolve, reject) => {
89 - this.currentPrompt = { resolve, reject };
90 - });
91 - await this.command({ type: CMD_PROMPT, message: prompt });
92 - await withTimeout(done, this.options.timeoutMs, () => {
93 - this.abort();
94 - return new Error(
95 - `RPC worker timed out after ${this.options.timeoutMs}ms`,
96 - );
97 - });
98 - } finally {
99 - this.runningPrompt = false;
100 - this.currentPrompt = undefined;
101 - }
102 - }
104 - abort(): void {
105 - if (!this.proc || this.proc.killed) return;
106 - void this.command({ type: CMD_ABORT }).catch(() => {});
107 - }
109 - async dispose(): Promise<void> {
110 - const proc = this.proc;
111 - this.proc = undefined;
112 - this.rejectAll(new Error("RPC worker disposed"));
113 - if (!proc || proc.killed) return;
115 - let exited = false;
116 - const closed = new Promise<void>((resolve) => {
117 - proc.once("close", () => {
118 - exited = true;
119 - resolve();
120 - });
121 - });
122 - proc.stdin.end();
123 - proc.kill("SIGTERM");
124 - const killTimer = setTimeout(() => {
125 - if (!exited) proc.kill("SIGKILL");
126 - }, RPC_KILL_GRACE_MS);
127 - try {
128 - await closed;
129 - } finally {
130 - clearTimeout(killTimer);
131 - }
132 - }
134 - private ensureStarted(): void {
135 - if (this.proc && !this.proc.killed) return;
137 - fs.mkdirSync(this.options.sessionDir, { recursive: true });
138 - const invocation =
139 - this.options.invocation ?? getPiInvocation(workerArgs(this.options));
141 - this.stderr = "";
142 - this.proc = spawn(invocation.command, invocation.args, {
143 - cwd: this.options.cwd,
144 - env: {
145 - ...process.env,
146 - ...this.options.env,
147 - [LLMITERATE_WORKER_ENV]: "1",
148 - },
149 - shell: false,
150 - stdio: ["pipe", "pipe", "pipe"],
151 - });
153 - this.proc.stdout.on("data", (data) => this.handleStdout(data.toString()));
154 - this.proc.stderr.on("data", (data) => {
155 - this.stderr += data.toString();
156 - });
157 - this.proc.on("error", (error) => this.rejectAll(error));
158 - this.proc.on("close", (code) => {
159 - const message =
160 - this.stderr.trim() ||
161 - `RPC worker exited with code ${code ?? "unknown"}`;
162 - this.proc = undefined;
163 - this.rejectAll(new Error(message));
164 - });
165 - }
167 - private command(payload: RpcCommandPayload): Promise<unknown> {
168 - this.ensureStarted();
169 - if (!this.proc?.stdin.writable)
170 - return Promise.reject(new Error("RPC worker stdin closed"));
172 - const id = `llmiterate-${this.nextId++}`;
173 - const line = JSON.stringify({ id, ...payload }) + "\n";
175 - return new Promise((resolve, reject) => {
176 - this.pending.set(id, { command: payload.type, resolve, reject });
177 - this.proc?.stdin.write(line, (error) => {
178 - if (!error) return;
179 - this.pending.delete(id);
180 - reject(error);
181 - });
182 - });
183 - }
185 - private handleStdout(chunk: string): void {
186 - this.stdoutBuffer += chunk;
187 - const lines = this.stdoutBuffer.split("\n");
188 - this.stdoutBuffer = lines.pop() ?? "";
189 - for (const line of lines) this.handleLine(line);
190 - }
192 - private handleLine(line: string): void {
193 - if (!line.trim()) return;
195 - let event: RpcWireEvent;
196 - try {
197 - event = parseRpcObject(line);
198 - } catch (error) {
199 - this.failProtocol(errorMessage(error));
200 - return;
201 - }
203 - if (isRpcResponse(event)) {
204 - this.handleResponse(event);
205 - return;
206 - }
208 - this.options.onEvent(event as RpcEvent);
209 - if (event.type === AGENT_END_EVENT) this.currentPrompt?.resolve();
210 - }
212 - private handleResponse(response: RpcResponse): void {
213 - const id = typeof response.id === "string" ? response.id : undefined;
214 - if (!id) return;
216 - const pending = this.pending.get(id);
217 - if (!pending) return;
218 - this.pending.delete(id);
220 - if (response.success === false) {
221 - const reason = response.error ?? `${pending.command} failed`;
222 - pending.reject(new Error(String(reason)));
223 - return;
224 - }
225 - pending.resolve(response.data ?? response);
226 - }
228 - private failProtocol(message: string): void {
229 - this.proc?.kill("SIGTERM");
230 - this.rejectAll(new Error(message));
231 - }
233 - private rejectAll(error: Error): void {
234 - for (const pending of this.pending.values()) pending.reject(error);
235 - this.pending.clear();
236 - this.currentPrompt?.reject(error);
237 - this.currentPrompt = undefined;
238 - this.runningPrompt = false;
239 - }
242 -function parseRpcObject(line: string): RpcWireEvent {
243 - const parsed = JSON.parse(line);
244 - if (!isObject(parsed) || typeof parsed.type !== "string")
245 - throw new Error(`invalid RPC event: ${line}`);
246 - return { ...parsed, type: parsed.type };
249 -function isRpcResponse(event: RpcWireEvent): event is RpcResponse {
250 - return event.type === RESPONSE_EVENT;
253 -function errorMessage(error: unknown): string {
254 - return error instanceof Error ? error.message : String(error);
257 -function isObject(value: unknown): value is Record<string, unknown> {
258 - return typeof value === "object" && value !== null && !Array.isArray(value);
261 -function withTimeout<T>(
262 - promise: Promise<T>,
263 - timeoutMs: number | undefined,
264 - makeError: () => Error,
265 -): Promise<T> {
266 - if (!timeoutMs) return promise;
267 - return new Promise((resolve, reject) => {
268 - const timer = setTimeout(() => reject(makeError()), timeoutMs);
269 - promise.then(
270 - (value) => {
271 - clearTimeout(timer);
272 - resolve(value);
273 - },
274 - (error) => {
275 - clearTimeout(timer);
276 - reject(error);
277 - },
278 - );
279 - });
282 -export function workerArgs(
283 - options: Pick<
284 - RpcWorkerOptions,
285 - "sessionDir" | "model" | "thinking" | "appendSystemPrompt" | "offline"
286 - >,
287 -): string[] {
288 - const args = ["--mode", "rpc"];
289 - if (options.offline !== false) args.push("--offline");
290 - args.push("--session-dir", options.sessionDir);
291 - args.push(
292 - "--append-system-prompt",
293 - options.appendSystemPrompt ?? WORKER_SYSTEM_PROMPT,
294 - );
295 - if (options.model) args.push("--model", options.model);
296 - if (options.thinking) args.push("--thinking", options.thinking);
297 - return args;
300 -function getPiInvocation(args: string[]): PiInvocation {
301 - const currentScript = process.argv[1];
302 - const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
303 - if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
304 - return { command: process.execPath, args: [currentScript, ...args] };
305 - }
307 - const execName = path.basename(process.execPath).toLowerCase();
308 - const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
309 - return isGenericRuntime
310 - ? { command: "pi", args }
311 - : { command: process.execPath, args };

extensions/llmiterate/state.ts

Deleted
deleted file mode 100644
1 -import * as fs from "node:fs";
2 -import * as path from "node:path";
3 -import { STATE_FILE } from "./constants";
4 -import { isObject } from "./util";
6 -export type MarkerRunStatus = "queued" | "running" | "done" | "failed";
8 -export interface MarkerRunState {
9 - file: string;
10 - startLine: number;
11 - endLine: number;
12 - promptHash: string;
13 - promptPreview: string;
14 - status: MarkerRunStatus;
15 - attempts: number;
16 - queuedAt: number;
17 - updatedAt: number;
18 - lastError?: string;
21 -export interface LlmiterateState {
22 - version: 1;
23 - markers: Record<string, MarkerRunState>;
26 -export function loadState(storeDir: string): LlmiterateState {
27 - try {
28 - const parsed = JSON.parse(
29 - fs.readFileSync(path.join(storeDir, STATE_FILE), "utf-8"),
30 - );
31 - if (!isObject(parsed) || parsed.version !== 1 || !isObject(parsed.markers))
32 - return emptyState();
33 - return {
34 - version: 1,
35 - markers: resetInflightMarkers(parseMarkerRunStates(parsed.markers)),
36 - };
37 - } catch {
38 - return emptyState();
39 - }
42 -export function saveState(storeDir: string, state: LlmiterateState): void {
43 - fs.mkdirSync(storeDir, { recursive: true });
44 - fs.writeFileSync(
45 - path.join(storeDir, STATE_FILE),
46 - JSON.stringify(state, null, 2) + "\n",
47 - "utf-8",
48 - );
51 -export function emptyState(): LlmiterateState {
52 - return { version: 1, markers: {} };
55 -function resetInflightMarkers(
56 - markers: Record<string, MarkerRunState>,
57 -): Record<string, MarkerRunState> {
58 - const now = Date.now();
59 - for (const marker of Object.values(markers)) {
60 - if (marker.status === "queued" || marker.status === "running") {
61 - marker.status = "failed";
62 - marker.lastError = "pi stopped before marker finished";
63 - marker.updatedAt = now;
64 - }
65 - }
66 - return markers;
69 -function parseMarkerRunStates(
70 - raw: Record<string, unknown>,
71 -): Record<string, MarkerRunState> {
72 - const markers: Record<string, MarkerRunState> = {};
73 - for (const [key, value] of Object.entries(raw)) {
74 - if (isMarkerRunState(value)) markers[key] = value;
75 - }
76 - return markers;
79 -function isMarkerRunState(value: unknown): value is MarkerRunState {
80 - if (!isObject(value)) return false;
81 - return (
82 - typeof value.file === "string" &&
83 - typeof value.startLine === "number" &&
84 - typeof value.endLine === "number" &&
85 - typeof value.promptHash === "string" &&
86 - typeof value.promptPreview === "string" &&
87 - isMarkerRunStatus(value.status) &&
88 - typeof value.attempts === "number" &&
89 - typeof value.queuedAt === "number" &&
90 - typeof value.updatedAt === "number" &&
91 - (value.lastError === undefined || typeof value.lastError === "string")
92 - );
95 -function isMarkerRunStatus(value: unknown): value is MarkerRunStatus {
96 - return (
97 - value === "queued" ||
98 - value === "running" ||
99 - value === "done" ||
100 - value === "failed"
101 - );

extensions/llmiterate/types.ts

Deleted
deleted file mode 100644
1 -import type { LlmiterateConfig, MarkerPrompt } from "./core";
3 -export type RunStatus = "queued" | "running" | "done" | "error";
5 -export interface LlmiterateRun {
6 - id: number;
7 - block: MarkerPrompt;
8 - projectFile: string;
9 - absoluteFile: string;
10 - fullPrompt: string;
11 - status: RunStatus;
12 - queuedAt: number;
13 - updatedAt: number;
14 - assistantText: string;
15 - toolText: string;
16 - error?: string;
17 -}
19 -export interface UiState {
20 - config?: LlmiterateConfig;
21 - lockError?: string;
22 - watchErrors: number;
23 - watchDirs: number;
24 - activeRun?: LlmiterateRun;
25 - queuedRuns: number;
26 -}
28 -export interface RpcTextPart {
29 - type?: string;
30 - text?: unknown;
31 -}
33 -export interface RpcMessage {
34 - role?: string;
35 - content?: string | RpcTextPart[];
36 -}
38 -export interface RpcAssistantMessageEvent {
39 - type?: string;
40 - contentIndex?: unknown;
41 - delta?: unknown;
42 - content?: unknown;
43 -}
45 -export type RpcEvent =
46 - | {
47 - type: "message_update";
48 - assistantMessageEvent?: RpcAssistantMessageEvent;
49 - }
50 - | { type: "message_end"; message?: RpcMessage }
51 - | { type: "tool_execution_start"; toolName?: unknown }
52 - | {
53 - type: "tool_execution_end";
54 - toolName?: unknown;
55 - isError?: unknown;
56 - result?: RpcToolResult;
57 - }
58 - | { type: "agent_end" };
60 -export interface RpcToolResult {
61 - content?: RpcTextPart[];
62 -}

extensions/llmiterate/ui.ts

Deleted
deleted file mode 100644
1 -import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 -import type { UiState } from "./types";
4 -export const STATUS_KEY = "llmiterate";
6 -export function renderLlmiterateStatus(
7 - ctx: ExtensionContext | undefined,
8 - state: UiState,
9 -): void {
10 - if (!ctx?.hasUI) return;
11 - ctx.ui.setStatus(STATUS_KEY, statusLine(ctx, state));
12 -}
14 -function statusLine(ctx: ExtensionContext, state: UiState): string | undefined {
15 - if (!state.config) return undefined;
17 - if (!state.config.enabled) return undefined;
19 - const theme = ctx.ui.theme;
20 - if (state.lockError) return theme.fg("dim", "llmiterate standby");
21 - if (state.watchErrors > 0)
22 - return theme.fg(
23 - "warning",
24 - `llmiterate ${state.watchErrors} watch error(s)`,
25 - );
26 - if (state.activeRun)
27 - return theme.fg(
28 - "accent",
29 - `llmiterate ${state.activeRun.status} ${state.activeRun.block.file}:${state.activeRun.block.startLine}`,
30 - );
31 - if (state.queuedRuns > 0)
32 - return theme.fg("warning", `llmiterate queued ${state.queuedRuns}`);
33 - return theme.fg("dim", "llmiterate watching .");
34 -}

extensions/llmiterate/util.ts

Deleted
deleted file mode 100644
1 -export function toSlash(s: string): string {
2 - return s.includes("\\") ? s.replace(/\\/g, "/") : s;
3 -}
5 -export function previewText(text: string, maxChars: number): string {
6 - const oneLine = text.replace(/\s+/g, " ").trim();
7 - return oneLine.length > maxChars
8 - ? `${oneLine.slice(0, Math.max(0, maxChars - 1))}…`
9 - : oneLine;
10 -}
12 -export function isObject(value: unknown): value is Record<string, unknown> {
13 - return typeof value === "object" && value !== null && !Array.isArray(value);
14 -}
16 -export function stringArray(value: unknown, fallback: string[]): string[] {
17 - return Array.isArray(value) &&
18 - value.every((v) => typeof v === "string" && v.trim())
19 - ? value.map((v) => v.trim())
20 - : [...fallback];
21 -}
23 -export function positiveInt(value: unknown, fallback: number): number {
24 - return typeof value === "number" && Number.isFinite(value) && value > 0
25 - ? Math.floor(value)
26 - : fallback;
27 -}

extensions/llmiterate/watcher.ts

Deleted
deleted file mode 100644
1 -import * as fs from "node:fs";
2 -import * as path from "node:path";
3 -import type { LlmiterateConfig } from "./config";
4 -import { GitIgnoreMatcher } from "./gitignore";
5 -import {
6 - type CompiledPathFilter,
7 - shouldIncludeCompiledPath,
8 - shouldWatchDirectory,
9 -} from "./path-filter";
10 -import { toSlash } from "./util";
12 -const DIRECTORY_REFRESH_MS = 50;
13 -const IGNORE_FILE_NAMES = new Set([".gitignore", ".ignore"]);
15 -type FileHandler = (absolutePath: string) => void;
16 -type ErrorHandler = () => void;
18 -interface RefreshOptions {
19 - scheduleFiles: boolean;
20 - fileMtimeSinceMs?: number;
23 -interface IgnoreContext {
24 - matcher: GitIgnoreMatcher;
25 - stamp: string;
28 -export class ProjectWatcher {
29 - private readonly watchers = new Map<string, fs.FSWatcher>();
30 - private readonly fileTimers = new Map<
31 - string,
32 - ReturnType<typeof setTimeout>
33 - >();
34 - private readonly dirTimers = new Map<string, ReturnType<typeof setTimeout>>();
35 - private readonly ignoreContexts = new Map<string, IgnoreContext>();
36 - private readonly scheduledFileMtimes = new Map<string, number>();
37 - private watchLimitHit = false;
38 - private eventMtimeSinceMs: number | undefined;
40 - public errorCount = 0;
42 - get watcherCount(): number {
43 - return this.watchers.size;
44 - }
46 - constructor(
47 - private readonly root: string,
48 - private readonly config: LlmiterateConfig,
49 - private readonly pathFilter: CompiledPathFilter,
50 - private readonly onFileReady: FileHandler,
51 - private readonly onError: ErrorHandler,
52 - ) {}
54 - start(): void {
55 - if (!shouldWatchDirectory("", this.pathFilter)) return;
57 - const root = path.resolve(this.root);
58 - const startedAt = performance.timeOrigin + performance.now();
59 - this.watchTree(root, { scheduleFiles: false });
60 - // fs.watch can miss changes made immediately after watcher creation.
61 - // Reconcile watched dirs once, but only queue files modified after start.
62 - this.scheduleWatchedTreeRefresh(root, {
63 - scheduleFiles: true,
64 - fileMtimeSinceMs: startedAt,
65 - });
66 - }
68 - stop(): void {
69 - for (const timer of this.fileTimers.values()) clearTimeout(timer);
70 - for (const timer of this.dirTimers.values()) clearTimeout(timer);
71 - for (const watcher of this.watchers.values()) watcher.close();
72 - this.fileTimers.clear();
73 - this.dirTimers.clear();
74 - this.watchers.clear();
75 - this.ignoreContexts.clear();
76 - this.scheduledFileMtimes.clear();
77 - this.eventMtimeSinceMs = undefined;
78 - }
80 - scanAll(onFile: (absolutePath: string) => number): number {
81 - let total = 0;
82 - this.walkFiles(this.root, (file) => {
83 - total += onFile(file);
84 - });
85 - return total;
86 - }
88 - private watchTree(dir: string, options: RefreshOptions): void {
89 - const abs = path.resolve(dir);
90 - if (this.watchers.has(abs)) return;
92 - if (!this.reserveWatchSlot()) return;
94 - try {
95 - const watcher = fs.watch(
96 - abs,
97 - { persistent: false },
98 - (eventType, filename) => {
99 - if (!filename) {
100 - this.scheduleWatchedTreeRefresh(abs, { scheduleFiles: true }, true);
101 - return;
102 - }
104 - const child = path.join(abs, filename.toString());
105 - if (IGNORE_FILE_NAMES.has(path.basename(child))) {
106 - this.scheduleWatchedTreeRefresh(
107 - abs,
108 - { scheduleFiles: false },
109 - true,
110 - );
111 - return;
112 - }
114 - this.handlePathEvent(child);
115 - if (eventType === "rename")
116 - this.scheduleDirectoryRefresh(abs, { scheduleFiles: true }, true);
117 - },
118 - );
119 - watcher.on("error", () => {
120 - this.recordError();
121 - this.unwatchTree(abs);
122 - });
123 - watcher.on("close", () => this.watchers.delete(abs));
124 - this.watchers.set(abs, watcher);
125 - } catch {
126 - this.recordError();
127 - this.refreshDirectory(abs, options);
128 - return;
129 - }
131 - this.refreshDirectory(abs, options);
132 - }
134 - private handlePathEvent(absPath: string): void {
135 - let stat: fs.Stats | undefined;
136 - try {
137 - stat = fs.statSync(absPath);
138 - } catch {
139 - return;
140 - }
142 - if (stat.isDirectory()) {
143 - if (this.shouldWatchDir(absPath))
144 - this.watchTree(absPath, { scheduleFiles: true });
145 - return;
146 - }
148 - if (
149 - stat.isFile() &&
150 - this.isFreshEnough(absPath, {
151 - scheduleFiles: true,
152 - fileMtimeSinceMs: this.eventMtimeSinceMs,
153 - })
154 - )
155 - this.scheduleFile(absPath);
156 - }
158 - private refreshDirectory(abs: string, options: RefreshOptions): void {
159 - this.loadIgnoreContext(abs);
161 - let entries: fs.Dirent[];
162 - try {
163 - entries = fs.readdirSync(abs, { withFileTypes: true });
164 - } catch {
165 - return;
166 - }
168 - for (const entry of entries) {
169 - const child = path.join(abs, entry.name);
170 - const rel = this.projectRel(child);
171 - if (entry.isDirectory()) {
172 - if (
173 - this.isIgnored(rel, true) ||
174 - !shouldWatchDirectory(rel, this.pathFilter)
175 - )
176 - continue;
177 - this.watchTree(child, options);
178 - continue;
179 - }
180 - if (entry.isFile()) {
181 - if (
182 - this.isIgnored(rel, false) ||
183 - !shouldIncludeCompiledPath(rel, this.pathFilter)
184 - )
185 - continue;
187 - if (!options.scheduleFiles) {
188 - this.recordFileMtime(rel, child);
189 - continue;
190 - }
192 - if (this.isFreshEnough(child, options)) this.scheduleFile(child);
193 - }
194 - }
195 - }
197 - private scheduleDirectoryRefresh(
198 - abs: string,
199 - options: RefreshOptions,
200 - reloadIgnores = false,
201 - ): void {
202 - const existing = this.dirTimers.get(abs);
203 - if (existing) clearTimeout(existing);
204 - this.dirTimers.set(
205 - abs,
206 - setTimeout(() => {
207 - this.dirTimers.delete(abs);
208 - if (reloadIgnores) this.invalidateIgnoreContextsUnder(abs);
209 - this.reconcileWatchersUnder(abs);
210 - this.refreshDirectory(abs, options);
211 - }, DIRECTORY_REFRESH_MS),
212 - );
213 - }
215 - private scheduleWatchedTreeRefresh(
216 - abs: string,
217 - options: RefreshOptions,
218 - reloadIgnores = false,
219 - ): void {
220 - const existing = this.dirTimers.get(abs);
221 - if (existing) clearTimeout(existing);
222 - this.dirTimers.set(
223 - abs,
224 - setTimeout(() => {
225 - this.dirTimers.delete(abs);
226 - if (reloadIgnores) this.invalidateIgnoreContextsUnder(abs);
227 - this.reconcileWatchersUnder(abs);
228 - for (const dir of [...this.watchers.keys()]) {
229 - if (dir === abs || isDescendant(abs, dir))
230 - this.refreshDirectory(dir, options);
231 - }
232 - }, DIRECTORY_REFRESH_MS),
233 - );
234 - }
236 - private reconcileWatchersUnder(abs: string): void {
237 - for (const dir of [...this.watchers.keys()]) {
238 - if (dir !== abs && !isDescendant(abs, dir)) continue;
239 - const rel = this.projectRel(dir);
240 - if (!fs.existsSync(dir) || (rel && this.isIgnored(rel, true)))
241 - this.unwatchTree(dir);
242 - }
243 - }
245 - private unwatchTree(abs: string): void {
246 - const dirs = [
247 - abs,
248 - ...[...this.watchers.keys()].filter((dir) => isDescendant(abs, dir)),
249 - ].sort((a, b) => b.length - a.length);
250 - for (const dir of dirs) {
251 - const watcher = this.watchers.get(dir);
252 - this.watchers.delete(dir);
253 - this.ignoreContexts.delete(this.projectRel(dir));
254 - try {
255 - watcher?.close();
256 - } catch {}
257 - }
258 - }
260 - private reserveWatchSlot(): boolean {
261 - if (this.watchers.size < this.config.maxWatchDirs) return true;
262 - if (!this.watchLimitHit) {
263 - this.watchLimitHit = true;
264 - this.recordError();
265 - }
266 - return false;
267 - }
269 - private isFreshEnough(absPath: string, options: RefreshOptions): boolean {
270 - if (options.fileMtimeSinceMs === undefined) return true;
271 - try {
272 - return fs.statSync(absPath).mtimeMs > options.fileMtimeSinceMs;
273 - } catch {
274 - return false;
275 - }
276 - }
278 - private scheduleFile(absPath: string): void {
279 - const rel = this.projectRel(absPath);
280 - if (
281 - !isSafeProjectRel(rel) ||
282 - this.isIgnored(rel, false) ||
283 - !shouldIncludeCompiledPath(rel, this.pathFilter)
284 - )
285 - return;
287 - const mtimeMs = fileMtimeMs(absPath);
288 - const previousMtimeMs = this.scheduledFileMtimes.get(rel);
289 - if (
290 - mtimeMs !== undefined &&
291 - previousMtimeMs !== undefined &&
292 - mtimeMs <= previousMtimeMs
293 - )
294 - return;
295 - if (mtimeMs !== undefined) this.scheduledFileMtimes.set(rel, mtimeMs);
297 - const existing = this.fileTimers.get(rel);
298 - if (existing) clearTimeout(existing);
299 - this.fileTimers.set(
300 - rel,
301 - setTimeout(() => {
302 - this.fileTimers.delete(rel);
303 - // Refresh may run after debounce; pin emitted mtime to avoid duplicate queues.
304 - const readyMtimeMs = fileMtimeMs(absPath);
305 - if (readyMtimeMs !== undefined)
306 - this.scheduledFileMtimes.set(rel, readyMtimeMs);
307 - this.onFileReady(absPath);
308 - }, this.config.debounceMs),
309 - );
310 - }
312 - private recordFileMtime(rel: string, absPath: string): void {
313 - const mtimeMs = fileMtimeMs(absPath);
314 - if (mtimeMs !== undefined) this.scheduledFileMtimes.set(rel, mtimeMs);
315 - }
317 - private walkFiles(dir: string, onFile: FileHandler): void {
318 - this.loadIgnoreContext(dir);
320 - let entries: fs.Dirent[];
321 - try {
322 - entries = fs.readdirSync(dir, { withFileTypes: true });
323 - } catch {
324 - return;
325 - }
327 - for (const entry of entries) {
328 - const abs = path.join(dir, entry.name);
329 - const rel = this.projectRel(abs);
330 - if (entry.isDirectory()) {
331 - if (
332 - this.isIgnored(rel, true) ||
333 - !shouldWatchDirectory(rel, this.pathFilter)
334 - )
335 - continue;
336 - this.walkFiles(abs, onFile);
337 - continue;
338 - }
339 - if (
340 - entry.isFile() &&
341 - !this.isIgnored(rel, false) &&
342 - shouldIncludeCompiledPath(rel, this.pathFilter)
343 - )
344 - onFile(abs);
345 - }
346 - }
348 - private projectRel(absPath: string): string {
349 - return toSlash(path.relative(this.root, absPath));
350 - }
352 - private shouldWatchDir(absPath: string): boolean {
353 - const rel = this.projectRel(absPath);
354 - return (
355 - isSafeProjectRel(rel) &&
356 - !this.isIgnored(rel, true) &&
357 - shouldWatchDirectory(rel, this.pathFilter)
358 - );
359 - }
361 - private loadIgnoreContext(absDir: string): void {
362 - const rel = this.projectRel(absDir);
363 - const stamp = this.ignoreStamp(absDir);
364 - const cached = this.ignoreContexts.get(rel);
365 - if (cached?.stamp === stamp) return;
367 - const parent = path.dirname(absDir);
368 - if (parent !== absDir && isDescendant(this.root, absDir))
369 - this.loadIgnoreContext(parent);
371 - const matcher = new GitIgnoreMatcher();
372 - for (const name of IGNORE_FILE_NAMES) {
373 - try {
374 - matcher.add(fs.readFileSync(path.join(absDir, name), "utf-8"));
375 - } catch {}
376 - }
377 - this.ignoreContexts.set(rel, { matcher, stamp });
378 - }
380 - private isIgnored(relPath: string, directory: boolean): boolean {
381 - const rel = toSlash(relPath);
382 - this.loadIgnoreContext(path.dirname(path.join(this.root, rel)));
383 - for (const [base, context] of this.ignoreContexts) {
384 - if (base && rel !== base && !rel.startsWith(`${base}/`)) continue;
385 - const local = base ? rel.slice(base.length + 1) : rel;
386 - if (!local) continue;
387 - if (
388 - context.matcher.ignores(local) ||
389 - (directory && context.matcher.ignores(`${local}/`))
390 - )
391 - return true;
392 - }
393 - return false;
394 - }
396 - private ignoreStamp(absDir: string): string {
397 - return [...IGNORE_FILE_NAMES]
398 - .map((name) => {
399 - try {
400 - const stat = fs.statSync(path.join(absDir, name));
401 - return `${name}:${stat.mtimeMs}:${stat.size}`;
402 - } catch {
403 - return `${name}:missing`;
404 - }
405 - })
406 - .join("|");
407 - }
409 - private invalidateIgnoreContextsUnder(abs: string): void {
410 - const rel = this.projectRel(abs);
411 - for (const base of [...this.ignoreContexts.keys()]) {
412 - if (base === rel || !rel || base.startsWith(`${rel}/`))
413 - this.ignoreContexts.delete(base);
414 - }
415 - }
417 - private recordError(): void {
418 - this.errorCount++;
419 - this.onError();
420 - }
423 -function fileMtimeMs(absPath: string): number | undefined {
424 - try {
425 - return fs.statSync(absPath).mtimeMs;
426 - } catch {
427 - return undefined;
428 - }
431 -function isSafeProjectRel(rel: string): boolean {
432 - return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel);
435 -function isDescendant(parent: string, child: string): boolean {
436 - const rel = path.relative(parent, child);
437 - return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel);

extensions/split-fork/README.md

Deleted
deleted file mode 100644
1 -# split-fork
3 -Fork Pi into a Ghostty split.
5 -## Install / load
7 -Loaded through the root `pi-ext` package.
8 -See [root README](../../README.md).
10 -## Commands / tools / settings
12 -- Commands:
13 - - `/split-fork [prompt]`
14 -- Tools:
15 - none
16 -- Hooks:
17 - - `session_start`
18 -- Settings:
19 - none
21 -## Behavior
23 -`/split-fork` copies the current session branch into a new session file and opens a right-hand Ghostty split running Pi on that fork.
24 -If a prompt is provided, the new Pi process receives it as startup input.
26 -Requirements:
28 -- macOS
29 -- Ghostty
30 -- `osascript`
32 -On non-macOS hosts the command exits with a warning.
33 -On macOS the extension warns at session start when `osascript` is missing.

extensions/split-fork/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
2 -import { tmpdir } from "node:os";
3 -import path from "node:path";
4 -import { afterEach, describe, expect, it } from "vitest";
5 -import { createTestSession, type TestSession } from "../../../test/harness";
6 -import splitForkExtension, { __test } from "../index";
8 -let t: TestSession | undefined;
9 -let fakeBin: string | undefined;
11 -afterEach(() => {
12 - t?.dispose();
13 - if (fakeBin) rmSync(fakeBin, { recursive: true, force: true });
14 - t = undefined;
15 - fakeBin = undefined;
16 -});
18 -describe("split-fork extension", () => {
19 - it("loads in real Pi extension runtime", async () => {
20 - t = await createTestSession({ extensionFactories: [splitForkExtension] });
22 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
23 - });
25 - it("finds osascript through native PATH access", () => {
26 - fakeBin = mkdtempSync(path.join(tmpdir(), "pi-split-fork-bin-"));
27 - copyFileSync(process.execPath, path.join(fakeBin, "osascript"));
29 - expect(__test.hasOsascript({ Path: fakeBin })).toBe(true);
30 - expect(__test.hasOsascript({ PATH: path.join(fakeBin, "missing") })).toBe(
31 - false,
32 - );
33 - });
35 - it("shell quotes prompt-safe command parts", () => {
36 - expect(__test.shellQuote("can't")).toBe("'can'\"'\"'t'");
37 - expect(__test.shellQuote("")).toBe("''");
38 - });
40 - it("builds startup input with session and prompt", () => {
41 - const startup = __test.buildPiStartupInput(
42 - "/tmp/session.jsonl",
43 - "review this",
44 - );
46 - expect(startup).toContain("'--session' '/tmp/session.jsonl'");
47 - expect(startup).toContain("'--' 'review this'");
48 - expect(startup.endsWith("\n")).toBe(true);
49 - });
50 -});

extensions/split-fork/index.ts

Deleted
deleted file mode 100644
1 -import { randomUUID } from "node:crypto";
2 -import { accessSync, constants, existsSync, promises as fs } from "node:fs";
3 -import path from "node:path";
4 -import type {
5 - ExtensionAPI,
6 - ExtensionCommandContext,
7 -} from "@earendil-works/pi-coding-agent";
9 -const GHOSTTY_SPLIT_SCRIPT = `on run argv
10 - set targetCwd to item 1 of argv
11 - set startupInput to item 2 of argv
12 - tell application "Ghostty"
13 - set cfg to new surface configuration
14 - set initial working directory of cfg to targetCwd
15 - set initial input of cfg to startupInput
16 - if (count of windows) > 0 then
17 - try
18 - set frontWindow to front window
19 - set targetTerminal to focused terminal of selected tab of frontWindow
20 - split targetTerminal direction right with configuration cfg
21 - on error
22 - new window with configuration cfg
23 - end try
24 - else
25 - new window with configuration cfg
26 - end if
27 - activate
28 - end tell
29 -end run`;
31 -function shellQuote(value: string): string {
32 - if (value.length === 0) return "''";
33 - return `'${value.replace(/'/g, `'"'"'`)}'`;
36 -function getPiInvocationParts(): string[] {
37 - const currentScript = process.argv[1];
38 - if (currentScript && existsSync(currentScript)) {
39 - return [process.execPath, currentScript];
40 - }
42 - const execName = path.basename(process.execPath).toLowerCase();
43 - if (!/^(node|bun)(\.exe)?$/.test(execName)) return [process.execPath];
44 - return ["pi"];
47 -function buildPiStartupInput(
48 - sessionFile: string | undefined,
49 - prompt: string,
50 -): string {
51 - const commandParts = [...getPiInvocationParts()];
52 - if (sessionFile) commandParts.push("--session", sessionFile);
53 - if (prompt) commandParts.push("--", prompt);
54 - return `${commandParts.map(shellQuote).join(" ")}\n`;
57 -function hasOsascript(env = process.env): boolean {
58 - const pathKey = Object.keys(env).find((key) => key.toLowerCase() === "path");
59 - for (const directory of (pathKey ? env[pathKey] : "")?.split(
60 - path.delimiter,
61 - ) ?? []) {
62 - try {
63 - accessSync(
64 - path.join(directory.replace(/^"|"$/gu, ""), "osascript"),
65 - constants.X_OK,
66 - );
67 - return true;
68 - } catch {}
69 - }
70 - return false;
73 -async function createForkedSession(
74 - ctx: ExtensionCommandContext,
75 -): Promise<string | undefined> {
76 - const sessionFile = ctx.sessionManager.getSessionFile();
77 - if (!sessionFile) return undefined;
79 - const sessionDir = path.dirname(sessionFile);
80 - const branchEntries = ctx.sessionManager.getBranch();
81 - const currentHeader = ctx.sessionManager.getHeader();
82 - const timestamp = new Date().toISOString();
83 - const newSessionId = randomUUID();
84 - const newSessionFile = path.join(
85 - sessionDir,
86 - `${timestamp.replace(/[:.]/g, "-")}_${newSessionId}.jsonl`,
87 - );
88 - const newHeader = {
89 - type: "session",
90 - version: currentHeader?.version ?? 3,
91 - id: newSessionId,
92 - timestamp,
93 - cwd: currentHeader?.cwd ?? ctx.cwd,
94 - parentSession: sessionFile,
95 - };
96 - const lines = [
97 - JSON.stringify(newHeader),
98 - ...branchEntries.map((entry) => JSON.stringify(entry)),
99 - ].join("\n");
101 - await fs.mkdir(sessionDir, { recursive: true });
102 - await fs.writeFile(newSessionFile, `${lines}\n`, "utf8");
103 - return newSessionFile;
106 -export const __test = { buildPiStartupInput, hasOsascript, shellQuote };
108 -export default function splitForkExtension(pi: ExtensionAPI) {
109 - pi.on("session_start", (_event, ctx) => {
110 - if (process.platform === "darwin" && !hasOsascript() && ctx.hasUI) {
111 - ctx.ui.notify(
112 - "split-fork: osascript not found; /split-fork unavailable",
113 - "warning",
114 - );
115 - }
116 - });
118 - pi.registerCommand("split-fork", {
119 - description:
120 - "Fork this session into a new Pi process in a right-hand Ghostty split. Usage: /split-fork [prompt]",
121 - handler: async (args, ctx) => {
122 - if (process.platform !== "darwin") {
123 - ctx.ui.notify(
124 - "/split-fork requires macOS, Ghostty, and osascript.",
125 - "warning",
126 - );
127 - return;
128 - }
129 - if (!hasOsascript()) {
130 - ctx.ui.notify("/split-fork requires osascript on PATH.", "error");
131 - return;
132 - }
134 - const wasBusy = !ctx.isIdle();
135 - const prompt = args.trim();
136 - const forkedSessionFile = await createForkedSession(ctx);
137 - const startupInput = buildPiStartupInput(forkedSessionFile, prompt);
138 - const result = await pi.exec("osascript", [
139 - "-e",
140 - GHOSTTY_SPLIT_SCRIPT,
141 - "--",
142 - ctx.cwd,
143 - startupInput,
144 - ]);
146 - if (result.code !== 0) {
147 - const reason =
148 - result.stderr?.trim() ||
149 - result.stdout?.trim() ||
150 - "unknown osascript error";
151 - ctx.ui.notify(`Failed to launch Ghostty split: ${reason}`, "error");
152 - if (forkedSessionFile) {
153 - ctx.ui.notify(
154 - `Forked session was created: ${forkedSessionFile}`,
155 - "info",
156 - );
157 - }
158 - return;
159 - }
161 - if (!forkedSessionFile) {
162 - ctx.ui.notify(
163 - "Opened a Ghostty split without a persisted session.",
164 - "warning",
165 - );
166 - return;
167 - }
169 - const suffix = prompt ? " and sent prompt" : "";
170 - ctx.ui.notify(
171 - `Forked to ${path.basename(forkedSessionFile)} in a Ghostty split${suffix}.`,
172 - "info",
173 - );
174 - if (wasBusy) {
175 - ctx.ui.notify(
176 - "Forked from committed session state; in-flight turn continues here.",
177 - "info",
178 - );
179 - }
180 - },
181 - });

extensions/split-fork/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-split-fork",
3 - "private": true,
4 - "type": "module",
5 - "main": "index.ts",
6 - "license": "MIT",
7 - "description": "Fork Pi into a Ghostty split.",
8 - "keywords": [
9 - "pi",
10 - "pi-extension"
11 - ],
12 - "peerDependencies": {
13 - "@earendil-works/pi-coding-agent": "*"
14 - },
15 - "devDependencies": {
16 - "@marcfargas/pi-test-harness": "^0.6.1",
17 - "vitest": "^4.1.9"
18 - }
19 -}

package-lock.json

Modified
99 99 "@earendil-works/pi-coding-agent": "*"
102 - "extensions/cwd": {
103 - "name": "@bugabinga/pi-ext-cwd",
104 - "license": "MIT",
105 - "devDependencies": {
106 - "@marcfargas/pi-test-harness": "^0.6.1",
107 - "vitest": "^4.1.9"
108 - },
109 - "peerDependencies": {
110 - "@earendil-works/pi-coding-agent": "*"
112 - },
113 102 "extensions/decay": {
114 103 "name": "@bugabinga/pi-ext-decay",
115 104 "license": "MIT",
161 150 "typebox": "*"
164 - "extensions/goldfish": {
165 - "name": "@bugabinga/pi-ext-goldfish",
166 - "license": "MIT",
167 - "devDependencies": {
168 - "@marcfargas/pi-test-harness": "^0.6.1",
169 - "vitest": "^4.1.8"
170 - },
171 - "peerDependencies": {
172 - "@earendil-works/pi-ai": "*",
173 - "@earendil-works/pi-coding-agent": "*",
174 - "@earendil-works/pi-tui": "*",
175 - "typebox": "*"
177 - },
178 153 "extensions/good-job": {
179 154 "name": "@bugabinga/pi-ext-good-job",
180 155 "license": "MIT",
295 270 "typebox": "*"
298 - "extensions/llmiterate": {
299 - "name": "@bugabinga/pi-ext-llmiterate",
300 - "license": "MIT",
301 - "devDependencies": {
302 - "@marcfargas/pi-test-harness": "^0.6.1",
303 - "vitest": "^4.1.9"
304 - },
305 - "peerDependencies": {
306 - "@earendil-works/pi-coding-agent": "*"
308 - },
309 273 "extensions/masks": {
310 274 "name": "@bugabinga/pi-ext-masks",
311 275 "license": "MIT",
445 409 "@earendil-works/pi-coding-agent": "*"
448 - "extensions/split-fork": {
449 - "name": "@bugabinga/pi-ext-split-fork",
450 - "license": "MIT",
451 - "devDependencies": {
452 - "@marcfargas/pi-test-harness": "^0.6.1",
453 - "vitest": "^4.1.9"
454 - },
455 - "peerDependencies": {
456 - "@earendil-works/pi-coding-agent": "*"
458 - },
459 412 "extensions/terse": {
460 413 "name": "@bugabinga/pi-ext-terse",
461 414 "license": "MIT",
1477 1430 "resolved": "extensions/cost",
1478 1431 "link": true
1480 - "node_modules/@bugabinga/pi-ext-cwd": {
1481 - "resolved": "extensions/cwd",
1482 - "link": true
1483 - },
1484 1433 "node_modules/@bugabinga/pi-ext-decay": {
1485 1434 "resolved": "extensions/decay",
1486 1435 "link": true
1497 1446 "resolved": "extensions/git-safe",
1498 1447 "link": true
1500 - "node_modules/@bugabinga/pi-ext-goldfish": {
1501 - "resolved": "extensions/goldfish",
1502 - "link": true
1503 - },
1504 1449 "node_modules/@bugabinga/pi-ext-good-job": {
1505 1450 "resolved": "extensions/good-job",
1506 1451 "link": true
1521 1466 "resolved": "extensions/leaks",
1522 1467 "link": true
1524 - "node_modules/@bugabinga/pi-ext-llmiterate": {
1525 - "resolved": "extensions/llmiterate",
1526 - "link": true
1527 - },
1528 1469 "node_modules/@bugabinga/pi-ext-masks": {
1529 1470 "resolved": "extensions/masks",
1530 1471 "link": true
1573 1514 "resolved": "extensions/session-rename",
1574 1515 "link": true
1576 - "node_modules/@bugabinga/pi-ext-split-fork": {
1577 - "resolved": "extensions/split-fork",
1578 - "link": true
1579 - },
1580 1517 "node_modules/@bugabinga/pi-ext-terse": {
1581 1518 "resolved": "extensions/terse",
1582 1519 "link": true