From 026194ad06351d5efd57690d4fc73ce39f1aa3bc Mon Sep 17 00:00:00 2001
From: dgrissen2 <123790187+dgrissen2@users.noreply.github.com>
Date: Sat, 7 Mar 2026 17:09:57 +0100
Subject: [PATCH] feat: smart file resolution for plannotator annotate (#237)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Add case-insensitive file resolution so users can open markdown files
without typing exact paths. Applies to both the CLI (`plannotator
annotate`) and the `/api/doc` endpoint for linked documents.
Resolution strategies (tried in order):
1. Exact path — absolute or relative to cwd (existing behavior)
2. Case-insensitive relative path — `docs/setup.md` matches `docs/SETUP.md`
3. Bare filename search — `setup.md` searches the entire project tree
Ambiguity handling:
- 1 match → opens the file, prints "Resolved: /full/path"
- 0 matches → "File not found: "
- 2+ matches → "Ambiguous filename: found N matches" with full paths
Skips node_modules, .git, dist, build, .next, __pycache__, .obsidian,
.trash during search. Restricts results to .md/.mdx/.markdown files
and enforces project root boundary (no path traversal).
Extracted shared resolveMarkdownFile() into packages/server/resolve-file.ts
and refactored /api/doc handler to use it, removing ~40 lines of inline
resolution logic.
Co-authored-by: Claude Opus 4.6
Co-authored-by: Michael Ramos
---
apps/hook/server/index.ts | 34 +++++----
apps/opencode-plugin/index.ts | 28 +++++--
packages/server/package.json | 3 +-
packages/server/reference-handlers.ts | 64 +++-------------
packages/server/resolve-file.ts | 101 ++++++++++++++++++++++++++
5 files changed, 152 insertions(+), 78 deletions(-)
create mode 100644 packages/server/resolve-file.ts
diff --git a/apps/hook/server/index.ts b/apps/hook/server/index.ts
index 3893e69..8e1eb3a 100644
--- a/apps/hook/server/index.ts
+++ b/apps/hook/server/index.ts
@@ -37,7 +37,7 @@ import {
} from "@plannotator/server/annotate";
import { getGitContext, runGitDiff } from "@plannotator/server/git";
import { writeRemoteShareLink } from "@plannotator/server/share-url";
-import path from "path";
+import { resolveMarkdownFile } from "@plannotator/server/resolve-file";
// Embed the built HTML at compile time
// @ts-ignore - Bun import attribute for text
@@ -123,30 +123,32 @@ if (args[0] === "review") {
filePath = filePath.slice(1);
}
- // Resolve path - use PLANNOTATOR_CWD if set (original working directory before script cd'd)
- const originalCwd = process.env.PLANNOTATOR_CWD || process.cwd();
+ // Use PLANNOTATOR_CWD if set (original working directory before script cd'd)
+ const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
- // Debug: log path resolution (visible in stderr, won't interfere with stdout JSON)
if (process.env.PLANNOTATOR_DEBUG) {
- console.error(`[DEBUG] Original CWD: ${originalCwd}`);
+ console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] File path arg: ${filePath}`);
}
- const absolutePath = path.isAbsolute(filePath)
- ? filePath
- : path.join(originalCwd, filePath);
+ // Smart file resolution: exact path, case-insensitive relative, or bare filename search
+ const resolved = await resolveMarkdownFile(filePath, projectRoot);
- if (process.env.PLANNOTATOR_DEBUG) {
- console.error(`[DEBUG] Resolved path: ${absolutePath}`);
+ if (resolved.kind === "ambiguous") {
+ console.error(`Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:`);
+ for (const match of resolved.matches) {
+ console.error(` ${match}`);
+ }
+ process.exit(1);
}
-
- // Read the markdown file
- const file = Bun.file(absolutePath);
- if (!(await file.exists())) {
- console.error(`File not found: ${absolutePath}`);
+ if (resolved.kind === "not_found") {
+ console.error(`File not found: ${resolved.input}`);
process.exit(1);
}
- const markdown = await file.text();
+
+ const absolutePath = resolved.path;
+ console.error(`Resolved: ${absolutePath}`);
+ const markdown = await Bun.file(absolutePath).text();
// Start the annotate server (reuses plan editor HTML)
const server = await startAnnotateServer({
diff --git a/apps/opencode-plugin/index.ts b/apps/opencode-plugin/index.ts
index 0ac9a2d..949caad 100644
--- a/apps/opencode-plugin/index.ts
+++ b/apps/opencode-plugin/index.ts
@@ -28,6 +28,7 @@ import {
} from "@plannotator/server/annotate";
import { getGitContext, runGitDiff } from "@plannotator/server/git";
import { writeRemoteShareLink } from "@plannotator/server/share-url";
+import { resolveMarkdownFile } from "@plannotator/server/resolve-file";
// @ts-ignore - Bun import attribute for text
import indexHtml from "./plannotator.html" with { type: "text" };
@@ -261,20 +262,31 @@ Do NOT proceed with implementation until your plan is approved.
message: `Opening annotation UI for ${filePath}...`,
});
- // Resolve to absolute path
- const path = await import("path");
- const absolutePath = path.resolve(filePath);
+ // Smart file resolution: exact path, case-insensitive relative, or bare filename
+ const projectRoot = process.cwd();
+ const resolved = await resolveMarkdownFile(filePath, projectRoot);
- // Read the markdown file
- const file = Bun.file(absolutePath);
- if (!(await file.exists())) {
+ if (resolved.kind === "ambiguous") {
ctx.client.app.log({
level: "error",
- message: `File not found: ${absolutePath}`,
+ message: `Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:\n${resolved.matches.map((m) => ` ${m}`).join("\n")}`,
});
return;
}
- const markdown = await file.text();
+ if (resolved.kind === "not_found") {
+ ctx.client.app.log({
+ level: "error",
+ message: `File not found: ${resolved.input}`,
+ });
+ return;
+ }
+
+ const absolutePath = resolved.path;
+ ctx.client.app.log({
+ level: "info",
+ message: `Resolved: ${absolutePath}`,
+ });
+ const markdown = await Bun.file(absolutePath).text();
// Start annotate server (reuses plan editor HTML)
const server = await startAnnotateServer({
diff --git a/packages/server/package.json b/packages/server/package.json
index 14d0ee6..cab14ac 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -14,7 +14,8 @@
"./storage": "./storage.ts",
"./git": "./git.ts",
"./repo": "./repo.ts",
- "./share-url": "./share-url.ts"
+ "./share-url": "./share-url.ts",
+ "./resolve-file": "./resolve-file.ts"
},
"files": [
"*.ts"
diff --git a/packages/server/reference-handlers.ts b/packages/server/reference-handlers.ts
index cf9e2a2..f8e4fa8 100644
--- a/packages/server/reference-handlers.ts
+++ b/packages/server/reference-handlers.ts
@@ -8,6 +8,7 @@
import { existsSync, statSync } from "fs";
import { resolve } from "path";
import { detectObsidianVaults } from "./integrations";
+import { resolveMarkdownFile } from "./resolve-file";
// --- Vault file tree helpers ---
@@ -73,65 +74,22 @@ export async function handleDoc(req: Request): Promise {
}
const projectRoot = process.cwd();
+ const result = await resolveMarkdownFile(requestedPath, projectRoot);
- // Restrict to markdown files only
- if (!/\.mdx?$/i.test(requestedPath)) {
- return Response.json({ error: "Only .md and .mdx files are supported" }, { status: 400 });
+ if (result.kind === "ambiguous") {
+ return Response.json(
+ { error: `Ambiguous filename '${result.input}': found ${result.matches.length} matches`, matches: result.matches },
+ { status: 400 },
+ );
}
- // Path resolution: 3 strategies in order
- let resolvedPath: string | null = null;
-
- if (requestedPath.startsWith("/")) {
- // 1. Absolute path
- resolvedPath = requestedPath;
- } else {
- // 2. Relative to project root
- const fromRoot = resolve(projectRoot, requestedPath);
- if (await Bun.file(fromRoot).exists()) {
- resolvedPath = fromRoot;
- }
-
- // 3. Bare filename — search entire project for unique match
- if (!resolvedPath && !requestedPath.includes("/")) {
- const glob = new Bun.Glob(`**/${requestedPath}`);
- const matches: string[] = [];
- for await (const match of glob.scan({ cwd: projectRoot, onlyFiles: true })) {
- if (match.includes("node_modules/") || match.includes(".git/")) continue;
- if (match.split("/").pop() === requestedPath) {
- matches.push(resolve(projectRoot, match));
- }
- }
- if (matches.length === 1) {
- resolvedPath = matches[0];
- } else if (matches.length > 1) {
- const relativePaths = matches.map((m) => m.replace(projectRoot + "/", ""));
- return Response.json(
- { error: `Ambiguous filename '${requestedPath}': found ${matches.length} matches`, matches: relativePaths },
- { status: 400 },
- );
- }
- }
- }
-
- if (!resolvedPath) {
- return Response.json({ error: `File not found: ${requestedPath}` }, { status: 404 });
- }
-
- // Security: path must stay within projectRoot
- const normalised = resolve(resolvedPath);
- if (!normalised.startsWith(projectRoot + "/") && normalised !== projectRoot) {
- return Response.json({ error: "Access denied: path is outside project root" }, { status: 403 });
- }
-
- const file = Bun.file(normalised);
- if (!(await file.exists())) {
- return Response.json({ error: `File not found: ${requestedPath}` }, { status: 404 });
+ if (result.kind === "not_found") {
+ return Response.json({ error: `File not found: ${result.input}` }, { status: 404 });
}
try {
- const markdown = await file.text();
- return Response.json({ markdown, filepath: normalised });
+ const markdown = await Bun.file(result.path).text();
+ return Response.json({ markdown, filepath: result.path });
} catch {
return Response.json({ error: "Failed to read file" }, { status: 500 });
}
diff --git a/packages/server/resolve-file.ts b/packages/server/resolve-file.ts
new file mode 100644
index 0000000..e88946c
--- /dev/null
+++ b/packages/server/resolve-file.ts
@@ -0,0 +1,101 @@
+/**
+ * Smart markdown file resolution.
+ *
+ * Resolves a user-provided path to an absolute file path using three strategies:
+ * 1. Exact path (absolute or relative to cwd)
+ * 2. Case-insensitive relative path search within project root
+ * 3. Case-insensitive bare filename search within project root
+ *
+ * Used by both the CLI (`plannotator annotate`) and the `/api/doc` endpoint.
+ */
+
+import { resolve } from "path";
+
+const IGNORED_DIRS = [
+ "node_modules/",
+ ".git/",
+ "dist/",
+ "build/",
+ ".next/",
+ "__pycache__/",
+ ".obsidian/",
+ ".trash/",
+];
+
+export type ResolveResult =
+ | { kind: "found"; path: string }
+ | { kind: "not_found"; input: string }
+ | { kind: "ambiguous"; input: string; matches: string[] };
+
+/**
+ * Resolve a markdown file path within a project root.
+ *
+ * @param input - User-provided path (absolute, relative, or bare filename)
+ * @param projectRoot - Project root directory to search within
+ */
+export async function resolveMarkdownFile(
+ input: string,
+ projectRoot: string,
+): Promise {
+ // Restrict to markdown files
+ if (!/\.mdx?$/i.test(input)) {
+ return { kind: "not_found", input };
+ }
+
+ // 1. Absolute path — use as-is
+ if (input.startsWith("/")) {
+ const normalized = resolve(input);
+ if (!normalized.startsWith(projectRoot + "/") && normalized !== projectRoot) {
+ return { kind: "not_found", input };
+ }
+ if (await Bun.file(normalized).exists()) {
+ return { kind: "found", path: normalized };
+ }
+ return { kind: "not_found", input };
+ }
+
+ // 2. Exact relative path from project root
+ const fromRoot = resolve(projectRoot, input);
+ if (
+ fromRoot.startsWith(projectRoot + "/") &&
+ (await Bun.file(fromRoot).exists())
+ ) {
+ return { kind: "found", path: fromRoot };
+ }
+
+ // 3. Case-insensitive search
+ const inputLower = input.toLowerCase();
+ const isBareFilename = !input.includes("/");
+
+ const pattern = isBareFilename ? `**/${input}` : `${input}`;
+ const glob = new Bun.Glob(pattern);
+ const matches: string[] = [];
+
+ for await (const match of glob.scan({ cwd: projectRoot, onlyFiles: true })) {
+ if (IGNORED_DIRS.some((dir) => match.includes(dir))) continue;
+
+ const matchLower = isBareFilename
+ ? match.split("/").pop()!.toLowerCase()
+ : match.toLowerCase();
+ const targetLower = isBareFilename
+ ? inputLower.split("/").pop()!
+ : inputLower;
+
+ if (matchLower === targetLower) {
+ const full = resolve(projectRoot, match);
+ if (full.startsWith(projectRoot + "/")) {
+ matches.push(full);
+ }
+ }
+ }
+
+ if (matches.length === 1) {
+ return { kind: "found", path: matches[0] };
+ }
+ if (matches.length > 1) {
+ const relative = matches.map((m) => m.replace(projectRoot + "/", ""));
+ return { kind: "ambiguous", input, matches: relative };
+ }
+
+ return { kind: "not_found", input };
+}
--
knotmirror 0.0.1