import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, test } from "bun:test"; import { buildAgentPrompt, compilePathFilter, defaultConfig, emptyState, globToRegExp, isExcludedPath, hashProjectRoot, loadState, normalizeConfig, parseMarkerPrompts, platformStateDir, projectStoreDir, previewText, saveState, STATE_FILE, shouldIncludeCompiledPath, shouldIncludePath, shouldWatchDirectory, toSlash, } from "../core"; const tempDirs: string[] = []; afterEach(() => { while (tempDirs.length) rmSync(tempDirs.pop()!, { recursive: true, force: true }); }); function tempDir(): string { const dir = mkdtempSync(join(tmpdir(), "llmiterate-core-")); tempDirs.push(dir); return dir; } describe("llmiterate parser", () => { test("parses marker as first word on line", () => { const blocks = parseMarkerPrompts("Main.java", [ "void main(final String[] a) {", " LLM some prompt text", " if (a.length == 0)", " LLM deal with this", "}", ].join("\n")); expect(blocks).toHaveLength(2); expect(blocks[0]).toMatchObject({ marker: "LLM", startLine: 2, endLine: 2, prompt: "some prompt text" }); expect(blocks[1]).toMatchObject({ marker: "LLM", startLine: 4, endLine: 4, prompt: "deal with this" }); }); test("groups consecutive marker lines with same marker", () => { const blocks = parseMarkerPrompts("Main.java", [ " LLM open ui", " LLM and then fix perf", " run();", ].join("\n")); expect(blocks).toHaveLength(1); expect(blocks[0]).toMatchObject({ startLine: 1, endLine: 2, prompt: "open ui\nand then fix perf" }); }); test("does not group different markers", () => { const blocks = parseMarkerPrompts("a.ts", "LLM first\nPROMPT second\nLLM third"); expect(blocks.map((b) => b.prompt)).toEqual(["first", "second", "third"]); expect(blocks.map((b) => b.startLine)).toEqual([1, 2, 3]); }); test("does not strip comments unless configured marker includes comment", () => { expect(parseMarkerPrompts("src/lib.rs", " // LLM implement knapsack algo")).toHaveLength(0); const blocks = parseMarkerPrompts("src/lib.rs", " //LLM implement knapsack algo", ["//LLM"]); expect(blocks).toHaveLength(1); expect(blocks[0]).toMatchObject({ marker: "//LLM", prompt: "implement knapsack algo" }); }); test("supports markers containing spaces", () => { const blocks = parseMarkerPrompts("a.rs", " /// LLM add tests", ["/// LLM"]); expect(blocks).toHaveLength(1); expect(blocks[0]).toMatchObject({ marker: "/// LLM", prompt: "add tests" }); }); test("sorts overlapping markers longest-first", () => { const [block] = parseMarkerPrompts("a.rs", "/// LLM add tests", ["LLM", "/// LLM"]); expect(block).toMatchObject({ marker: "/// LLM", prompt: "add tests" }); }); test("supports PROMPT marker too", () => { const blocks = parseMarkerPrompts("a.ts", "PROMPT add tests"); expect(blocks).toHaveLength(1); expect(blocks[0]).toMatchObject({ marker: "PROMPT", prompt: "add tests" }); }); test("marker must be first word", () => { expect(parseMarkerPrompts("a.md", "some LLM receives message history")).toHaveLength(0); expect(parseMarkerPrompts("a.ts", "xLLM implement foo")).toHaveLength(0); expect(parseMarkerPrompts("a.ts", "LLMish implement foo")).toHaveLength(0); }); test("ignores empty marker lines", () => { expect(parseMarkerPrompts("a.ts", "LLM\nPROMPT ")).toHaveLength(0); }); test("ignores enum/string assignment false positives", () => { expect(parseMarkerPrompts("node.d.ts", 'PROMPT = "PROMPT",')).toHaveLength(0); }); test("does not parse old colon or brace syntax", () => { expect(parseMarkerPrompts("a.ts", "// PROMPT: do thing")).toHaveLength(0); expect(parseMarkerPrompts("a.ts", "// PROMPT{{\n// do thing\n// }}")).toHaveLength(0); }); test("ignores Markdown fenced code blocks", () => { const blocks = parseMarkerPrompts("notes.md", [ "# docs", "```ts", "LLM fake inside fence", "```", "LLM real outside fence", "~~~", "PROMPT fake tilde fence", "~~~", ].join("\n")); expect(blocks).toHaveLength(1); expect(blocks[0]).toMatchObject({ startLine: 5, prompt: "real outside fence" }); }); test("normalizes CRLF and CR line endings", () => { expect(parseMarkerPrompts("a.ts", "LLM one\r\nLLM two")[0]!.prompt).toBe("one\ntwo"); expect(parseMarkerPrompts("a.ts", "LLM one\rLLM two")[0]!.prompt).toBe("one\ntwo"); }); }); describe("llmiterate config/state/path helpers", () => { test("defaults to watching nothing", () => { const config = defaultConfig(); const filter = compilePathFilter(config); expect(config.include).toEqual([]); expect(shouldWatchDirectory("", filter)).toBe(false); expect(shouldIncludeCompiledPath("src/a.ts", filter)).toBe(false); }); test("normalizes valid partial config and rejects invalid values", () => { const config = normalizeConfig({ enabled: false, include: ["src/**/*.ts"], exclude: ["tmp/**"], debounceMs: 12.8, maxFileBytes: 42, markers: ["//LLM", "bad\nmarker", " PROMPT "], }); expect(config).toMatchObject({ enabled: false, include: ["src/**/*.ts"], exclude: ["tmp/**"], debounceMs: 12, maxFileBytes: 42, markers: ["//LLM", "PROMPT"], }); const fallback = defaultConfig(); expect(normalizeConfig({ include: [""] })).toMatchObject({ include: fallback.include, }); }); test("uses platform state dir for project stores", () => { const oldXdg = process.env.XDG_STATE_HOME; const stateRoot = tempDir(); process.env.XDG_STATE_HOME = stateRoot; try { const root = "/tmp/project"; expect(platformStateDir()).toBe(join(stateRoot, "pi")); expect(projectStoreDir(root)).toBe(join(stateRoot, "pi", "llmiterate", hashProjectRoot(root))); } finally { if (oldXdg === undefined) delete process.env.XDG_STATE_HOME; else process.env.XDG_STATE_HOME = oldXdg; } }); test("platformStateDir uses native conventions", () => { expect(platformStateDir("linux", {}, "/home/me")).toBe("/home/me/.local/state/pi"); expect(platformStateDir("linux", { XDG_STATE_HOME: "/state" }, "/home/me")).toBe("/state/pi"); expect(platformStateDir("darwin", {}, "/Users/me")).toBe("/Users/me/Library/Application Support/pi"); expect(platformStateDir("win32", { LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local" }, "C:\\Users\\me")) .toBe("C:\\Users\\me\\AppData\\Local\\pi"); expect(platformStateDir("win32", {}, "C:\\Users\\me")) .toBe("C:\\Users\\me\\AppData\\Local\\pi"); }); test("saves and loads state, invalid state falls back empty", () => { const storeDir = tempDir(); const state = emptyState(); state.processed["a.ts:1:hash"] = { file: "a.ts", startLine: 1, endLine: 1, promptHash: "hash", promptPreview: "preview", queuedAt: 123, }; saveState(storeDir, state); expect(loadState(storeDir)).toEqual(state); expect(readFileSync(join(storeDir, STATE_FILE), "utf-8")).toEndWith("\n"); writeFileSync(join(storeDir, STATE_FILE), JSON.stringify({ version: 1, processed: { good: state.processed["a.ts:1:hash"], bad: { file: "missing required fields" }, }, })); expect(loadState(storeDir).processed).toEqual({ good: state.processed["a.ts:1:hash"] }); rmSync(join(storeDir, STATE_FILE)); expect(loadState(storeDir)).toEqual(emptyState()); }); test("glob supports globstar, brace alternatives, and excludes", () => { const re = globToRegExp("**/*.{ts,rs}"); expect(re.test("index.ts")).toBe(true); expect(re.test("src/lib.rs")).toBe(true); expect(re.test("src/lib.java")).toBe(false); const filter = compilePathFilter({ include: ["**/*.{ts,rs}"], exclude: ["node_modules/**", "packages/pkg/dist/**"] }); expect(shouldIncludeCompiledPath("src/lib.rs", filter)).toBe(true); expect(shouldIncludePath("node_modules/x.ts", filter)).toBe(false); expect(isExcludedPath("node_modules/x.ts", filter)).toBe(true); expect(isExcludedPath("packages/pkg/dist/x.ts", filter)).toBe(true); const defaults = compilePathFilter(defaultConfig()); expect(shouldIncludeCompiledPath("extensions/devil/node_modules/pkg/index.ts", defaults)).toBe(false); }); test("directory watch traversal is include-whitelisted with exclude veto", () => { const filter = compilePathFilter({ include: ["src/**/*.ts", "docs/*.md"], exclude: ["src/generated/**"] }); expect(shouldWatchDirectory("", filter)).toBe(true); expect(shouldWatchDirectory("src", filter)).toBe(true); expect(shouldWatchDirectory("src/feature", filter)).toBe(true); expect(shouldWatchDirectory("docs", filter)).toBe(true); expect(shouldWatchDirectory("research", filter)).toBe(false); expect(shouldWatchDirectory("docs/deep", filter)).toBe(false); expect(shouldWatchDirectory("src/generated", filter)).toBe(false); }); test("globstar include watches all directories unless excluded", () => { const filter = compilePathFilter({ include: ["**/*.ts"], exclude: ["node_modules/**"] }); expect(shouldWatchDirectory("any/depth", filter)).toBe(true); expect(shouldWatchDirectory("node_modules", filter)).toBe(false); }); test("toSlash and previewText are allocation-aware utility behavior", () => { expect(toSlash("a/b/c")).toBe("a/b/c"); expect(toSlash("a\\b\\c")).toBe("a/b/c"); expect(previewText(" one\n two\tthree ", 9)).toBe("one two …"); }); }); describe("llmiterate output snapshots", () => { test("agent prompt snapshot", () => { const [block] = parseMarkerPrompts("a.rs", "LLM implement foo"); expect(buildAgentPrompt(block!)).toMatchSnapshot(); }); });