repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

rework llmiterate watcher scope

b78f5ea230bafafaa66f88d260a0fe254915ff89

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (14)

pi/agent/extensions/llmiterate/CHANGELOG.md

Modified
1 1 # Changelog
3 +## Unreleased
5 +- Make llmiterate manual: `/llmiterate` toggles cwd-scoped watcher on/off.
6 +- Remove upward project-root guessing; state/lock scope is current cwd.
7 +- Replace panel UX with status, one-shot status, and `explain <path>`.
8 +- Add command completions for public subcommands only.
9 +- Make marker comment prefixes extension-scoped.
10 +- Expand default cache/home excludes.
3 12 ## 0.1.0 - 2026-05-21
5 14 - a40a427 prepare extensions for npm release

pi/agent/extensions/llmiterate/README.md

Modified
2 2 <!-- !llmiterate -->
4 4 # llmiterate
6 -Editor-save bridge from comments to background Pi edits.
6 +Manual editor-save bridge from comments to background Pi edits.
8 8 ## Marker syntax
47 47 ## Comment prefixes
49 -Built in prefixes cover common languages:
49 +Prefixes are extension-scoped. Examples:
51 51 ```text
52 -// /// //! # ## ### -- --- ; ;; ;;; % %% * *> ' :: REM rem dnl DNL <!-- /* /**
52 +.ts/.rs/.java/.go // /// /* /**
53 +.py/.sh/.yaml #
54 +.md/.html/.xml <!-- -->
55 +.sql/.lua --
56 +.lisp/.clj ; ;; ;;;
57 +.tex % %%
55 -Config `commentPrefixes` appends to builtins:
60 +Unknown extensions do not run markers. Markdown only accepts HTML comments, so headings or bullets containing `llmiterate:` are inert.
62 +Config `commentPrefixes` appends by extension:
57 64 ```json
59 66 "llmiterate": {
60 - "commentPrefixes": ["COMMENT"]
67 + "commentPrefixes": {
68 + "foo": ["COMMENT"],
69 + "lua": ["--"]
70 + }
65 75 ## Replacement behavior
67 -On save or `/llmiterate scan`, matching markers are queued. A background Pi RPC worker edits files. Success means the marker span is gone/replaced.
77 +llmiterate is off until `/llmiterate` or `/llmiterate on` starts it. It watches the current Pi session directory, runs one initial scan, then queues matching markers on save. A background Pi RPC worker edits files. Success means the marker span is gone/replaced.
79 +Only one llmiterate watcher may own an exact real cwd at a time. A second Pi session started in the same cwd enters standby and reports the owning pid/host. Parent/child directories are independent; choosing overlapping scopes is user responsibility.
69 81 llmiterate itself does not mutate source files; only the worker uses normal Pi tools.
73 85 State lives in:
75 87 ```text
76 -${XDG_STATE_HOME:-~/.local/state}/pi/llmiterate/<projectHash>/state.json
88 +${XDG_STATE_HOME:-~/.local/state}/pi/llmiterate/<scopeHash>/state.json
79 91 Statuses:
82 94 queued | running | done | failed
85 -Duplicate saves do not start duplicate queued/running jobs. Failed markers remain retryable on next save/scan. Markers are only `done` after the worker finishes and the marker no longer exists.
97 +Duplicate saves do not start duplicate queued/running jobs. Failed markers remain retryable on next save or debug scan. Markers are only `done` after the worker finishes and the marker no longer exists.
87 99 ## Worker
92 104 LLMITERATE_WORKER=1 pi \
93 105 --mode rpc \
94 106 --offline \
95 - --session-dir <state>/llmiterate/<projectHash>/sessions \
107 + --session-dir <state>/llmiterate/<scopeHash>/sessions \
96 108 --append-system-prompt <llmiterate worker rules> \
97 109 --model <optional> \
98 110 --thinking <optional>
103 115 ## Config
105 -Default `include` is `["**/*"]`. `.gitignore` and `.ignore` files are respected, plus default metadata/build excludes.
117 +Default `include` is `["**/*"]`. Scope is the cwd where `/llmiterate on` runs. Config loads global settings plus `<scope>/.pi/settings.json`; there is no upward project-root search. `.gitignore` and `.ignore` files are respected, plus default metadata/build/cache excludes.
107 119 ```json
112 124 "exclude": [
113 125 ".git/**",
114 126 ".pi/**",
127 + ".local/**",
115 128 "node_modules/**",
116 129 "target/**"
129 -`notify`: `off | errors | done | all`. Default: `errors`.
142 +`enabled: false` disables even manual `/llmiterate on`.
144 +`notify`: `off | errors | done | all`. Current public behavior notifies errors only unless `off`.
131 146 ## Commands
133 148 ```text
134 -/llmiterate toggle panel
135 -/llmiterate show show panel
136 -/llmiterate hide hide panel
137 -/llmiterate status show panel
138 -/llmiterate scan scan all matching files now
139 -/llmiterate reset forget run state
140 -/llmiterate reload reload config + watcher
141 -/llmiterate log open latest worker transcript as markdown in $VISUAL/$EDITOR
149 +/llmiterate toggle on/off for current cwd
150 +/llmiterate on start watcher for current cwd + initial scan
151 +/llmiterate off stop watcher + worker
152 +/llmiterate status show scope/counts/state path
153 +/llmiterate explain <path> explain include/exclude/marker decision
154 +/llmiterate log open latest worker transcript as markdown in $VISUAL/$EDITOR
155 +```
157 +Debug escape hatches (not autocompleted):
159 +```text
160 +/llmiterate scan scan current scope now
161 +/llmiterate forget forget run state
162 +/llmiterate reload reload config + watcher
144 165 ## UI channels
146 167 - source file: final edits only
147 -- footer status: idle/queued/running/done/failed
148 -- panel: queue/dashboard
149 -- notifications: errors by default
168 +- footer/status: watching/standby/queued/running/failed
169 +- notifications: on/off actions + errors
170 +- `/llmiterate status`: one-shot scope/counts/state
171 +- `/llmiterate explain <path>`: include/exclude/marker decision
150 172 - markdown log: full assistant/tool transcript
152 174 ## Demo

pi/agent/extensions/llmiterate/__tests__/core.test.ts

Modified
3 3 import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4 4 import { tmpdir } from "node:os";
5 5 import { join } from "node:path";
6 6 import { afterEach, describe, expect, test } from "bun:test";
7 7 import {
8 - BUILTIN_COMMENT_PREFIXES,
8 + COMMENT_PREFIXES_BY_EXTENSION,
9 9 buildAgentPrompt,
10 10 compilePathFilter,
11 11 defaultConfig,
70 70 expect(blocks[0]).toMatchObject({ startLine: 1, endLine: 2, prompt: "open ui\nand then fix perf" });
73 - test("supports builtin popular comment prefixes", () => {
73 + test("supports extension-scoped builtin comment prefixes", () => {
74 74 const samples = [
75 - "# llmiterate: shell",
76 - "-- llmiterate: sql",
77 - ";;; llmiterate: lisp",
78 - "% llmiterate: tex",
79 - "REM llmiterate: basic",
80 - "' llmiterate: vb",
81 - "<!-- llmiterate: markdown -->",
82 - "/* llmiterate: c */",
83 - "* llmiterate: javadoc",
84 - ];
75 + ["x.sh", "# llmiterate: shell"],
76 + ["x.sql", "-- llmiterate: sql"],
77 + ["x.lisp", ";;; llmiterate: lisp"],
78 + ["x.tex", "% llmiterate: tex"],
79 + ["x.md", "<!-- llmiterate: markdown -->"],
80 + ["x.c", "/* llmiterate: c */"],
81 + ["x.java", "// llmiterate: javadoc"],
82 + ["x.lua", "-- llmiterate: lua"],
83 + ] as const;
86 - expect(samples.map((line) => parseMarkerPrompts("x", line)[0]?.prompt)).toEqual([
85 + expect(samples.map(([file, line]) => parseMarkerPrompts(file, line)[0]?.prompt)).toEqual([
87 86 "shell",
88 87 "sql",
89 88 "lisp",
90 89 "tex",
91 - "basic",
92 - "vb",
93 90 "markdown",
95 92 "javadoc",
93 + "lua",
99 - test("appends configured comment prefixes to builtins", () => {
100 - const config = normalizeConfig({ commentPrefixes: ["COMMENT"] });
101 - expect(config.commentPrefixes).toContain("//");
102 - expect(config.commentPrefixes).toContain("COMMENT");
103 - expect(parseMarkerPrompts("a", "COMMENT llmiterate: custom", config.commentPrefixes)[0]?.prompt).toBe("custom");
97 + test("rejects prefixes outside their extension", () => {
98 + expect(parseMarkerPrompts("x.md", "# llmiterate: heading")).toHaveLength(0);
99 + expect(parseMarkerPrompts("x.md", "* llmiterate: bullet")).toHaveLength(0);
100 + expect(parseMarkerPrompts("x.ts", "<!-- llmiterate: html -->")).toHaveLength(0);
101 + expect(parseMarkerPrompts("x.txt", "// llmiterate: unknown extension")).toHaveLength(0);
102 + });
104 + test("appends configured comment prefixes by extension", () => {
105 + const config = normalizeConfig({ commentPrefixes: { foo: ["COMMENT"] } });
106 + expect(config.commentPrefixes.ts).toContain("//");
107 + expect(config.commentPrefixes.foo).toContain("COMMENT");
108 + expect(parseMarkerPrompts("a.foo", "COMMENT llmiterate: custom", config.commentPrefixes)[0]?.prompt).toBe("custom");
106 111 test("disable directive ignores whole file", () => {
107 - expect(isLlmiterateDisabled("// !llmiterate\n// llmiterate: ignored")).toBe(true);
112 + expect(isLlmiterateDisabled("// !llmiterate\n// llmiterate: ignored", "a.ts")).toBe(true);
108 113 expect(parseMarkerPrompts("a.ts", "// !llmiterate\n// llmiterate: ignored")).toEqual([]);
109 114 expect(parseMarkerPrompts("a.ts", "prose !llmiterate\n// llmiterate: active")).toHaveLength(1);
117 122 test("exact marker boundary", () => {
118 123 expect(parseMarkerPrompts("a.ts", "// llmiteratex: nope")).toHaveLength(0);
119 124 expect(parseMarkerPrompts("a.ts", "// llmiterate : nope")).toHaveLength(0);
120 - expect(BUILTIN_COMMENT_PREFIXES.length).toBeGreaterThan(10);
125 + expect(Object.keys(COMMENT_PREFIXES_BY_EXTENSION).length).toBeGreaterThan(10);
139 144 maxFileBytes: 42,
140 145 timeoutMs: 1000.4,
141 146 maxWatchDirs: 77.7,
142 - commentPrefixes: ["COMMENT"],
147 + commentPrefixes: { foo: ["COMMENT"] },
143 148 model: "zai/glm-5.1",
144 149 thinking: "high",
145 150 notify: "all",
157 162 thinking: "high",
158 163 notify: "all",
160 - expect(config.commentPrefixes).toContain("//");
161 - expect(config.commentPrefixes).toContain("COMMENT");
165 + expect(config.commentPrefixes.ts).toContain("//");
166 + expect(config.commentPrefixes.foo).toContain("COMMENT");
164 169 test("uses platform state dir for project stores", () => {
232 237 const defaults = compilePathFilter(defaultConfig());
233 238 expect(shouldIncludeCompiledPath(".jj/repo/store.ts", defaults)).toBe(false);
239 + expect(shouldWatchDirectory(".local", defaults)).toBe(false);
240 + expect(shouldIncludeCompiledPath(".local/share/Trash/files/a.ts", defaults)).toBe(false);
236 243 test("directory watch traversal is include-whitelisted with exclude veto", () => {

pi/agent/extensions/llmiterate/__tests__/extension.test.ts

Modified
8 8 afterEach(cleanupHarness);
10 10 describe("llmiterate extension queue/state", () => {
11 - test("uses project-relative paths when Pi cwd is subdir", async () => {
12 - const root = tempProject({ include: ["src/**/*.ts"] });
11 + test("does not autostart and uses cwd-relative paths", async () => {
12 + const root = tempProject({ include: ["**/*.ts"] });
13 13 mkdirSync(join(root, "src"));
14 14 writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
19 19 const pi = bootLlmiterate(join(root, "src"), worker);
21 - await pi.command("llmiterate", "scan");
21 + await new Promise((resolve) => setTimeout(resolve, 20));
22 + expect(worker.prompts).toHaveLength(0);
24 + await pi.command("llmiterate", "on");
22 25 await eventually(() => worker.prompts.length === 1);
24 - expect(worker.prompts[0]).toContain("@src/a.ts:1");
25 - expect(worker.prompts[0]).not.toContain("@a.ts:1");
27 + expect(worker.prompts[0]).toContain("@a.ts:1");
28 + expect(worker.prompts[0]).not.toContain("@src/a.ts:1");
29 + await pi.shutdown();
30 + });
32 + test("blank command toggles on then off", async () => {
33 + const root = tempProject({ include: ["src/**/*.ts"] });
34 + mkdirSync(join(root, "src"));
35 + writeFileSync(join(root, "src", "a.ts"), "// llmiterate: implement foo\n");
37 + let release!: () => void;
38 + const blocker = new Promise<void>((resolve) => { release = resolve; });
39 + const worker = new FakeWorker(async () => blocker);
40 + const pi = bootLlmiterate(root, worker);
42 + await pi.command("llmiterate", "");
43 + await eventually(() => worker.started === 1);
44 + await pi.command("llmiterate", "");
45 + expect(pi.ui.notifications.map((n) => n.message)).toContain("llmiterate off");
47 + release();
26 48 await pi.shutdown();
36 58 const worker = new FakeWorker(async () => blocker);
37 59 const pi = bootLlmiterate(root, worker);
39 - await pi.command("llmiterate", "scan");
61 + await pi.command("llmiterate", "on");
40 62 await pi.command("llmiterate", "scan");
41 63 await eventually(() => worker.started === 1);
42 64 expect(worker.started).toBe(1);
61 83 const pi = bootLlmiterate(root, worker);
63 - await pi.command("llmiterate", "scan");
85 + await pi.command("llmiterate", "on");
64 86 await eventually(() => worker.finished === 1);
65 87 expect(Object.values(loadState(projectStoreDir(root)).markers)[0]!.status).toBe("failed");
82 104 const worker = new FakeWorker(async () => blocker);
83 105 const pi = bootLlmiterate(root, worker);
85 - await pi.command("llmiterate", "scan");
107 + await pi.command("llmiterate", "on");
86 108 await eventually(() => Object.keys(loadState(projectStoreDir(root)).markers).length === 50);
87 109 expect(Object.keys(loadState(projectStoreDir(root)).markers)).toHaveLength(50);
88 110 release();
97 119 const worker = new FakeWorker(() => { throw new Error("bad auth"); });
98 120 const pi = bootLlmiterate(root, worker);
100 - await pi.command("llmiterate", "scan");
122 + await pi.command("llmiterate", "on");
101 123 await eventually(() => pi.ui.notifications.some((n) => n.message.includes("bad auth")));
102 124 expect(pi.ui.notifications.filter((n) => n.message.startsWith("llmiterate queued src/"))).toHaveLength(0);
103 125 expect(pi.ui.notifications.some((n) => n.type === "error")).toBe(true);

pi/agent/extensions/llmiterate/__tests__/lock.test.ts

Modified
2 2 import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 3 import { hostname, tmpdir } from "node:os";
4 4 import { join } from "node:path";
5 5 import { afterEach, describe, expect, test } from "bun:test";
6 -import { acquireLock, findProjectRoot, realPath, releaseLock, type LockHandle } from "../lock";
6 +import { acquireLock, realPath, releaseLock, type LockHandle } from "../lock";
8 8 const tempDirs: string[] = [];
16 16 return dir;
19 -describe("llmiterate lock/project root", () => {
20 - test("finds nearest project boundary", () => {
19 +describe("llmiterate lock", () => {
20 + test("realPath resolves existing paths", () => {
21 21 const root = tempDir();
22 - mkdirSync(join(root, ".git"));
23 - const nested = join(root, "a", "b");
24 - mkdirSync(nested, { recursive: true });
26 - expect(findProjectRoot(nested)).toBe(realPath(root));
28 - const sub = join(root, "a");
29 - writeFileSync(join(sub, "AGENTS.md"), "# subproject\n");
30 - expect(findProjectRoot(nested)).toBe(realPath(sub));
22 + expect(realPath(root)).toBe(root);
33 25 test("acquires, blocks duplicate, and releases lock", () => {

pi/agent/extensions/llmiterate/__tests__/ui.test.ts

Modified
1 1 import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 2 import { describe, expect, test } from "bun:test";
3 3 import { defaultConfig, normalizeConfig, parseMarkerPrompts } from "../core";
4 -import { LlmiterateWidget, renderLlmiterateUi } from "../ui";
4 +import { renderLlmiterateStatus } from "../ui";
5 5 import type { LlmiterateRun } from "../types";
7 7 interface UiCall {
20 20 const ctx = fakeContext({ setStatus: (key, value) => calls.push({ key, value }) });
21 21 const activeConfig = normalizeConfig({ include: ["src/**/*.ts"] });
23 - renderLlmiterateUi(ctx, false, [], { config: defaultConfig(), watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
24 - renderLlmiterateUi(ctx, false, [], { config: activeConfig, lockError: "held", watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
25 - renderLlmiterateUi(ctx, false, [], { config: activeConfig, watchErrors: 2, watchDirs: 0, queuedRuns: 0 });
26 - renderLlmiterateUi(ctx, false, [], { config: activeConfig, watchErrors: 0, watchDirs: 2, queuedRuns: 3 });
23 + renderLlmiterateStatus(ctx, { watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
24 + renderLlmiterateStatus(ctx, { config: defaultConfig(), watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
25 + renderLlmiterateStatus(ctx, { config: activeConfig, lockError: "held", watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
26 + renderLlmiterateStatus(ctx, { config: activeConfig, watchErrors: 2, watchDirs: 0, queuedRuns: 0 });
27 + renderLlmiterateStatus(ctx, { config: activeConfig, watchErrors: 0, watchDirs: 2, queuedRuns: 3 });
28 + renderLlmiterateStatus(ctx, { config: activeConfig, watchErrors: 0, watchDirs: 2, queuedRuns: 0, activeRun: sampleRun() });
28 30 expect(calls.map((c) => c.value)).toEqual([
29 - "llmiterate idle",
31 + undefined,
32 + "llmiterate watching .",
30 33 "llmiterate standby",
31 34 "llmiterate 2 watch error(s)",
32 35 "llmiterate queued 3",
36 + "llmiterate running src/main.ts:1",
36 - test("clears widget when hidden", () => {
37 - let widgetValue: unknown = "not cleared";
38 - const ctx = fakeContext({ setWidget: (_key, value) => { widgetValue = value; } });
40 - renderLlmiterateUi(ctx, false, [], { config: defaultConfig(), watchErrors: 0, watchDirs: 0, queuedRuns: 0 });
41 - expect(widgetValue).toBeUndefined();
42 - });
44 - test("widget empty snapshot", () => {
45 - expect(new LlmiterateWidget([], theme).render(60).join("\n")).toMatchSnapshot();
46 - });
48 - test("widget run snapshot", () => {
49 - expect(new LlmiterateWidget([sampleRun()], theme).render(80).join("\n")).toMatchSnapshot();
50 - });
53 41 function fakeContext(overrides: {
54 42 setStatus?: (key: string, value: string | undefined) => void;
55 - setWidget?: (key: string, value: unknown) => void;
56 43 }): ExtensionContext {
57 44 return {
58 45 hasUI: true,
59 46 ui: {
60 47 theme,
61 48 setStatus: overrides.setStatus ?? (() => {}),
62 - setWidget: overrides.setWidget ?? (() => {}),
64 50 } as unknown as ExtensionContext;

pi/agent/extensions/llmiterate/__tests__/watcher.test.ts

Modified
24 24 const root = tempDir();
25 25 mkdirSync(join(root, "src"));
26 26 mkdirSync(join(root, ".jj"));
27 + mkdirSync(join(root, ".local", "share", "Trash", "files"), { recursive: true });
27 28 writeFileSync(join(root, "src", "a.ts"), "// llmiterate: seen");
28 29 writeFileSync(join(root, ".jj", "ignored.ts"), "// llmiterate: ignored");
30 + writeFileSync(join(root, ".local", "share", "Trash", "files", "ignored.ts"), "// llmiterate: ignored");
30 32 const config = normalizeConfig({ debounceMs: 10 });
31 33 const seen: string[] = [];

pi/agent/extensions/llmiterate/config.ts

Modified
2 2 import * as fs from "node:fs";
3 3 import * as path from "node:path";
4 4 import { getAgentDir } from "@earendil-works/pi-coding-agent";
5 5 import {
6 - BUILTIN_COMMENT_PREFIXES,
6 + COMMENT_PREFIXES_BY_EXTENSION,
7 7 DEFAULT_DEBOUNCE_MS,
8 8 DEFAULT_EXCLUDE,
9 9 DEFAULT_INCLUDE,
23 23 maxFileBytes: number;
24 24 timeoutMs: number;
25 25 maxWatchDirs: number;
26 - commentPrefixes: string[];
26 + commentPrefixes: Record<string, string[]>;
27 27 model?: string;
28 28 thinking?: ThinkingLevel;
29 29 notify: NotifyPolicy;
38 38 maxFileBytes: DEFAULT_MAX_FILE_BYTES,
39 39 timeoutMs: DEFAULT_TIMEOUT_MS,
40 40 maxWatchDirs: DEFAULT_MAX_WATCH_DIRS,
41 - commentPrefixes: [...BUILTIN_COMMENT_PREFIXES],
41 + commentPrefixes: clonePrefixMap(COMMENT_PREFIXES_BY_EXTENSION),
42 42 notify: "errors",
95 95 return [...new Set([...DEFAULT_EXCLUDE, ...stringArray(value, [])])];
98 -function mergeCommentPrefixes(value: unknown): string[] {
99 - return normalizeCommentPrefixes([...BUILTIN_COMMENT_PREFIXES, ...stringArray(value, [])]);
98 +function mergeCommentPrefixes(value: unknown): Record<string, string[]> {
99 + const merged = clonePrefixMap(COMMENT_PREFIXES_BY_EXTENSION);
100 + if (!isObject(value)) return merged;
102 + for (const [rawKey, rawPrefixes] of Object.entries(value)) {
103 + const key = normalizeExtensionKey(rawKey);
104 + if (!key) continue;
105 + merged[key] = normalizeCommentPrefixes([...(merged[key] ?? []), ...stringArray(rawPrefixes, [])]);
107 + return merged;
110 +function clonePrefixMap(value: Record<string, string[]>): Record<string, string[]> {
111 + return Object.fromEntries(Object.entries(value).map(([key, prefixes]) => [key, normalizeCommentPrefixes(prefixes)]));
114 +function normalizeExtensionKey(key: string): string {
115 + return key.trim().toLowerCase().replace(/^\./, "");
102 118 function normalizeCommentPrefixes(prefixes: string[]): string[] {

pi/agent/extensions/llmiterate/constants.ts

Modified
16 16 "**/coverage/**",
17 17 "**/target/**",
18 18 "**/.cache/**",
19 + "**/.local/**",
20 + "**/.bun/**",
21 + "**/.npm/**",
22 + "**/.cargo/**",
23 + "**/.rustup/**",
24 + "**/.gradle/**",
25 + "**/.m2/**",
26 + "**/.steam/**",
19 27 "**/.next/**",
20 28 "**/.gitignore",
21 29 "**/.ignore",
25 33 export const MARKER = "llmiterate:";
26 34 export const DISABLE_MARKER = "!llmiterate";
27 -export const BUILTIN_COMMENT_PREFIXES = [
28 - "<!--",
29 - "/**",
30 - "/*",
31 - "///",
32 - "//!",
33 - "//",
34 - "###",
35 - "##",
36 - "#",
37 - "---",
38 - "--",
39 - ";;;",
40 - ";;",
41 - ";",
42 - "%%",
43 - "%",
44 - "::",
45 - "*>",
46 - "*",
47 - "REM",
48 - "rem",
49 - "'",
50 - "dnl",
51 - "DNL",
52 -];
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 +};
53 91 export const STORE_NAMESPACE = "llmiterate";
54 92 export const STATE_FILE = "state.json";
55 93 export const APP_STATE_DIR = "pi";

pi/agent/extensions/llmiterate/index.ts

Modified
2 2 import * as fs from "node:fs";
3 3 import * as path from "node:path";
4 4 import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
5 5 import { loadConfig, type LlmiterateConfig, type NotifyPolicy } from "./config";
6 -import { compilePathFilter, projectStoreDir, shouldIncludeCompiledPath, type CompiledPathFilter } from "./path-filter";
7 -import { parseMarkerPrompts, type MarkerPrompt } from "./parser";
6 +import { compilePathFilter, globToRegExp, projectStoreDir, shouldIncludeCompiledPath, type CompiledPathFilter } from "./path-filter";
7 +import { isLlmiterateDisabled, parseMarkerPrompts, type MarkerPrompt } from "./parser";
8 8 import { buildAgentPrompt } from "./prompt";
9 9 import { emptyState, loadState, saveState, type LlmiterateState, type MarkerRunState } from "./state";
10 10 import { previewText, toSlash } from "./util";
11 -import { acquireLock, findProjectRoot, realPath, releaseLock, type LockHandle } from "./lock";
11 +import { acquireLock, realPath, releaseLock, type LockHandle } from "./lock";
12 12 import { LLMITERATE_WORKER_ENV, PiRpcWorker } from "./rpc";
13 13 import { openInEditor, renderLatestSessionLog } from "./log";
14 -import { renderLlmiterateUi } from "./ui";
14 +import { renderLlmiterateStatus } from "./ui";
15 15 import { ProjectWatcher } from "./watcher";
16 16 import type { LlmiterateRun, RpcEvent, RpcMessage, RpcTextPart, RpcToolResult } from "./types";
53 53 const STATE_PROMPT_PREVIEW_CHARS = 120;
54 54 const ERROR_PREVIEW_CHARS = 160;
55 -const COMMAND_USAGE = "Usage: /llmiterate [show|hide|status|scan|reset|reload|log]";
55 +const COMMAND_USAGE = "Usage: /llmiterate [on|off|status|log|explain <path>]";
56 +const COMPLETED_COMMANDS = ["on", "off", "status", "log", "explain"] as const;
57 58 export function createLlmiterateExtension(deps: LlmiterateExtensionDeps = {}) {
58 59 return function llmiterate(pi: ExtensionAPI) {
67 68 class LlmiterateController {
68 69 private runtime?: WatchRuntime;
69 70 private sessionCtx?: ExtensionContext;
70 - private panelVisible = false;
71 71 private nextRunId = 1;
72 72 private activeRunId?: number;
73 73 private activeJob = false;
95 95 this.pi.on("session_start", async (_event, ctx) => this.onSessionStart(ctx));
96 96 this.pi.on("session_shutdown", async () => this.onSessionShutdown());
97 97 this.pi.registerCommand("llmiterate", {
98 - description: "Toggle/show llmiterate watcher UI. Args: show | hide | status | scan | reset | reload | log",
98 + description: "Toggle llmiterate for current cwd. Args: on | off | status | log | explain <path>",
99 + getArgumentCompletions: (prefix: string) => {
100 + if (prefix.trimStart().includes(" ")) return null;
101 + const items = COMPLETED_COMMANDS
102 + .filter((command) => command.startsWith(prefix.trimStart()))
103 + .map((command) => ({ value: command, label: command }));
104 + return items.length ? items : null;
105 + },
99 106 handler: async (args, ctx) => {
100 - this.runCommand(args.trim().toLowerCase(), ctx);
107 + this.runCommand(args, ctx);
101 108 this.updateUi(ctx);
106 113 private onSessionStart(ctx: ExtensionContext): void {
107 114 this.sessionCtx = ctx;
108 - this.start(ctx.cwd);
109 115 this.updateUi(ctx);
112 118 private onSessionShutdown(): void {
113 119 this.stop();
120 + this.updateUi(this.sessionCtx);
114 121 this.sessionCtx = undefined;
115 122 this.activeRunId = undefined;
118 - private runCommand(command: string, ctx: ExtensionCommandContext): void {
125 + private runCommand(args: string, ctx: ExtensionCommandContext): void {
126 + const { command, rest } = parseCommandArgs(args);
119 127 switch (command) {
120 - case "": this.panelVisible = !this.panelVisible; return;
121 - case "show":
122 - case "status": this.panelVisible = true; return;
123 - case "hide": this.panelVisible = false; return;
124 - case "scan": this.scanCommand(ctx); return;
125 - case "reset": this.resetCommand(ctx); return;
126 - case "reload": this.reloadCommand(ctx); return;
128 + case "": this.toggleCommand(ctx); return;
129 + case "on": this.onCommand(ctx); return;
130 + case "off": this.offCommand(ctx); return;
131 + case "status": this.statusCommand(ctx); return;
127 132 case "log": this.logCommand(ctx); return;
133 + case "explain": this.explainCommand(rest, ctx); return;
134 + case "scan": this.scanCommand(ctx); return;
135 + case "forget": this.forgetCommand(ctx); return;
136 + case "reload": this.reloadCommand(ctx); return;
128 137 default: ctx.ui.notify(COMMAND_USAGE, "warning");
132 - private scanCommand(ctx: ExtensionCommandContext): void {
133 - if (this.notifyIfStandby(ctx)) {
134 - this.panelVisible = true;
141 + private toggleCommand(ctx: ExtensionCommandContext): void {
142 + if (this.runtime) this.offCommand(ctx);
143 + else this.onCommand(ctx);
146 + private onCommand(ctx: ExtensionCommandContext): void {
147 + if (this.runtime && !this.runtime.lockError) {
148 + ctx.ui.notify(`llmiterate already on: ${this.runtime.root}`, "info");
135 149 return;
152 + this.start(ctx.cwd);
153 + if (!this.runtime) return;
154 + if (!this.runtime.config.enabled) {
155 + ctx.ui.notify("llmiterate disabled by config", "warning");
156 + this.stop();
157 + return;
159 + if (this.notifyIfStandby(ctx)) return;
161 + const count = this.scanAll();
162 + ctx.ui.notify(`llmiterate on: ${this.runtime.root}${count ? `; queued ${count}` : ""}`, "info");
165 + private offCommand(ctx: ExtensionCommandContext): void {
166 + if (!this.runtime) {
167 + ctx.ui.notify("llmiterate already off", "info");
168 + return;
171 + this.stop();
172 + ctx.ui.notify("llmiterate off", "info");
175 + private scanCommand(ctx: ExtensionCommandContext): void {
176 + if (!this.runtime) {
177 + ctx.ui.notify("llmiterate off; run /llmiterate on", "warning");
178 + return;
180 + if (this.notifyIfStandby(ctx)) return;
138 182 const count = this.scanAll();
139 - this.panelVisible = true;
140 183 ctx.ui.notify(`llmiterate scan queued ${count} new prompt(s)`, "info");
143 - private resetCommand(ctx: ExtensionCommandContext): void {
186 + private forgetCommand(ctx: ExtensionCommandContext): void {
144 187 if (this.notifyIfStandby(ctx)) return;
146 189 if (this.runtime) {
150 193 this.stopWorker();
151 194 this.runs.length = 0;
152 195 this.activeRunId = undefined;
153 - ctx.ui.notify("llmiterate state reset", "info");
196 + ctx.ui.notify("llmiterate forgot run state", "info");
156 199 private reloadCommand(ctx: ExtensionCommandContext): void {
157 - this.start(ctx.cwd);
200 + if (!this.runtime) {
201 + ctx.ui.notify("llmiterate off; run /llmiterate on", "warning");
202 + return;
204 + const cwd = this.runtime.cwd;
205 + this.start(cwd);
158 206 ctx.ui.notify("llmiterate config/watcher reloaded", "info");
209 + private statusCommand(ctx: ExtensionCommandContext): void {
210 + ctx.ui.notify(this.statusText(ctx.cwd), "info");
161 213 private logCommand(ctx: ExtensionCommandContext): void {
162 - if (!this.runtime) return;
214 + if (!this.runtime) {
215 + ctx.ui.notify("llmiterate off; no active worker log", "warning");
216 + return;
164 219 const target = renderLatestSessionLog(sessionDir(this.runtime), path.join(this.runtime.storeDir, "logs"));
165 220 if (!target) {
171 226 if (error) ctx.ui.notify(`llmiterate log written: ${target.markdownFile} (${error})`, "warning");
229 + private explainCommand(targetPath: string, ctx: ExtensionCommandContext): void {
230 + const target = targetPath.trim();
231 + if (!target) {
232 + ctx.ui.notify("Usage: /llmiterate explain <path>", "warning");
233 + return;
235 + ctx.ui.notify(explainPath(ctx.cwd, target), "info");
238 + private statusText(cwd: string): string {
239 + const runtime = this.runtime;
240 + if (!runtime) return `llmiterate off\nscope: ${realPath(cwd)}`;
242 + const active = this.activeRun();
243 + return [
244 + runtime.lockError ? "llmiterate standby" : "llmiterate on",
245 + `scope: ${runtime.root}`,
246 + ...(runtime.lockError ? [`reason: ${runtime.lockError}`, "action: use existing same-cwd watcher, stop it, or choose another cwd"] : []),
247 + `filters: include ${runtime.config.include.length}, exclude ${runtime.config.exclude.length}, .gitignore/.ignore on`,
248 + `watch dirs: ${runtime.watcher?.watcherCount ?? 0}`,
249 + `watch errors: ${runtime.watcher?.errorCount ?? 0}`,
250 + `queued: ${this.queuedRunCount()}`,
251 + `running: ${active ? `${active.projectFile}:${active.block.startLine}` : "none"}`,
252 + `failed: ${this.runs.filter((run) => run.status === "error").length}`,
253 + `state: ${runtime.storeDir}`,
254 + ].join("\n");
174 257 private notifyIfStandby(ctx: ExtensionCommandContext): boolean {
175 258 if (!this.runtime?.lockError) return false;
176 - ctx.ui.notify(`llmiterate inactive: ${this.runtime.lockError}`, "warning");
259 + ctx.ui.notify(`llmiterate standby: ${this.runtime.root} already watched (${this.runtime.lockError})`, "warning");
177 260 return true;
180 263 private start(cwd: string): void {
181 264 this.stop();
183 - const root = findProjectRoot(cwd);
266 + const root = realPath(cwd);
184 267 const config = loadConfig(root);
185 268 const storeDir = projectStoreDir(root);
186 269 this.runtime = {
188 - cwd: realPath(cwd),
271 + cwd: root,
189 272 config,
190 273 pathFilter: compilePathFilter(config),
191 274 storeDir,
285 368 private enqueueRun(block: MarkerPrompt, projectFile: string, absoluteFile: string): void {
286 369 this.runs.unshift(this.createRun(block, projectFile, absoluteFile));
287 - this.maybeNotify("queued", `llmiterate queued ${projectFile}:${block.startLine}`);
288 370 this.startNextRun();
289 371 this.updateUi(this.sessionCtx);
426 508 if (run.status === "error") return;
427 509 run.status = "done";
428 510 this.setMarkerStatus(run, "done");
429 - this.maybeNotify("done", `llmiterate done ${run.projectFile}:${run.block.startLine}`);
430 511 this.touchRun(run);
488 569 private updateUi(ctx: ExtensionContext | undefined): void {
489 - renderLlmiterateUi(ctx, this.panelVisible, this.runs, {
570 + renderLlmiterateStatus(ctx, {
490 571 config: this.runtime?.config,
491 572 lockError: this.runtime?.lockError,
492 573 watchErrors: this.runtime?.watcher?.errorCount ?? 0,
505 586 return path.join(runtime.storeDir, "sessions");
589 +function parseCommandArgs(args: string): { command: string; rest: string } {
590 + const trimmed = args.trim();
591 + if (!trimmed) return { command: "", rest: "" };
592 + const match = trimmed.match(/^(\S+)(?:\s+([\s\S]*))?$/);
593 + return { command: (match?.[1] ?? "").toLowerCase(), rest: match?.[2] ?? "" };
596 +function explainPath(cwd: string, target: string): string {
597 + const scope = realPath(cwd);
598 + const abs = path.resolve(scope, target);
599 + const rel = toSlash(path.relative(scope, abs));
600 + const config = loadConfig(scope);
601 + const stat = statFile(abs);
602 + const directory = stat?.isDirectory() === true;
603 + const include = firstMatchingGlob(config.include, rel, directory);
604 + const exclude = firstMatchingGlob(config.exclude, rel, directory);
605 + const unsafe = !rel || rel.startsWith("..") || path.isAbsolute(rel);
606 + const tooLarge = stat?.isFile() && stat.size > config.maxFileBytes;
607 + const text = stat?.isFile() && !tooLarge ? readUtf8(abs) : undefined;
608 + const disabled = text !== undefined && isLlmiterateDisabled(text, rel, config.commentPrefixes);
609 + const markers = text !== undefined && !disabled ? parseMarkerPrompts(rel, text, config.commentPrefixes).length : 0;
610 + const status = explainStatus({ unsafe, stat, include, exclude, tooLarge, disabled, markers });
612 + return [
613 + rel || ".",
614 + `scope: ${scope}`,
615 + `included: ${include ?? "no"}`,
616 + `excluded: ${exclude ?? "no"}`,
617 + `ignored: .gitignore/.ignore respected during scan/watch`,
618 + `size: ${stat?.isFile() ? `${formatBytes(stat.size)} / ${formatBytes(config.maxFileBytes)}` : "not a file"}`,
619 + `markers: ${disabled ? "disabled by !llmiterate" : markers}`,
620 + `status: ${status}`,
621 + ].join("\n");
624 +function firstMatchingGlob(globs: readonly string[], rel: string, directory: boolean): string | undefined {
625 + for (const glob of globs) {
626 + const pattern = globToRegExp(glob);
627 + if (pattern.test(rel) || (directory && pattern.test(`${rel}/`))) return glob;
629 + return undefined;
632 +function explainStatus(input: {
633 + unsafe: boolean;
634 + stat: fs.Stats | undefined;
635 + include: string | undefined;
636 + exclude: string | undefined;
637 + tooLarge: boolean | undefined;
638 + disabled: boolean;
639 + markers: number;
640 +}): string {
641 + if (input.unsafe) return "outside scope";
642 + if (!input.stat) return "missing";
643 + if (!input.stat.isFile()) return "not a file";
644 + if (!input.include) return "not included";
645 + if (input.exclude) return "excluded";
646 + if (input.tooLarge) return "too large";
647 + if (input.disabled) return "disabled";
648 + if (input.markers === 0) return "no llmiterate marker";
649 + return "will run";
652 +function formatBytes(bytes: number): string {
653 + if (bytes < 1024) return `${bytes} B`;
654 + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
655 + return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
508 658 function statFile(absPath: string): fs.Stats | undefined {
509 659 try { return fs.statSync(absPath); } catch { return undefined; }
516 666 function shouldNotify(policy: NotifyPolicy, kind: "queued" | "done" | "error"): boolean {
517 - if (policy === "off") return false;
518 - if (policy === "all") return true;
519 - if (policy === "done") return kind === "done" || kind === "error";
520 - return kind === "error";
667 + return policy !== "off" && kind === "error";
523 670 function sessionName(run: LlmiterateRun): string {

pi/agent/extensions/llmiterate/lock.ts

Modified
17 17 token: string;
20 -export function findProjectRoot(cwd: string): string {
21 - const start = realPath(cwd);
23 - for (let dir: string | undefined = start; dir; dir = parentDir(dir)) {
24 - if (isProjectBoundary(dir)) return realPath(dir);
25 - }
27 - return start;
30 20 export function realPath(file: string): string {
31 21 try { return fs.realpathSync(file); } catch { return path.resolve(file); }
122 -function isProjectBoundary(dir: string): boolean {
123 - return isDirectory(path.join(dir, ".pi"))
124 - || fs.existsSync(path.join(dir, "AGENTS.md"))
125 - || fs.existsSync(path.join(dir, ".git"));
128 -function parentDir(dir: string): string | undefined {
129 - const parent = path.dirname(dir);
130 - return parent === dir ? undefined : parent;
133 -function isDirectory(file: string): boolean {
134 - try { return fs.statSync(file).isDirectory(); } catch { return false; }
137 112 function nodeErrorCode(error: unknown): string | undefined {
138 113 return error instanceof Error && "code" in error ? String((error as NodeJS.ErrnoException).code) : undefined;

pi/agent/extensions/llmiterate/parser.ts

Modified
1 -import { BUILTIN_COMMENT_PREFIXES, DISABLE_MARKER, MARKER } from "./constants";
1 +import { COMMENT_PREFIXES_BY_EXTENSION, DISABLE_MARKER, MARKER } from "./constants";
3 3 export interface MarkerPrompt {
4 4 marker: typeof MARKER;
13 13 const commentPrefixGroupCache = new Map<string, Map<string, string[]>>();
15 -export function parseMarkerPrompts(file: string, text: string, commentPrefixes = BUILTIN_COMMENT_PREFIXES): MarkerPrompt[] {
15 +export function parseMarkerPrompts(
16 + file: string,
17 + text: string,
18 + commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
19 +): MarkerPrompt[] {
16 20 if (!text.includes("llmiterate")) return [];
17 - if (isLlmiterateDisabled(text, commentPrefixes)) return [];
21 + const prefixes = prefixesForFile(file, commentPrefixes);
22 + if (prefixes.length === 0) return [];
23 + if (isLlmiterateDisabled(text, file, commentPrefixes)) return [];
19 - const prefixes = normalizeCommentPrefixes(commentPrefixes);
20 25 const lines = normalizeLines(text);
21 26 const prompts: MarkerPrompt[] = [];
43 48 return prompts;
46 -export function isLlmiterateDisabled(text: string, commentPrefixes = BUILTIN_COMMENT_PREFIXES): boolean {
51 +export function isLlmiterateDisabled(
52 + text: string,
53 + file = "",
54 + commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
55 +): boolean {
47 56 if (!text.includes(DISABLE_MARKER)) return false;
48 - const prefixes = normalizeCommentPrefixes(commentPrefixes);
57 + const prefixes = prefixesForFile(file, commentPrefixes);
58 + if (prefixes.length === 0) return false;
49 59 return normalizeLines(text).some((line) => {
50 60 const stripped = stripCommentPrefix(line, prefixes);
51 61 return stripped !== undefined && /^!llmiterate(?:\s|$)/.test(stripped);
65 +export function prefixesForFile(file: string, commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION): string[] {
66 + return normalizeCommentPrefixes(commentPrefixes[extensionKey(file)] ?? []);
69 +function extensionKey(file: string): string {
70 + const base = (file.split(/[\\/]/).pop() ?? "").toLowerCase();
71 + if (!base) return "";
72 + if (base === "dockerfile" || base.endsWith(".dockerfile")) return "dockerfile";
73 + const dot = base.lastIndexOf(".");
74 + return dot === -1 ? base : base.slice(dot + 1);
55 77 function parsePromptLine(line: string, prefixes: string[]): string | undefined {
56 78 const stripped = stripCommentPrefix(line, prefixes);
57 79 if (stripped === undefined || !stripped.startsWith(MARKER)) return undefined;

pi/agent/extensions/llmiterate/ui.ts

Modified
1 1 import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 -import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3 -import type { Component } from "@earendil-works/pi-tui";
4 -import { previewText } from "./util";
5 -import type { LlmiterateRun, RunStatus, UiState } from "./types";
2 +import type { UiState } from "./types";
7 -const STATUS_KEY = "llmiterate";
8 -const WIDGET_KEY = "llmiterate";
9 -const WIDGET_RUN_LIMIT = 6;
10 -const PROMPT_PREVIEW_CHARS = 80;
11 -const DETAIL_PREVIEW_CHARS = 110;
4 +export const STATUS_KEY = "llmiterate";
13 -export function renderLlmiterateUi(
14 - ctx: ExtensionContext | undefined,
15 - panelVisible: boolean,
16 - runs: readonly LlmiterateRun[],
17 - state: UiState,
18 -): void {
6 +export function renderLlmiterateStatus(ctx: ExtensionContext | undefined, state: UiState): void {
19 7 if (!ctx?.hasUI) return;
21 8 ctx.ui.setStatus(STATUS_KEY, statusLine(ctx, state));
22 - if (!panelVisible) {
23 - ctx.ui.setWidget(WIDGET_KEY, undefined);
24 - return;
25 - }
27 - ctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => new LlmiterateWidget(runs, theme), {
28 - placement: "belowEditor",
29 - });
32 -function statusLine(ctx: ExtensionContext, state: UiState): string {
11 +function statusLine(ctx: ExtensionContext, state: UiState): string | undefined {
12 + if (!state.config) return undefined;
14 + if (!state.config.enabled) return undefined;
33 16 const theme = ctx.ui.theme;
34 - if (!state.config?.enabled) return theme.fg("dim", "llmiterate off");
35 - if (state.config.include.length === 0) return theme.fg("dim", "llmiterate watching nothing");
36 17 if (state.lockError) return theme.fg("dim", "llmiterate standby");
37 18 if (state.watchErrors > 0) return theme.fg("warning", `llmiterate ${state.watchErrors} watch error(s)`);
38 19 if (state.activeRun) return theme.fg("accent", `llmiterate ${state.activeRun.status} ${state.activeRun.block.file}:${state.activeRun.block.startLine}`);
39 20 if (state.queuedRuns > 0) return theme.fg("warning", `llmiterate queued ${state.queuedRuns}`);
40 - return theme.fg("dim", "llmiterate idle");
43 -export class LlmiterateWidget implements Component {
44 - constructor(
45 - private readonly runs: readonly LlmiterateRun[],
46 - private readonly theme: ExtensionContext["ui"]["theme"],
47 - ) {}
49 - render(width: number): string[] {
50 - if (width <= 0) return [];
52 - const inner = Math.max(1, width - 2);
53 - const lines = [
54 - this.border("╭", "╮", inner, ` ${this.theme.bold("llmiterate")} `),
55 - ...this.runLines(inner),
56 - this.border("╰", "╯", inner),
57 - ];
59 - return lines.map((line) => truncateToWidth(line, width, ""));
60 - }
62 - invalidate(): void {}
64 - private runLines(inner: number): string[] {
65 - if (this.runs.length === 0) return [this.line(this.theme.fg("dim", "no prompts queued yet; /llmiterate log opens latest transcript"), inner)];
67 - const lines: string[] = [];
68 - for (const run of this.runs.slice(0, WIDGET_RUN_LIMIT)) {
69 - lines.push(this.line(this.runHeader(run), inner));
70 - if (run.toolText) lines.push(this.line(this.theme.fg("dim", ` ${run.toolText}`), inner));
71 - if (run.error) lines.push(this.line(this.theme.fg("error", ` ${previewText(run.error, DETAIL_PREVIEW_CHARS)}`), inner));
72 - else if (run.assistantText) lines.push(this.line(this.theme.fg("dim", ` ${previewText(run.assistantText, DETAIL_PREVIEW_CHARS)}`), inner));
73 - }
74 - return lines;
75 - }
77 - private runHeader(run: LlmiterateRun): string {
78 - return `${statusIcon(run.status)} ${run.block.file}:${run.block.startLine} ${this.theme.fg("muted", run.block.marker)} ${previewText(run.block.prompt, PROMPT_PREVIEW_CHARS)}`;
79 - }
81 - private border(left: string, right: string, inner: number, label = ""): string {
82 - const labelWidth = visibleWidth(label);
83 - return this.theme.fg("border", left)
84 - + this.theme.fg("accent", label)
85 - + this.theme.fg("border", "─".repeat(Math.max(0, inner - labelWidth)) + right);
86 - }
88 - private line(text: string, inner: number): string {
89 - const body = fit(text, inner);
90 - return this.theme.fg("border", "│") + body + this.theme.fg("border", "│");
91 - }
94 -function fit(text: string, width: number): string {
95 - const t = truncateToWidth(text, width, "…");
96 - return t + " ".repeat(Math.max(0, width - visibleWidth(t)));
99 -function statusIcon(status: RunStatus): string {
100 - if (status === "queued") return "◌";
101 - if (status === "running") return "●";
102 - if (status === "done") return "✓";
103 - return "✗";
21 + return theme.fg("dim", "llmiterate watching .");

pi/agent/extensions/llmiterate/watcher.ts

Modified
193 193 private isFreshEnough(absPath: string, options: RefreshOptions): boolean {
194 194 if (options.fileMtimeSinceMs === undefined) return true;
195 - try { return fs.statSync(absPath).mtimeMs >= options.fileMtimeSinceMs; } catch { return false; }
195 + try { return fs.statSync(absPath).mtimeMs > options.fileMtimeSinceMs; } catch { return false; }
198 198 private scheduleFile(absPath: string): void {