import type { FileEntry, Vault } from "../vault.js"; import { searchHybrid } from "./search.js"; /** * Arguments for {@link validateNoteProposal}. * * Pre-write validator — never mutates disk regardless of `mode`. The mode * only controls how the validator reports path collisions. */ export interface ValidateProposalArgs { /** Vault-relative path the LLM intends to write to (e.g. "Inbox/idea.md"). */ path: string; /** Full proposed markdown content including any frontmatter block. */ content: string; /** "create" (default) → fail if path exists. "overwrite" / "append" → ok if exists. */ mode?: "create" | "overwrite" | "append"; } /** * Structured validation report returned by {@link validateNoteProposal}. * * `ok` is true iff `errors` is empty — warnings don't block the agent. * `wikilinks[*].suggestions` carry did-you-mean hints for broken links so * the LLM can fix-and-retry without writing a broken note. */ export interface ValidateProposalResult { ok: boolean; proposed_path: string; mode: "create" | "overwrite" | "append"; errors: Array<{ kind: string; message: string; }>; warnings: Array<{ kind: string; message: string; suggestion?: string; }>; yaml: { parsed: boolean; error: string | null; keys: string[]; /** v3.11.0-rc.11 (rc.9-audit L4) — true if the frontmatter is valid YAML but NOT * a mapping (a bare scalar / sequence), which `frontmatter_set` refuses (rc.64). * Surfaced so an agent isn't surprised by a later refusal after a green validate. */ coerced: boolean; }; wikilinks: Array<{ raw: string; target: string; status: "resolved" | "broken" | "ambiguous"; resolved_path: string | null; suggestions: string[]; }>; tags: Array<{ name: string; status: "existing" | "new"; }>; collision: { kind: "none" | "path-exists" | "title-exists-elsewhere"; existing_path?: string; }; } /** * Pre-write validator — lint an LLM-proposed note against the live vault * before writing. * * The "anti-slop" first call: the LLM proposes a draft, this validator * checks YAML / wikilinks / tags / path-collision against the vault, and * returns structured `errors[]` + `warnings[]`. The LLM can fix-and-retry * via the same call, finally invoking {@link createNote} / {@link appendToNote} * only after the validator reports `ok: true`. Read-only — never mutates * disk. Always returns a structured result for ANY input, even malformed — * path-traversal errors become `kind: "path-traversal"` errors rather than * exceptions. * * v3.7.16 P2-14 — errors[] now includes `path-excluded` when the * proposed destination is blocked by `--exclude-glob` / `--read-paths`. * Pre-3.7.16 the validator passed structurally-valid proposals into * excluded destinations; the actual write would then fail at runtime. * Pre-write parity with `writeNote` / `createNote` is the new contract. * * @param vault - The vault. * @param args - {@link ValidateProposalArgs}. `path` + `content` required. * @returns A {@link ValidateProposalResult} with `ok`, `errors`, `warnings`, * YAML parse status, per-wikilink resolution, tag classification, and * collision detection. Possible `errors[].kind` values include * `path-traversal`, `path-excluded` (v3.7.16+), `yaml-invalid`, * plus the wikilink / tag / collision categories. * @example * ```ts * const v = await validateNoteProposal(vault, { * path: "Inbox/draft.md", * content: "---\nstatus: draft\n---\n# Title\n\n[[Bar]] is broken.", * mode: "create" * }); * if (!v.ok) { * for (const e of v.errors) console.error(e.kind, e.message); * } * ``` */ export declare function validateNoteProposal(vault: Vault, args: ValidateProposalArgs): Promise; /** * Arguments for {@link lintWiki}. All optional with sensible defaults. */ export interface LintWikiArgs { /** Folder to restrict the lint to (default: whole vault). */ folder?: string; /** Word count below which a note is considered a "stub". Default 100. */ stub_word_threshold?: number; /** A note is "stale" if its frontmatter `last_reviewed` (or mtime if missing) * is older than this many days. Default 365. */ stale_days?: number; /** A capitalised n-gram mentioned by ≥ N distinct notes but not having its * own page is flagged as a concept candidate. Default 3. */ concept_min_mentions?: number; /** Cap on each finding-bucket so the response stays bounded. Default 50. */ max_per_bucket?: number; } /** * One lint finding. `details` carries kind-specific context (word count for * stubs, mention sources for concepts, etc.). `suggestion` is an action * hint the agent can paraphrase to the user. */ export interface LintWikiFinding { /** Lint category. */ kind: "orphan" | "broken-link" | "stub" | "stale" | "concept-without-page"; /** Vault-relative path of the offending note (absent on concept candidates). */ path?: string; /** Human-readable description of the issue. */ message: string; /** Action hint for fixing. */ suggestion?: string; /** Kind-specific payload (word_count, mention_count, sources, etc.). */ details?: Record; } /** * Envelope returned by {@link lintWiki}. * * `summary` carries truncated counts (capped at `max_per_bucket`); use it * for the agent's headline message. `findings` carries the per-issue list. */ export interface LintWikiResult { scope: string; scanned: number; generated_at: string; summary: { orphans: number; broken_links: number; stubs: number; stale: number; concept_candidates: number; }; findings: { orphans: LintWikiFinding[]; broken_links: LintWikiFinding[]; stubs: LintWikiFinding[]; stale: LintWikiFinding[]; concept_candidates: LintWikiFinding[]; }; } /** * Karpathy-style LLM-Wiki lint — single-call audit of orphans, broken * links, stubs, stale notes, and concept candidates. * * Implements the "lint" workflow from Karpathy's LLM-Wiki gist (which named * ingest/query/lint as the three primitives). Returns five finding buckets, * each capped to `max_per_bucket` for bounded responses. Findings are * shaped so the agent can act on them via existing tools * ({@link validateNoteProposal} → {@link createNote} / {@link appendToNote} / * {@link renameNote}). * * Concept candidates use a capitalised-phrase heuristic: 1-3 CapitalCase * tokens that appear in ≥ `concept_min_mentions` notes but don't have a * page of their own. Stop-words ("The", "This", etc.) at phrase start are * dropped. * * @param vault - The vault. * @param args - {@link LintWikiArgs}. All optional with documented defaults. * @returns A {@link LintWikiResult} with summary counts + per-bucket findings. * @throws {VaultPathError} If `folder` resolves outside the vault. * @example * ```ts * const lint = await lintWiki(vault, { * folder: "Wiki", * stub_word_threshold: 50, * stale_days: 180 * }); * console.log(`Orphans: ${lint.summary.orphans}, Stubs: ${lint.summary.stubs}`); * for (const f of lint.findings.broken_links) console.log(f.message); * ``` */ export declare function lintWiki(vault: Vault, args: LintWikiArgs): Promise; /** * One open question / TODO marker surfaced by {@link getOpenQuestions}. * * `context_heading` is the nearest preceding heading (any level) — useful * for context-locating the question without reading the surrounding note. * `age_days` is computed from the note's mtime, so it surfaces questions * that have aged without being touched. */ export interface OpenQuestion { /** Trimmed text of the question (capture group of the matcher). */ question: string; /** Vault-relative path of the source note. */ source_path: string; /** `.md`-stripped basename for display. */ source_title: string; /** Nearest preceding heading, or null if at top of file. */ context_heading: string | null; /** 1-based line number where the question appears. */ line: number; /** Rounded days since the source note was last modified. */ age_days: number; /** ISO-8601 mtime of the source note. */ mtime: string; } /** * Max length of a caller-supplied `obsidian_open_questions` pattern. A hard * cap is the first line of defense (paired with {@link isCatastrophicRegex}) * against an unbounded user regex compiled into V8's backtracking engine. */ export declare const MAX_QUESTION_PATTERN_LEN = 200; /** * Hard wall-clock budget (ms) for matching a CALLER-SUPPLIED * `obsidian_open_questions` pattern against the vault, enforced by running the * match on a WORKER THREAD ({@link matchLinesBounded}). {@link isCatastrophicRegex} * is a best-effort static denylist (ReDoS detection is undecidable — a v3.10.0-rc.39 * re-sweep confirmed a residual tail of nested patterns it under-flags); this is * the HARD backstop. Because matching runs off the main thread, the event loop can * NEVER hang regardless of pattern, and a pattern that blows the budget is rejected * fail-closed. Generous enough that a legit linear pattern over a large vault * finishes well under it, while a catastrophic-backtracking pattern (effectively * unbounded) is killed. * @internal v3.10.0-rc.39 — the hard ReDoS sink-bound (closes the static-detector * residual the rc.36 re-sweep surfaced). */ export declare const MAX_QUESTION_SCAN_MS = 5000; export declare function readUnboundedQuantifier(src: string, pos: number): { unbounded: boolean; length: number; }; /** * Decode a regex escape whose body starts at `src[pos]` (the char AFTER the * backslash) to the single character it matches plus the number of source chars * the body consumes. `char` is `null` if the escape is not a resolvable * single-char escape (caller then treats it as a broad/ANY leading atom — the * safe over-flag direction). Handles `\\xHH`, `\\uHHHH`, `\\u{H+}`, the control escapes, * and punctuation/metacharacter escapes; leaves octal / backrefs / class * shorthands unresolved (`char: null`). `length` is the body length even when * `char` is null (1 for a single unknown char) so callers can still advance. * * Returning `length` makes this the SINGLE source of truth for escape spans: * `leadingAtomSet` and `branchIsNullable` both locate the atom end * through this function rather than re-parsing (a re-parse would risk diverging — * the exact recursion class CLAUDE.md tracks). * * @internal exported only for unit tests. v3.9.0-rc.24 — rc.21 returned the raw * byte after the backslash (`"x"` for `\\x61`), so `(\\x61|a)+` slipped the guard. * v3.9.0-rc.25 — also returns `length` (was `string | null`). */ export declare function decodeEscapedChar(src: string, pos: number): { char: string | null; length: number; }; /** * True if an alternation `body` is AMBIGUOUS under repetition — two of its * top-level branches' leading sets intersect, a branch is broad (ANY), or a * branch is nullable. `(a|a)`, `(a|ab)`, `(.|a)`, `(a|)`, `(a?b|b)` are ambiguous * (→ catastrophic under `+`/`*`); `(a|b|c)`, `(cat|dog)`, `(a?b|c)` are NOT * (disjoint leading sets → linear). Built on {@link leadingAtomSet} (a sound * over-approximation: broad atoms widen to ANY), so it may over-flag a * shared-first-char-but-divergent group (`(cat|car)`) but never under-flags a * real overlap. * @internal exported only for unit tests of {@link isCatastrophicRegex}. */ export declare function alternationBodyAmbiguous(body: string): boolean; /** * Conservative, dependency-free guard against catastrophic-backtracking * (ReDoS) in a caller-supplied regex. V8's Irregexp engine backtracks, so * `(a+)+$`, `(.*)*`, or `(.*a){20}` can freeze the event loop for seconds on * a single long line. `obsidian_open_questions` runs the caller's `pattern` * against every line of every note, so an unvalidated regex is a remote DoS * on a bearer-authenticated `serve-http` (the tool is always registered). * * Catches four catastrophic shapes — each is an unbounded-quantified group * (`(...)+`, `(...)*`, `(...){n,}`, `(...){0,BIG}`) whose body is "dangerous": * 1. **Star height ≥ 2** — the body ALSO contains an unbounded quantifier * (`(a+)+`, `(.*)*`). * 2. **Ambiguous alternation** (v3.9.0-rc.21/rc.24/rc.25) — the body's top-level * branches' LEADING SETS intersect, so the backtracker can split one * repetition many ways: `(a|a)+`, `(a|ab)*`, `(.|a)+`, `(a|A)+` (`/i`), * `(\\x61|a)+` (escape alias), `(a?b|b)+` (optional leading atom). Decided by * `alternationBodyAmbiguous` over `leadingAtomSet` (a sound * over-approximation), so a DISJOINT alternation (`(a|b|c)+`, `(cat|dog)+`, * `(a?b|c)+`) stays accepted and a NON-quantified alternation (`(?:a|b)\s*`, * the default pattern's shape) is never flagged. * 3. **Nullable body** (v3.9.0-rc.25) — the body can match empty (`(a?)+`, * `(\\s*)*`, `()+`), so each repetition can consume nothing. * 4. **Variable-length body** (v3.9.0-rc.25) — the body contains a * variable-length quantifier (`(a{2,5})+`, `(\\w[ba]{0,3})+`, `(a[ab]?)+`); * consecutive repetitions partition a long run exponentially. Gated on the * OUTER quantifier being unbounded, so a BOUNDED outer (`(.+){2,5}`, ≤5 reps * → polynomial) stays accepted. * 5. **Adjacent overlapping quantifiers** (v3.10.0-rc.36) — two ADJACENT atoms, * each unbounded-quantified, whose match sets overlap, at ANY frame INCLUDING * the TOP level: `a*a*$`, `\\w*\\w*$`, `(a)*(a)*$`. rc.21–rc.25 only evaluated * the verdict when a QUANTIFIED GROUP closed, so a BARE top-level sequence * (frame 0 is never popped) slipped — the rc.36 CRITICAL. Decided by * `frameAdjacentOverlap`; a DISJOINT adjacency (`a*b*$`) stays accepted, and a * `.`-greedy absorber tail (`…\\s*\\s*(.+)$`, the default's shape) is benign. * * Sound but conservative: it never UNDER-flags a real catastrophic shape (proven * by the `tests/redos-fuzz.test.ts` fuzz harness, which times a real * `exec` against the static verdict), but it MAY over-flag — `(cat|car)+` * (shared first char), `(a?b)+` / `(\\w+\\s)+` (variable but anchored). For a * security guard, a rare false positive (caller simplifies / omits the override) * beats a hung event loop. * * Honors char-classes (`[...]` contents are literal) and backslash escapes * (`\(`, `\+`, `\|` are literals). Still best-effort — ReDoS detection is * undecidable in general — so the caller also pairs it with * {@link MAX_QUESTION_PATTERN_LEN}. * * @param src - The raw regex source the caller wants to compile. * @returns true if the pattern risks catastrophic backtracking. * @example * ```ts * isCatastrophicRegex("(a+)+$"); // true — nested unbounded quantifiers * isCatastrophicRegex("(a|a)+$"); // true — ambiguous alternation under + * isCatastrophicRegex("(a?b|b)+$"); // true — optional leading atom overlaps (rc.25) * isCatastrophicRegex("(a?){25}"); // true — nullable body under repetition (rc.25) * isCatastrophicRegex("(a{2,5})+"); // true — variable-length body under + (rc.25) * isCatastrophicRegex("\\w*\\w*$"); // true — adjacent overlapping quantifiers (rc.36) * isCatastrophicRegex("a*b*$"); // false — adjacent but DISJOINT (linear) * isCatastrophicRegex("(a|b|c)+"); // false — disjoint alternation (linear) * isCatastrophicRegex("(.+){2,5}"); // false — variable body but BOUNDED outer * isCatastrophicRegex("^Q: (.+)$"); // false — single-level * isCatastrophicRegex("(?:a|b)\\s*c"); // false — alternation NOT unbounded-quantified * ``` */ export declare function isCatastrophicRegex(src: string): boolean; /** * Match `lines` against a caller-supplied regex `pattern` (compiled case-INsensitively) * on a WORKER THREAD, bounded by `budgetMs`. Returns `{ idx, q }` for every line whose * FIRST capture group matched (mirrors the `re.exec(line)?.[1]` contract * {@link getOpenQuestions} uses). The worker isolates V8's backtracking off the main * event loop and the timeout terminates it, so even a catastrophic-backtracking pattern * the best-effort static {@link isCatastrophicRegex} guard MISSED can never hang the * server — it's rejected fail-closed when the budget elapses. An invalid pattern rejects * with a clear error. This is the HARD ReDoS sink-bound; the static guard is a cheap * pre-filter in front of it. * @internal v3.10.0-rc.39 — closes the static-detector residual the rc.36 re-sweep found. */ export declare function matchLinesBounded(pattern: string, lines: readonly string[], budgetMs: number): Promise<{ idx: number; q: string; }[]>; /** * Surface unresolved threads — `Open question:` / `Q:` / `TODO?` / `??` * markers across the vault. * * Karpathy and ML PKM workflows use these as deferred-thinking markers. * This tool returns every such line with source path, context heading, * and `age_days` for staleness ranking. Sorted oldest-first so aging * questions surface for the agent to nudge the user about. * * Scans `parsed.body` (frontmatter excluded) so YAML lines containing * "Q:"-ish tokens don't pollute results. The default matcher is * case-insensitive and accepts list-bullets / quote / heading prefixes * before the marker. Override `pattern` for a custom regex. * * @param vault - The vault. * @param args - All optional. `folder` restricts the scan. `limit` * defaults to 100. `pattern` overrides the default matcher regex. * @returns Sorted `OpenQuestion[]` (oldest-first by `age_days`). * @throws {VaultPathError} If `folder` resolves outside the vault. * @example * ```ts * const qs = await getOpenQuestions(vault, { folder: "Reading", limit: 30 }); * for (const q of qs.slice(0, 5)) { * console.log(`${q.source_path}:${q.line} [${q.age_days}d ago] ${q.question}`); * } * ``` */ export declare function getOpenQuestions(vault: Vault, args: { folder?: string; limit?: number; pattern?: string; scanBudgetMs?: number; }): Promise; /** * One flagged paper note returned by {@link paperAudit}. * * `proposed_frontmatter_patch` is a ready-to-apply YAML patch the agent * can hand to {@link frontmatterSet}. Null when the body has no detectable * identifiers either (the note really has no citation, manual fix needed). */ export interface PaperAuditFinding { /** Vault-relative path of the offending note. */ path: string; /** `.md`-stripped basename for display. */ title: string; /** Whether the note has any of arxiv/doi/url/isbn in frontmatter. */ has_frontmatter_citation: boolean; /** Identifiers detected in body text (deduplicated, URLs capped at 3). */ found_in_body: { arxiv: string[]; doi: string[]; url: string[]; }; /** A ready-to-apply `{ arxiv | doi | url }` patch — or null. */ proposed_frontmatter_patch: Record | null; /** Human-readable description of the issue. */ message: string; } /** * Audit `#paper`-tagged notes for missing citation metadata. * * Scans every note carrying the configured tag and verifies frontmatter has * at least one of `arxiv` / `doi` / `url` / `isbn`. Notes with detectable * identifiers in body text (e.g. `arxiv:2401.12345` from quick-capture) * but missing frontmatter receive an actionable `proposed_frontmatter_patch`. * * @param vault - The vault. * @param args - All optional. `tag` defaults to `"paper"` (leading `#` * stripped if provided). `folder` restricts the scan. `limit` defaults * to 100. * @returns `{ scanned, flagged }` — `scanned` counts notes carrying the * tag; `flagged` is the subset with missing frontmatter citation. * @throws {VaultPathError} If `folder` resolves outside the vault. * @example * ```ts * const audit = await paperAudit(vault, { tag: "paper", limit: 50 }); * console.log(`${audit.flagged.length}/${audit.scanned} papers need citation`); * for (const p of audit.flagged) { * if (p.proposed_frontmatter_patch) { * await frontmatterSet(vault, { path: p.path, set: p.proposed_frontmatter_patch }); * } * } * ``` */ export declare function paperAudit(vault: Vault, args: { tag?: string; folder?: string; limit?: number; }): Promise<{ scanned: number; flagged: PaperAuditFinding[]; }>; /** * One step of a graph traversal path returned by {@link findPath}. */ export interface PathStep { /** Vault-relative path of this step. */ path: string; /** `.md`-stripped basename. */ title: string; /** Wikilink raw text (`[[…]]` content) used to traverse FROM the previous * step to this one. Empty on the source step. */ via: string; } /** * Result of a {@link findPath} traversal. * * `found: false` + `hops: -1` indicates no path within `max_depth`. * `alternatives` is populated only when `args.include_alternatives` is true * and at least one same-length alternative exists. */ export interface FindPathResult { /** Source path (vault-relative, with `.md`). */ from: string; /** Destination path. */ to: string; /** Whether a path was found within `max_depth`. */ found: boolean; /** Shortest path as a sequence of {@link PathStep}. Empty on miss. */ path: PathStep[]; /** Number of hops in `path`. -1 when not found. 0 for from = to. */ hops: number; /** Up to 10 same-length alternatives, only when include_alternatives=true. */ alternatives?: PathStep[][]; } /** * Find the shortest wikilink-graph path between two notes via BFS. * * Multi-hop graph traversal — closes the gap the competitive audit * surfaced ("find paths between concepts" was the most-praised graph * feature in competitor plugins). Returns the shortest path up to * `max_depth` hops; with `include_alternatives: true`, also returns up * to 10 same-length alternatives (useful for "show me different * connections"). * * Uses the shared `EntryIndex` (basename → entries map) for O(1) target * resolution per hop, so repeat calls in a session reuse the index. * v1.8.1 perf fix: builds a `relPath → entry` map once before BFS * (pre-fix was O(N²) per visited node). * * @param vault - The vault. * @param args - One of `from` / `from_title` and one of `to` / `to_title` * required. `max_depth` defaults to 5. `include_alternatives` defaults * to false. `follow_embeds` defaults to true (include `![[embeds]]` as * edges). * @returns A {@link FindPathResult}. When `found: false`, `path: []` and * `hops: -1`. * @throws {Error} If from / to can't be resolved. * @example * ```ts * const r = await findPath(vault, { * from_title: "Attention", * to_title: "RLHF", * max_depth: 4 * }); * if (r.found) { * console.log(`${r.hops} hops:`, r.path.map(s => s.title).join(" → ")); * } * ``` */ export declare function findPath(vault: Vault, args: { from?: string; from_title?: string; to?: string; to_title?: string; max_depth?: number; include_alternatives?: boolean; follow_embeds?: boolean; }): Promise; /** * Result of {@link openInUi} — an `obsidian://` URI ready to hand off to * the desktop app. */ export interface OpenInUiResult { /** Full `obsidian://open?...` URI. */ uri: string; /** Vault name as derived from the root folder leaf. */ vault_name: string; /** Vault-relative path of the target note. */ path: string; /** `.md`-stripped basename for display. */ title: string; } /** * Emit an `obsidian://` URI for hand-off to the Obsidian desktop app. * * No filesystem or network side effect — the URI emission lets the agent * say "open this in Obsidian" without enquire-mcp needing to coordinate * with the running app (pattern from cyanheads' Obsidian MCP). The vault * name is the leaf of the vault root path; Obsidian matches by name OR by * file's absolute path, so this works even when the user opened the vault * under a different name client-side. * * @param vault - The vault. * @param args - One of `path` or `title` required. `new_pane: true` opens * the note in a new pane. * @returns An {@link OpenInUiResult}. The caller is responsible for * actually emitting the URI (e.g. via the MCP client surface or stdout). * @throws {Error} If target can't be resolved. * @example * ```ts * const r = await openInUi(vault, { * path: "Reference/Article.md", * new_pane: true * }); * console.log(r.uri); // → obsidian://open?vault=Vault&file=Reference/Article&newpane=true * ``` */ export declare function openInUi(vault: Vault, args: { path?: string; title?: string; new_pane?: boolean; }): Promise; /** * Arguments for {@link contextPack}. */ export interface ContextPackArgs { /** Topic / question to gather context for. */ query: string; /** Approximate token budget for the bundle. ~4 chars/token assumption. Default 4000. */ budget_tokens?: number; /** Restrict retrieval to this folder. */ folder?: string; /** Include backlinks of top-K notes (1-line each)? Default true. */ include_backlinks?: boolean; /** Include the last N daily notes? Default 0 (off). Set to 3 for "what was I doing recently". */ recent_dailies?: number; } /** * Result of {@link contextPack} — a ready-to-paste markdown bundle. * * `bundle` is the full markdown blob the caller can paste into any AI * chat. `sections` exposes per-section byte counts so the agent can * report what's inside ("4 notes + 12 backlinks + 3 daily notes"). * `estimated_tokens` uses the ~4 chars/token heuristic for English / * Cyrillic; CJK estimates run higher (real tokenization is * model-dependent). */ export interface ContextPackResult { /** Echo of the input query. */ query: string; /** The packed markdown bundle ready to paste into an AI chat. */ bundle: string; /** Approximate token count (chars / 4). */ estimated_tokens: number; /** Echo of the input budget. */ budget_tokens: number; /** Per-section byte counts for observability. */ sections: { notes: number; backlinks: number; dailies: number; }; /** Top-K hit paths included in the bundle. */ included_notes: string[]; } /** * Token-budgeted vault context export — runs hybrid retrieval, gathers * note bodies + backlinks + recent dailies, packs to a token budget, * returns one ready-to-paste markdown blob. * * The MCP-native answer to Smart Connections' "Send to Smart Context" * pattern, but works in any chat (Claude / Cursor / Codex / web UI) by * producing a plain-text bundle. Saves the agent from orchestrating 5 * separate tool calls. * * Budget enforcement: each note's body is truncated to ~50% of remaining * budget so room remains for backlinks + dailies; oversize bodies get a * `[…truncated…]` marker. As a final defense-in-depth, the assembled bundle * is hard-capped at `budget_tokens × 4` chars and marked `[…budget cap * reached…]` if truncated. Top-3 included notes get 1-line backlink * summaries when `include_backlinks` is true. * * @param vault - The vault. * @param args - {@link ContextPackArgs}. `query` required + non-empty. * @param ctx - Server-side context — the SAME shape as {@link searchHybrid}'s * ctx, forwarded verbatim to the inner retrieval. v3.11.6-rc.14: pre-rc.14 * only `ftsIndex`/`embedFile` were accepted, so a server started with * `--enable-reranker` / `--use-hnsw` / `--recency-weight` / `--feedback-weight` * silently packed context in PLAIN RRF order while `obsidian_search` ranked * with the enabled enhancements — an "enabled but not wired" divergence * (the CRL-1/M5 class). Now the full ctx flows through, so the pack's * top-10 is ranked exactly like `obsidian_search` would rank it. * @returns A {@link ContextPackResult} with the packed bundle + meta. * @throws {Error} If `query` is empty / whitespace-only. * @example * ```ts * const pack = await contextPack( * vault, * { * query: "How do I tune the hybrid retrieval?", * budget_tokens: 3000, * include_backlinks: true, * recent_dailies: 3 * }, * { ftsIndex, embedFile: "/path/to/vault.embed.db" } * ); * console.log(pack.bundle); // ready to paste into any chat * ``` */ export declare function contextPack(vault: Vault, args: ContextPackArgs, ctx: Parameters[2]): Promise; /** * Compute the Jaccard similarity coefficient of two sets — `|A ∩ B| / |A ∪ B|`. * * Returns 0 for two empty sets (mathematically undefined; this convention * avoids NaN propagation in similarity score sums). Used by * {@link findSimilar}, {@link getNoteNeighbors}, and {@link searchHybrid} * for tag and co-backlink overlap computations. * * @internal * @param a - First set. * @param b - Second set. * @returns Similarity in `[0, 1]`. 1 means identical sets; 0 means disjoint * or both empty. * @example * ```ts * jaccard(new Set([1, 2, 3]), new Set([2, 3, 4])); * // → 0.5 (intersection {2,3} over union {1,2,3,4}) * ``` */ export declare function jaccard(a: Set, b: Set): number; /** * Count elements present in both sets — `|A ∩ B|`. * * Cheaper than `new Set([...a].filter((x) => b.has(x))).size` when only * the count is needed (no intermediate set allocation). Used by * {@link findSimilar} for shared-outbound overlap percentage. * * @internal * @param a - First set. * @param b - Second set. * @returns Non-negative integer count of common elements. * @example * ```ts * intersectionSize(new Set([1, 2, 3]), new Set([2, 3, 4])); * // → 2 * ``` */ export declare function intersectionSize(a: Set, b: Set): number; /** * Build the character n-gram set of a string. * * Used by {@link findSimilar} for title 3-gram Jaccard similarity. Strings * shorter than `n` produce a single-element set containing the string * itself (so a 1-char title doesn't collapse to an empty signal). * * @internal * @param s - Input string. * @param n - N-gram length (typically 3 for title matching). * @returns Set of character n-grams. Empty only when `s` is empty. * @example * ```ts * ngrams("hello", 3); * // → Set { "hel", "ell", "llo" } * ngrams("a", 3); * // → Set { "a" } * ``` */ export declare function ngrams(s: string, n: number): Set; interface EntryIndex { byBasename: Map; byRelPath: Map; bySuffix: Map; } export declare function indexFor(entries: FileEntry[]): EntryIndex; /** * Resolve a wikilink target string to a concrete vault entry — the * Obsidian-style fuzzy matcher used by every link-traversal tool. * * Resolution priority: * 1. Relative paths (`./`, `../`) → resolve via `path.posix.normalize` * against `fromNote`'s directory. * 2. Exact basename match. On collision, prefer the entry in `fromNote`'s * directory; otherwise return the first. * 3. Path-qualified target → exact-relPath match, then `endsWith` fallback. * * Matches Obsidian's client-side link resolution closely enough that * agents and the desktop app agree on what `[[Target]]` points at. * * @internal * @param entries - File-entry array from `vault.listMarkdown()`. * @param target - Link target string (with or without `.md`). * @param fromNote - Source note's vault-relative path (biases resolution * toward same folder; required for `./` / `../`). * @returns The resolved `FileEntry`, or null if no match. * @example * ```ts * const entries = await vault.listMarkdown(); * findBestMatch(entries, "Foo"); // bare basename * findBestMatch(entries, "Sub/Foo", "X.md"); // path-qualified * findBestMatch(entries, "./Sibling", "Sub/X.md"); // relative * ``` */ export declare function findBestMatch(entries: FileEntry[], target: string, fromNote?: string): FileEntry | null; /** * Strip a trailing `.md` extension (case-insensitive) from a filename or * basename. * * @internal * @param name - Filename or basename. * @returns The input with any trailing `.md` removed. * @example * ```ts * stripMd("Foo.md"); // → "Foo" * stripMd("Foo.MD"); // → "Foo" * stripMd("Foo.canvas"); // → "Foo.canvas" (only .md is stripped) * ``` */ export declare function stripMd(name: string): string; /** * Normalize a tag for comparison — strip leading `#` characters and * lowercase the rest. * * Used everywhere the toolkit compares tags ({@link listNotes}, * {@link listTags}, {@link findSimilar}) to keep `#Draft` / `Draft` / * `#draft` / `DRAFT` all hashing to the same key. * * @internal * @param t - Tag string (with or without leading `#`). * @returns Lowercased, `#`-stripped tag. * @example * ```ts * normalizeTag("#Draft"); // → "draft" * normalizeTag("DRAFT"); // → "draft" * normalizeTag("##Idea"); // → "idea" * ``` */ export declare function normalizeTag(t: string): string; export {}; //# sourceMappingURL=meta.d.ts.map