import * as fs from "node:fs"; import * as path from "node:path"; export const DEFAULT_DIR_GLOB = "**/*.md"; export type PulseDocType = "file" | "dir" | "glob"; export interface PulseDoc { path: string; type?: PulseDocType; glob?: string; instruction?: string; model?: string; } export type PulseApplyMode = "auto" | "confirm" | "review"; export interface PulseConfig { documents: PulseDoc[]; model?: string; interval?: number; apply?: PulseApplyMode; } const GLOB_CHARS = /[*?[]/; const REGEX_CHARS = /[|\\{}()[\]^$+?.]/; const TERMINAL_CONTROLS = /\x1B\][\s\S]*?(?:\x07|\x1B\\)|\x9D[\s\S]*?(?:\x07|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-Z\\-_]|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g; export function toSlash(s: string): string { return s.split(path.sep).join("/"); } export function stripUnsafeText(s: string): string { return s.replace(TERMINAL_CONTROLS, "").replace(/\r/g, ""); } export function isModelSpec(s: string): boolean { return /^[^\s/]+\/[^\s/]+$/.test(s); } function assertRealPathInside(cwd: string, target: string): void { const root = fs.realpathSync(cwd); const real = fs.realpathSync(target); const rel = path.relative(root, real); if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`unsafe path: ${path.relative(cwd, target) || target}`); } export function safeRelativePath(cwd: string, input: string): string { if (!input || path.isAbsolute(input)) throw new Error(`unsafe path: ${input}`); const rel = path.relative(cwd, path.resolve(cwd, input)); if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`unsafe path: ${input}`); return rel === "" ? "." : toSlash(rel); } export function assertSafeGlob(pattern: string): void { if (!pattern || path.isAbsolute(pattern)) throw new Error(`unsafe glob: ${pattern}`); for (const part of toSlash(pattern).split("/")) { if (part === "..") throw new Error(`unsafe glob: ${pattern}`); } } export function createFileDoc( cwd: string, filePath: string, instruction?: string, ): PulseDoc { const rel = safeRelativePath(cwd, filePath); const abs = path.join(cwd, rel); assertRealPathInside(cwd, abs); const st = fs.statSync(abs); if (!st.isFile()) throw new Error(`not a file: ${rel}`); return instruction ? { path: rel, instruction } : { path: rel }; } export function createDirDoc( cwd: string, dirPath: string, glob: string, instruction?: string, ): PulseDoc { const rel = safeRelativePath(cwd, dirPath); assertSafeGlob(glob); const abs = path.join(cwd, rel); assertRealPathInside(cwd, abs); const st = fs.statSync(abs); if (!st.isDirectory()) throw new Error(`not a directory: ${rel}`); const doc: PulseDoc = { path: rel, type: "dir", glob: toSlash(glob) }; if (instruction) doc.instruction = instruction; return doc; } export function createGlobDoc(pattern: string, instruction?: string): PulseDoc { assertSafeGlob(pattern); const doc: PulseDoc = { path: toSlash(pattern), type: "glob" }; if (instruction) doc.instruction = instruction; return doc; } export function normalizeDoc(cwd: string, doc: PulseDoc): PulseDoc | null { if (!doc || typeof doc.path !== "string") return null; const type = doc.type ?? "file"; if (type !== "file" && type !== "dir" && type !== "glob") return null; if ( doc.model !== undefined && (typeof doc.model !== "string" || !isModelSpec(doc.model)) ) return null; if (doc.instruction !== undefined && typeof doc.instruction !== "string") return null; try { if (type === "glob") { assertSafeGlob(doc.path); return { ...doc, path: toSlash(doc.path), type }; } const rel = safeRelativePath(cwd, doc.path); if (type === "dir") { const glob = doc.glob ?? DEFAULT_DIR_GLOB; assertSafeGlob(glob); return { ...doc, path: rel, type, glob: toSlash(glob) }; } return { ...doc, path: rel }; } catch { return null; } } function globBase(pattern: string): string { const parts = toSlash(pattern).split("/"); const base: string[] = []; for (const part of parts) { if (GLOB_CHARS.test(part)) break; base.push(part); } return base.join("/") || "."; } export function globToRegExp(pattern: string): RegExp { const g = toSlash(pattern); let s = "^"; for (let i = 0; i < g.length; ) { const c = g[i]; if (c === "*") { if (g[i + 1] === "*") { i += 2; if (g[i] === "/") { i++; s += "(?:.*/)?"; } else { s += ".*"; } continue; } s += "[^/]*"; i++; continue; } if (c === "?") { s += "[^/]"; i++; continue; } s += REGEX_CHARS.test(c) ? `\\${c}` : c; i++; } return new RegExp(`${s}$`); } function collectFiles(dir: string, out: string[]): void { let entries: fs.Dirent[]; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const e of entries) { const p = path.join(dir, e.name); if (e.isFile()) { out.push(p); continue; } if (e.isDirectory()) collectFiles(p, out); } } function expandGlob(cwd: string, pattern: string): string[] { assertSafeGlob(pattern); const base = safeRelativePath(cwd, globBase(pattern)); const baseAbs = path.join(cwd, base); try { assertRealPathInside(cwd, baseAbs); } catch { return []; } const re = globToRegExp(pattern); const files: string[] = []; collectFiles(baseAbs, files); return files .map((f) => toSlash(path.relative(cwd, f))) .filter((rel) => re.test(rel)) .sort(); } export function expandPulseDocuments( cwd: string, docs: PulseDoc[], ): PulseDoc[] { const out: PulseDoc[] = []; const seen = new Set(); const push = (doc: PulseDoc): void => { if (seen.has(doc.path)) return; seen.add(doc.path); out.push(doc); }; for (const raw of docs) { const doc = normalizeDoc(cwd, raw); if (!doc) continue; const type = doc.type ?? "file"; if (type === "glob") { for (const rel of expandGlob(cwd, doc.path)) push({ ...doc, path: rel, type: "file" }); continue; } if (type === "dir") { for (const rel of expandGlob( cwd, `${doc.path}/${doc.glob ?? DEFAULT_DIR_GLOB}`, )) push({ ...doc, path: rel, type: "file" }); continue; } try { const abs = path.join(cwd, doc.path); assertRealPathInside(cwd, abs); if (fs.statSync(abs).isFile()) push({ ...doc, type: "file" }); } catch {} } return out; } export function formatDoc(doc: PulseDoc): string { const type = doc.type ?? "file"; if (type === "dir") return `${doc.path} (${doc.glob ?? DEFAULT_DIR_GLOB})`; if (type === "glob") return doc.path; return doc.path; }