import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import { buildAgentPrompt, COMMENT_PREFIXES_BY_EXTENSION, compilePathFilter, defaultConfig, emptyState, globToRegExp, hashProjectRoot, isExcludedPath, isLlmiterateDisabled, loadState, normalizeConfig, parseMarkerPrompts, platformStateDir, previewText, projectStoreDir, STATE_FILE, saveState, shouldIncludeCompiledPath, shouldIncludePath, shouldWatchDirectory, toSlash, } from "../core"; const tempDirs: string[] = []; afterEach(() => { for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function tempDir(): string { const dir = mkdtempSync(join(tmpdir(), "llmiterate-core-")); tempDirs.push(dir); return dir; } describe("llmiterate parser", () => { test("parses only comment-transported canonical marker", () => { const blocks = parseMarkerPrompts( "Main.java", [ "void main(final String[] a) {", " // llmiterate: some prompt text", " if (a.length == 0)", " //llmiterate: deal with this", "}", ].join("\n"), ); expect(blocks).toHaveLength(2); expect(blocks[0]).toMatchObject({ marker: "llmiterate:", startLine: 2, endLine: 2, prompt: "some prompt text", }); expect(blocks[1]).toMatchObject({ startLine: 4, prompt: "deal with this" }); }); test("rejects raw and legacy markers", () => { expect( parseMarkerPrompts("a.ts", "llmiterate: raw is invalid"), ).toHaveLength(0); expect( parseMarkerPrompts("a.ts", "LLM implement foo\nPROMPT implement bar"), ).toHaveLength(0); expect(parseMarkerPrompts("a.ts", "// LLM implement foo")).toHaveLength(0); }); test("groups consecutive llmiterate comment lines", () => { const blocks = parseMarkerPrompts( "a.ts", [ "// llmiterate: open ui", "// llmiterate: 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("supports extension-scoped builtin comment prefixes", () => { const samples = [ ["x.sh", "# llmiterate: shell"], ["x.sql", "-- llmiterate: sql"], ["x.lisp", ";;; llmiterate: lisp"], ["x.tex", "% llmiterate: tex"], ["x.md", ""], ["x.c", "/* llmiterate: c */"], ["x.java", "// llmiterate: javadoc"], ["x.lua", "-- llmiterate: lua"], ] as const; expect( samples.map(([file, line]) => parseMarkerPrompts(file, line)[0]?.prompt), ).toEqual([ "shell", "sql", "lisp", "tex", "markdown", "c", "javadoc", "lua", ]); }); test("rejects prefixes outside their extension", () => { expect(parseMarkerPrompts("x.md", "# llmiterate: heading")).toHaveLength(0); expect(parseMarkerPrompts("x.md", "* llmiterate: bullet")).toHaveLength(0); expect( parseMarkerPrompts("x.ts", ""), ).toHaveLength(0); expect( parseMarkerPrompts("x.txt", "// llmiterate: unknown extension"), ).toHaveLength(0); }); test("appends configured comment prefixes by extension", () => { const config = normalizeConfig({ commentPrefixes: { foo: ["COMMENT"] } }); expect(config.commentPrefixes.ts).toContain("//"); expect(config.commentPrefixes.foo).toContain("COMMENT"); expect( parseMarkerPrompts( "a.foo", "COMMENT llmiterate: custom", config.commentPrefixes, )[0]?.prompt, ).toBe("custom"); }); test("disable directive ignores whole file", () => { expect( isLlmiterateDisabled("// !llmiterate\n// llmiterate: ignored", "a.ts"), ).toBe(true); expect( parseMarkerPrompts("a.ts", "// !llmiterate\n// llmiterate: ignored"), ).toEqual([]); expect( parseMarkerPrompts("a.ts", "prose !llmiterate\n// llmiterate: active"), ).toHaveLength(1); }); test("normalizes CRLF and CR line endings", () => { expect( parseMarkerPrompts("a.ts", "// llmiterate: one\r\n// llmiterate: two")[0] ?.prompt, ).toBe("one\ntwo"); expect( parseMarkerPrompts("a.ts", "// llmiterate: one\r// llmiterate: two")[0] ?.prompt, ).toBe("one\ntwo"); }); test("exact marker boundary", () => { expect(parseMarkerPrompts("a.ts", "// llmiteratex: nope")).toHaveLength(0); expect(parseMarkerPrompts("a.ts", "// llmiterate : nope")).toHaveLength(0); expect(Object.keys(COMMENT_PREFIXES_BY_EXTENSION).length).toBeGreaterThan( 10, ); }); }); describe("llmiterate config/state/path helpers", () => { test("defaults to watching everything except excludes", () => { const config = defaultConfig(); const filter = compilePathFilter(config); expect(config.include).toEqual(["**/*"]); expect(shouldWatchDirectory("", filter)).toBe(true); expect(shouldIncludeCompiledPath("src/a.ts", filter)).toBe(true); }); test("normalizes config", () => { const config = normalizeConfig({ enabled: false, include: ["src/**/*.ts"], exclude: ["tmp/**"], debounceMs: 12.8, maxFileBytes: 42, timeoutMs: 1000.4, maxWatchDirs: 77.7, commentPrefixes: { foo: ["COMMENT"] }, model: "zai/glm-5.1", thinking: "high", notify: "all", }); expect(config).toMatchObject({ enabled: false, include: ["src/**/*.ts"], exclude: expect.arrayContaining(["tmp/**", "**/.jj/**"]), debounceMs: 12, maxFileBytes: 42, timeoutMs: 1000, maxWatchDirs: 77, model: "zai/glm-5.1", thinking: "high", notify: "all", }); expect(config.commentPrefixes.ts).toContain("//"); expect(config.commentPrefixes.foo).toContain("COMMENT"); }); 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", { XDG_STATE_HOME: "C:\\state", LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local", }, "C:\\Users\\me", ), ).toBe("C:\\state\\pi"); }); test("saves and loads state, invalid state falls back empty", () => { const storeDir = tempDir(); const state = emptyState(); state.markers["a.ts:1:hash"] = { file: "a.ts", startLine: 1, endLine: 1, promptHash: "hash", promptPreview: "preview", status: "done", attempts: 1, queuedAt: 123, updatedAt: 456, }; saveState(storeDir, state); expect(loadState(storeDir)).toEqual(state); expect( readFileSync(join(storeDir, STATE_FILE), "utf-8").endsWith("\n"), ).toBe(true); writeFileSync( join(storeDir, STATE_FILE), JSON.stringify({ version: 1, markers: { bad: { file: "missing" } } }), ); expect(loadState(storeDir)).toEqual(emptyState()); }); test("loadState resets queued/running markers to failed", () => { const storeDir = tempDir(); const state = emptyState(); state.markers.a = { file: "a.ts", startLine: 1, endLine: 1, promptHash: "h", promptPreview: "p", status: "running", attempts: 1, queuedAt: 1, updatedAt: 1, }; saveState(storeDir, state); expect(loadState(storeDir).markers.a?.status).toBe("failed"); }); 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(".jj/repo/store.ts", defaults)).toBe( false, ); expect(shouldWatchDirectory(".local", defaults)).toBe(false); expect( shouldIncludeCompiledPath(".local/share/Trash/files/a.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("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", "// llmiterate: implement foo"); expect(block).toBeDefined(); if (!block) throw new Error("expected llmiterate block"); expect(buildAgentPrompt(block)).toMatchSnapshot(); }); });