import { type ParsedNote } from "./parser.js"; import { type PeriodicConfig } from "./periodic.js"; /** Maximum file size {@link Vault.readNote} / {@link Vault.writeNote} will * process by default. 5 MB — large enough for any realistic note, small * enough that a runaway file (e.g. a multi-GB log mistakenly placed in * the vault) doesn't OOM the server. */ export declare const DEFAULT_MAX_FILE_BYTES: number; /** Maximum in-memory parsed-note cache size (LRU eviction past this). */ export declare const DEFAULT_MAX_CACHE_ENTRIES = 1024; /** Maximum size of the on-disk parse cache file (`~/.cache/enquire/.json`). * Refuse to read or write a larger file — defensive limit so a corrupted * cache can't balloon. */ export declare const DEFAULT_MAX_DISK_CACHE_BYTES: number; /** * A markdown file discovered by {@link Vault.listMarkdown}. Carries both * absolute and vault-relative paths so callers can chose whichever fits * their downstream API. */ export interface FileEntry { /** Absolute filesystem path. */ absPath: string; /** Vault-relative path (forward-slash separated on all platforms). */ relPath: string; /** Basename including the `.md` extension. */ basename: string; /** Modification time, ms since epoch. */ mtimeMs: number; } /** A parse-cached note (post-frontmatter body + parsed structure + the * mtime at parse time, for cache freshness). */ export interface CachedNote { /** Raw file content (UTF-8). */ content: string; /** Parsed structure — see {@link ParsedNote}. */ parsed: ParsedNote; /** mtime at parse time. Used to detect stale cache entries. */ mtimeMs: number; } /** * Options accepted by the {@link Vault} constructor. Every field is * optional; omit to accept the documented default. */ export interface VaultOptions { /** Per-file size cap. Default {@link DEFAULT_MAX_FILE_BYTES}. */ maxFileBytes?: number; /** In-memory parsed-note cache size cap. Default {@link DEFAULT_MAX_CACHE_ENTRIES}. */ maxCacheEntries?: number; /** Allow `writeNote` / `appendNote` / `renameFile`. Default false (read-only). */ enableWrite?: boolean; /** Persist the parse cache across server restarts. Default false. */ persistentCache?: boolean; /** Override the cache file location. Default: ~/.cache/enquire/.json. */ cacheFile?: string; /** Refuse to read/write a cache file larger than this (default 50 MB). */ maxDiskCacheBytes?: number; /** Glob patterns matched against vault-relative paths. Excluded paths never appear in * listMarkdown(), and reads/writes against them throw. Privacy filter for users who * point an LLM at a vault but want `02_Personal/**` invisible. */ excludeGlobs?: string[]; /** Glob patterns matched against vault-relative paths. When set, ONLY paths matching * one of these patterns are visible — strict allowlist mode. Complement to * excludeGlobs (cyanheads OBSIDIAN_READ_PATHS pattern). If both are set, a path * must match an allow-glob AND not match any exclude-glob. */ readPaths?: string[]; } /** * Vault — the central read-and-cache layer over the user's Obsidian * directory. Handles path safety (no escapes via `..` or symlinks), * privacy filtering (`--read-paths` allowlist + `--exclude-glob` denylist), * parsed-note caching (in-memory LRU + optional persistent JSON file), * and write gating (opt-in via `--enable-write`). * * Construct once at server start, then share across all tool calls. * Methods are async because filesystem IO; the in-memory cache makes * repeated reads of the same note ~free. * * @example * ```ts * const vault = new Vault("/home/me/Vault", { enableWrite: false }); * await vault.ensureExists(); * const md = await vault.listMarkdown(); * const note = await vault.readNote(md[0].absPath); * ``` */ export declare class Vault { root: string; readonly maxFileBytes: number; readonly maxCacheEntries: number; readonly writeEnabled: boolean; readonly persistentCacheEnabled: boolean; readonly maxDiskCacheBytes: number; readonly excludeGlobs: readonly string[]; readonly readPaths: readonly string[]; private excludeMatchers; private readPathMatchers; cacheFile: string | null; private cache; private cacheDirty; private ready; /** Lazily loaded periodic-notes config (.obsidian/daily-notes.json + Periodic * Notes plugin). Cached forever after first read — users restart the server * if they reconfigure plugins. */ private periodicConfig; constructor(root: string, opts?: VaultOptions); /** v2.0.0-beta.2: helper that returns the reason a path was excluded, or * null if not excluded. Lets call sites surface the right CLI flag in * user-facing error messages without duplicating the regex predicates. */ exclusionReason(relPath: string): "--read-paths allowlist (path doesn't match any allow-glob)" | "--exclude-glob denylist" | null; /** True if a vault-relative path is filtered out by either --read-paths * (strict allowlist) or --exclude-glob (denylist). When --read-paths is set * but the path doesn't match any allow-glob, the file is treated as * excluded — no list/read/write/watch event surfaces it. * When BOTH are set: must match an allow-glob AND not match an exclude. */ isExcluded(relPath: string): boolean; /** * Verify the vault root exists, is a directory, and resolve through any * symlinks. Idempotent — safe to call before every operation; the * underlying state is cached after the first successful call. * * Also (when persistent cache is enabled) loads the on-disk parse cache. * * @throws {Error} If the vault root doesn't exist or isn't a directory. */ ensureExists(): Promise; /** * Read the on-disk parse cache (`.cache/enquire/.json`) into the * in-memory LRU. Drops entries whose source file is missing, oversized, * or path-traverses outside the vault. Re-runs the realpath check to * guard against symlink-based escape attempts in a tampered cache file. * * v3.7.16 P1-4 — ALSO drops entries that violate the LIVE privacy * filter state (`--exclude-glob` / `--read-paths`). Pre-3.7.16, if a * user filled the cache with all notes and then added a new exclusion * pattern on the next start, the excluded note bodies were silently * restored into the in-memory cache (and rewritten on the next save). * Privacy-driven drops mark `cacheDirty` so the next `saveDiskCache` * persists the pruned snapshot, and emit a stderr disclosure line. * * Idempotent — entries already in memory aren't duplicated. * * @returns Number of entries loaded into memory. * @internal called automatically by {@link ensureExists} when persistent * cache is enabled. */ loadDiskCache(): Promise; /** * Delete the on-disk parse cache file and reset the in-memory cache. * No-op when persistent cache wasn't configured. * * @returns `true` if a cache file was removed, `false` if no file existed. */ clearDiskCache(): Promise; /** * Flush the in-memory parse cache to disk. Writes to a temp file then * atomically renames over the target so a crash mid-flush can't * corrupt the cache. Sets mode 0o600 on the cache file and 0o700 on * its directory to keep note bodies private to the user account. * * No-op when persistent cache wasn't configured or the cache hasn't * been modified since the last save (`cacheDirty` flag). */ saveDiskCache(): Promise; /** * Resolve a vault-relative or absolute path to an absolute path, after * asserting the result stays inside the vault root. This is the * lexical guard; {@link resolveSafePath} additionally walks symlinks. * * @param p - Path string (relative or absolute). * @returns Absolute path. * @throws {Error} If the resolved path escapes the vault root. */ resolveInside(p: string): string; /** * List every markdown file under the vault root (or a subfolder). * Skips `.git` / `.obsidian` / `.trash` / `node_modules` directories, * follows the standard hidden-file rule (no dotfiles), refuses to * traverse symlinks. Applies the privacy filter (`--exclude-glob` / * `--read-paths`) before returning. * * @param folder - Optional vault-relative subfolder. When set, scan * only under that folder. Returns `[]` if the folder doesn't exist, * is a symlink, or is itself excluded. * @returns Discovered files in walk order (depth-first, alphabetical). */ listMarkdown(folder?: string): Promise; /** Walk the vault and return files ending with the given extension (e.g. * ".canvas", ".pdf"). Honors --exclude-glob + --read-paths. Used by the * v1.7 canvas tools and any future file-format-specific tools. */ listFilesByExtension(ext: string, folder?: string): Promise; /** Read a non-markdown file (e.g. `.canvas` JSON). Same path-safety + size * cap as readFile/readNote, but returns Buffer so callers can decide on * encoding. */ /** v3.10.0-rc.45 (abs-path-leak class) — strip the vault root from an fs error so a * CLIENT-facing message never reveals the host's absolute path / home dir, while * PRESERVING `err.code` and the ENOENT-shaped message text some callers regex-match * (e.g. resolveTarget's periodic fallback). Mutates + returns the same error object. */ private sanitizeFsError; private statSafe; private realpathSafe; private readFileSafe; private mkdirSafe; private writeFileSafe; private openSafe; private renameSafe; private linkSafe; private copyFileSafe; private unlinkSafe; readBinaryFile(relOrAbs: string): Promise; /** * Read a text file (UTF-8) from the vault. Same path-safety and size * cap as {@link readNote}, but doesn't parse — useful for non-markdown * text files where the caller wants the raw bytes. * * @param relOrAbs - Vault-relative or absolute path. * @returns File content as UTF-8 string. * @throws {Error} If the path escapes the vault, is excluded by privacy * filter, or the file exceeds the size cap. */ readFile(relOrAbs: string): Promise; /** * Read and parse a markdown note. Returns the cached entry when the * file's mtime hasn't changed; otherwise reads from disk, parses via * {@link parseNote}, and caches the result (LRU-evicting the oldest * entry when at capacity). * * @param relOrAbs - Vault-relative or absolute path to a `.md` file. * @param knownMtimeMs - Optional pre-stat'd mtime (saves a `fs.stat` * call when the caller already has it, e.g. straight after `listMarkdown`). * @returns Cached note including parsed structure. * @throws {Error} If the path escapes the vault, is excluded, or * exceeds the size cap. */ readNote(relOrAbs: string, knownMtimeMs?: number): Promise; /** * Create or overwrite a markdown note. Requires `enableWrite: true` at * construction. Honors privacy filters — refuses to write to a path * excluded by `--read-paths` / `--exclude-glob`. Refuses to write * through symlinks. Auto-creates parent directories. * * v3.7.13 M2 — `overwrite=false` uses the `wx` open flag for atomic * exclusive create (closes stat-then-write TOCTOU race). * * v3.7.16 P1-6 — privacy filter runs on the canonical-case relative * path (resolved via `realpath` against the nearest existing parent) * rather than the lexical user input. Closes the case-insensitive-FS * bypass on default macOS HFS+/APFS and Windows NTFS where * `personal/secret.md` and `Personal/secret.md` resolve to the same * physical file but used to bypass `--exclude-glob "Personal/**"`. * * @param relPath - Vault-relative target path. `.md` suffix is added * if absent. Must not be empty / `.` / `.md`. * @param content - File body (UTF-8). Must be under the size cap. * @param opts.overwrite - If true, replace an existing file; otherwise * throw when the target exists. Default false. * @returns Metadata about the written file. * @throws {Error} If the vault is read-only, the destination is * excluded, the target is a symlink, content exceeds the cap, or * the file exists and `overwrite` is false. */ writeNote(relPath: string, content: string, opts?: { overwrite?: boolean; }): Promise<{ absPath: string; relPath: string; mtimeMs: number; bytes: number; }>; private assertParentInsideVault; /** * v3.7.16 P1-6 — return the relative path used for privacy-filter * matching, canonicalized against the filesystem's actual case * convention. On case-insensitive filesystems (default macOS HFS+/APFS, * default Windows NTFS), `personal/Note.md` and `Personal/Note.md` * resolve to the same physical file. Pre-3.7.16 the privacy check ran * on the LEXICAL relative path (whatever the caller typed), so a * case-variant of an excluded folder bypassed `--exclude-glob` / * `--read-paths`. * * Strategy: walk UP from the target until we hit an existing parent, * resolve its real (on-disk) path via `fs.realpath`, then re-join the * not-yet-existing tail segments AS-TYPED. This yields a path whose * EXISTING prefix uses the filesystem's canonical case and whose TAIL * uses the caller's case (which is fine — the tail doesn't exist yet, * so it has no canonical case). Linux ext4/btrfs (case-sensitive) * filesystems treat realpath as a no-op, so this is portable. * * Falls back to the lexical form if no parent exists (vault root * missing — handled by the broader `ensureExists` startup check). */ /** * Public alias for {@link canonicalRelForPrivacyCheck}. v3.7.16 P1-6 — * used by `renameNote` wrapper in `src/tools/write.ts` to fail-fast on * case-insensitive-FS variants before doing O(N) backlink-rewrite work. * The inner `renameFile` also does this check; this public surface lets * orchestrators pre-check without duplicating the realpath logic. */ canonicalRelForPrivacyCheckPublic(abs: string): Promise; private canonicalRelForPrivacyCheck; /** Rename a markdown file inside the vault. v3.7.14 F2 — atomic destination * guard via `fs.link(fromAbs, toAbs)` + `fs.unlink(fromAbs)` for the * non-overwrite path (link(2) fails atomically with EEXIST, closing the * stat-then-rename TOCTOU race that POSIX rename(2) silently lost by * replacing destinations). Cross-device fallback (`EXDEV`) uses * `fs.copyFile(..., COPYFILE_EXCL)` + `fs.unlink` for the same atomic * guarantee. The overwrite=true path keeps plain `fs.rename` since the * caller opted into replacement. Refuses if source missing, target exists * (unless overwrite), either path traverses, or the target sits behind a * symlink that points outside the vault. Caller is responsible for * rewriting wikilinks pointing at the old name (see {@link renameNote} * in `src/tools/write.ts` for the orchestration). * * v3.7.16 P1-6 — destination privacy filter uses * {@link canonicalRelForPrivacyCheck} (case-insensitive-FS bypass * closure; parity with `writeNote`). */ /** * v3.10.0-rc.61 (WRITE-3) — true iff `fromAbs`/`toAbs` differ only in case AND resolve to the * SAME physical file (same inode) — i.e. a case-only rename on a case-INSENSITIVE filesystem. * On a case-SENSITIVE FS the two are distinct files (toAbs is a different inode or absent) → false. */ private isSameInodeCaseRename; renameFile(fromRel: string, toRel: string, opts?: { overwrite?: boolean; }): Promise<{ from: string; to: string; mtimeMs: number; }>; /** * Append text to an existing note. Requires `enableWrite: true`. * Refuses if the resulting file would exceed the size cap. * * v3.7.14 F3 — the size-cap check is performed against the OPEN file * descriptor's `fstat`, not a separate `fs.stat(abs)` call before * `fs.appendFile`. Pre-3.7.14 the two-call pattern let parallel * writers race the cap: stat says `before.size + addition <= max`, * another process appends size Y between stat and our append, our * append takes the file past `max`. The post-3.7.14 single-fd pattern * keeps stat→write inside one kernel handle that another process * can't reposition. * * @param relOrAbs - Vault-relative or absolute target path. * @param addition - Text to append (UTF-8). Caller is responsible for * including any leading newline. * @returns Metadata about the file after the append. * @throws {Error} If the vault is read-only or the appended file * would exceed `maxFileBytes`. */ appendNote(relOrAbs: string, addition: string): Promise<{ absPath: string; relPath: string; mtimeMs: number; appended_bytes: number; }>; /** Drop every entry from the in-memory parse cache. Used after bulk * changes (e.g. a full vault rebuild). Does NOT delete the on-disk * cache file — call {@link clearDiskCache} for that. */ invalidateCache(): void; /** Drop a single cached note by absolute path. Used by the watcher when one * file changes — full-cache clear would be wasteful for a 5k-note vault. */ invalidateOne(absPath: string): void; /** * Stat a vault file. Same path-safety as the read methods but no * size-cap check (callers may want to inspect oversized files' * metadata). * * @param relOrAbs - Vault-relative or absolute path. * @returns Modification time and byte size. */ stat(relOrAbs: string): Promise<{ mtimeMs: number; size: number; }>; /** Convert an absolute path under the vault to a vault-relative one * (POSIX-separated on all platforms). Does not verify the result * stays inside the vault; callers needing that should use * {@link resolveInside}. */ toRel(abs: string): string; /** * Find a markdown note by title (basename without `.md`, case-insensitive). * Returns the first match in walk order — vaults with duplicate titles * across folders silently pick one. * * v3.7.16 P2-13 — WRITE callers should use {@link findAllByTitle} + * fail-on-ambiguity instead of this method (silent first-match * selection here is fine for read paths but causes silent data * corruption when used as the write-target resolver). The * `resolveTarget` helper in `src/tools/write.ts` has an * `opts.strictOnAmbiguousTitle` flag for the write/read distinction. * * @param title - Note title with or without `.md` suffix. * @returns The matching file entry, or `null` if no note matches. */ findByTitle(title: string): Promise; /** * v3.7.16 P2-13 — find ALL notes with a given title (basename match). * Used by write tools to FAIL LOUDLY when multiple files share a * basename instead of silently mutating the first walk-order match. * * Pre-3.7.16, `appendToNote({ title: "Daily" })` would mutate * `Work/Daily.md` or `Personal/Daily.md` depending on directory walk * order — a silent-data-corruption footgun. Write surfaces now use * this method, fail on `.length > 1`, and surface the candidate paths * to the caller so they can disambiguate by `path`. * * @param title - Title without `.md` (case-insensitive basename match). * @returns All matching file entries (empty array if no match). */ findAllByTitle(title: string): Promise; /** Periodic Notes plugin config (`.obsidian/daily-notes.json` + Periodic * Notes plugin's `data.json`). Lazy-loaded, then cached for the process * lifetime. Returns an empty config when no plugin files exist. */ getPeriodicConfig(): Promise; private resolveSafePath; private assertSize; private cacheSet; } /** * Defensive cap on a glob pattern length (v3.10.0-rc.68, round-3 re-sweep). Bounds the * tokenize/match work on an absurd operator-supplied glob from `--exclude-glob` / * `--read-paths`. As of v3.10.0-rc.71 the catastrophic-backtracking guard is structural — * {@link compileGlob} matches via a NON-backtracking DP, not a `RegExp` — so this is a * cheap secondary bound, not the ReDoS guard. */ export declare const MAX_GLOB_PATTERN_LEN = 1024; /** * Compile a minimal glob into a NON-backtracking matcher anchored against * vault-relative paths (forward-slash separated). Supports: * `*` — any run of non-slash characters * `**` — any run of characters including slashes (globstar) * `?` — exactly one non-slash character * No bracket sets, no `!` negation, no `{a,b}` alternation. Patterns are matched * against the full vault-relative path (e.g. `02_Personal/Inbox/x.md`). The * returned object exposes `.test(path)` so call sites read like the old * `globToRegex(...).test(...)`. * * v3.10.0-rc.71 (post-rc.66 re-sweep, ReDoS class — closes the rc.68 sibling): matching * is now a NON-backtracking DP ({@link matchWildcardTokens}), NOT a `RegExp`. The * pre-rc.71 `globToRegex` compiled `*`→`[^/]*` / `**`→`.*` and (rc.68) collapsed only * ADJACENT unbounded quantifiers. A glob with wildcards SEPARATED BY LITERALS * (`*a*a*…` → `^[^/]*a[^/]*a…$`, or `**a**a…`) was still catastrophic — the rc.68 * adjacency-collapse cannot touch a literal-separated run, and its structural guard * (asserting "no adjacent quantifiers") gave false confidence against this shape. The * catastrophe scales with the matched PATH length (paths can be 100+ chars deep), so a * wildcard count cap is not structurally safe. This filter runs via `.test()` on EVERY * path of EVERY vault scan, so one fat-fingered `--exclude-glob` / `--read-paths` froze * every scan; the linear matcher removes the backtracking engine entirely. */ export declare function compileGlob(glob: string): { test(path: string): boolean; }; //# sourceMappingURL=vault.d.ts.map