xonecas.io
64875
Mc

mini-coder / commit 2ed8041

fix: canonicalize cwd and AGENTS path discovery

Sean2026-04-06 2ed8041eba2777f3def003517a5a337370c61402 parent df9e5a6

9 files changed

AGENTS.md+2−0
@@ -49,6 +49,8 @@
4949 - **Read the framework's key dispatch code.** cel-tui intercepts Escape at the framework level (unfocuses before `onKeyPress` fires). Use `onBlur` for dismiss-on-Escape instead of `onKeyPress`. Don't assume events reach component handlers without checking the framework's dispatch order.
5050 - **Pass all required options through the call chain.** pi-ai's `streamSimple` needs `apiKey` in options for OAuth providers (env vars aren't set). When adding a new field to a dependency's options, trace the full call path from UI → agent loop → provider to ensure it arrives.
5151 - **Display-only state must not leak into model context.** Info messages (login progress, fork confirmation) belong in a separate display array, not `state.messages`. Anything in `state.messages` gets sent to the LLM as conversation history.
52+- **Compatibility policy is a product decision.** Before 1.0, prefer correct, simple semantics over speculative backward-compatibility shims. If a change may affect existing data or behavior, raise it explicitly, but do not implement migrations or compatibility layers unless the spec or user asks for them.
53+- **Breaking changes still need to be called out.** Pre-1.0 is not a license to surprise the user. If a change intentionally trades compatibility for correctness or simplicity, say so explicitly in discussion and keep TODO/release notes aligned.
5254
5355 ## Testing strategy
5456
TODO.md+2−1
@@ -31,7 +31,7 @@
3131
3232 - [ ] `/skill:name` input handling (strip prefix, prepend skill body to user message)
3333 - [ ] Image embedding (entire input is image path → embed as `ImageContent`)
34-- [ ] Conditional `readImage` tool registration (only for vision-capable models, re-evaluated on `/model`)
34+- [x] Conditional `readImage` tool registration (only for vision-capable models, re-evaluated on `/model`)
3535 - [ ] Tab file path autocomplete in input
3636 - [ ] Context limit compaction (threshold detection, model-generated summary, prompt cache preservation)
3737
@@ -40,3 +40,4 @@
4040 - [ ] User preferences persistence (model, effort) — not in spec, currently resets to defaults on launch
4141 - [ ] Session list preview — show first user message snippet in `/session` selector
4242 - [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
43+- [ ] Backward-compatibility and migration policy for 1.0 (session/app data versioning, explicit migration strategy)
src/git.test.ts+21−5
@@ -1,8 +1,15 @@
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+import {
3+ mkdirSync,
4+ mkdtempSync,
5+ rmSync,
6+ symlinkSync,
7+ writeFileSync,
8+} from "node:fs";
39 import { tmpdir } from "node:os";
4-import { join, resolve } from "node:path";
10+import { join } from "node:path";
511 import { getGitState } from "./git.ts";
12+import { canonicalizePath } from "./paths.ts";
613
714 // ---------------------------------------------------------------------------
815 // Helpers
@@ -59,7 +66,7 @@ describe("getGitState", () => {
5966 await initRepo();
6067 const state = await getGitState(tmp);
6168 expect(state).not.toBeNull();
62- expect(state!.root).toBe(resolve(tmp));
69+ expect(state!.root).toBe(canonicalizePath(tmp));
6370 });
6471
6572 test("gets current branch name", async () => {
@@ -139,11 +146,20 @@ describe("getGitState", () => {
139146 test("works from a subdirectory", async () => {
140147 await initRepo();
141148 const sub = join(tmp, "src", "deep");
142- const { mkdirSync } = await import("node:fs");
143149 mkdirSync(sub, { recursive: true });
144150
145151 const state = await getGitState(sub);
146152 expect(state).not.toBeNull();
147- expect(state!.root).toBe(resolve(tmp));
153+ expect(state!.root).toBe(canonicalizePath(tmp));
154+ });
155+
156+ test("returns the canonical repo root when accessed through a symlink", async () => {
157+ await initRepo();
158+ mkdirSync(join(tmp, "src"), { recursive: true });
159+ symlinkSync(tmp, join(tmp, "alias"));
160+
161+ const state = await getGitState(join(tmp, "alias", "src"));
162+ expect(state).not.toBeNull();
163+ expect(state!.root).toBe(canonicalizePath(tmp));
148164 });
149165 });
src/index.ts+9−4
@@ -22,6 +22,7 @@ import { getEnvApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
2222 import { getOAuthApiKey, getOAuthProviders } from "@mariozechner/pi-ai/oauth";
2323 import type { ToolHandler } from "./agent.ts";
2424 import { type GitState, getGitState } from "./git.ts";
25+import { canonicalizePath } from "./paths.ts";
2526 import {
2627 type AgentContext,
2728 destroyPlugins,
@@ -287,8 +288,10 @@ export interface AppState {
287288 providers: Map<string, string>;
288289 /** OAuth credentials on disk. */
289290 oauthCredentials: Record<string, OAuthCredentials>;
290- /** Working directory. */
291+ /** Working directory as entered by the user/shell (for display and tool execution). */
291292 cwd: string;
293+ /** Canonical working directory (for path identity and session scoping). */
294+ canonicalCwd: string;
292295 /** Whether the agent loop is currently running. */
293296 running: boolean;
294297 /** Abort controller for the current agent run. */
@@ -306,6 +309,7 @@ export interface AppState {
306309 /** Initialize and return the full app state. */
307310 export async function init(): Promise<AppState> {
308311 const cwd = process.cwd();
312+ const canonicalCwd = canonicalizePath(cwd);
309313
310314 // Ensure data directory exists
311315 mkdirSync(DATA_DIR, { recursive: true });
@@ -324,7 +328,7 @@ export async function init(): Promise<AppState> {
324328 const home = homedir();
325329 const scanRoot = gitRoot ?? home;
326330 const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
327- const skills = discoverSkills(getSkillScanPaths(cwd, gitRoot));
331+ const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
328332
329333 // Load plugins
330334 const pluginEntries = loadPluginConfig(PLUGIN_CONFIG_PATH);
@@ -334,11 +338,11 @@ export async function init(): Promise<AppState> {
334338 const effort = DEFAULT_EFFORT;
335339 const modelLabel = model ? `${model.provider}/${model.id}` : undefined;
336340 const session = createSession(db, {
337- cwd,
341+ cwd: canonicalCwd,
338342 model: modelLabel,
339343 effort,
340344 });
341- truncateSessions(db, cwd, MAX_SESSIONS_PER_CWD);
345+ truncateSessions(db, canonicalCwd, MAX_SESSIONS_PER_CWD);
342346 const messages = loadMessages(db, session.id);
343347 const stats = computeStats(messages);
344348
@@ -373,6 +377,7 @@ export async function init(): Promise<AppState> {
373377 providers,
374378 oauthCredentials,
375379 cwd,
380+ canonicalCwd,
376381 running: false,
377382 abortController: null,
378383 showReasoning: false,
src/paths.test.ts+37−0
@@ -0,0 +1,37 @@
1+import { describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { canonicalizePath, isSamePath } from "./paths.ts";
6+
7+describe("paths", () => {
8+ test("canonicalizePath resolves symlinked directories", () => {
9+ const tmp = mkdtempSync(join(tmpdir(), "mc-paths-"));
10+
11+ try {
12+ const realDir = join(tmp, "real");
13+ const linkedDir = join(tmp, "linked");
14+ mkdirSync(realDir, { recursive: true });
15+ symlinkSync(realDir, linkedDir);
16+
17+ expect(canonicalizePath(linkedDir)).toBe(canonicalizePath(realDir));
18+ } finally {
19+ rmSync(tmp, { recursive: true, force: true });
20+ }
21+ });
22+
23+ test("isSamePath returns true for logical and canonical spellings", () => {
24+ const tmp = mkdtempSync(join(tmpdir(), "mc-paths-"));
25+
26+ try {
27+ const realDir = join(tmp, "real");
28+ const linkedDir = join(tmp, "linked");
29+ mkdirSync(realDir, { recursive: true });
30+ symlinkSync(realDir, linkedDir);
31+
32+ expect(isSamePath(realDir, linkedDir)).toBe(true);
33+ } finally {
34+ rmSync(tmp, { recursive: true, force: true });
35+ }
36+ });
37+});
src/paths.ts+37−0
@@ -0,0 +1,37 @@
1+/**
2+ * Filesystem path normalization helpers.
3+ *
4+ * Provides a small shared policy for path identity across the app:
5+ * when paths are used for comparison or persistence, we canonicalize them
6+ * to an absolute, symlink-resolved spelling.
7+ *
8+ * @module
9+ */
10+
11+import { realpathSync } from "node:fs";
12+import { resolve } from "node:path";
13+
14+/**
15+ * Return the canonical absolute path for an existing filesystem entry.
16+ *
17+ * Canonicalization resolves `.`/`..` segments and follows symlinks,
18+ * producing a stable spelling suitable for path equality checks and
19+ * persistence keys.
20+ *
21+ * @param path - An existing filesystem path.
22+ * @returns The canonical absolute path.
23+ */
24+export function canonicalizePath(path: string): string {
25+ return realpathSync(resolve(path));
26+}
27+
28+/**
29+ * Check whether two paths refer to the same existing filesystem entry.
30+ *
31+ * @param a - The first path to compare.
32+ * @param b - The second path to compare.
33+ * @returns `true` when both paths resolve to the same canonical location.
34+ */
35+export function isSamePath(a: string, b: string): boolean {
36+ return canonicalizePath(a) === canonicalizePath(b);
37+}
src/prompt.test.ts+50−3
@@ -1,8 +1,15 @@
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+import {
3+ mkdirSync,
4+ mkdtempSync,
5+ rmSync,
6+ symlinkSync,
7+ writeFileSync,
8+} from "node:fs";
39 import { tmpdir } from "node:os";
410 import { join, resolve } from "node:path";
511 import type { GitState } from "./git.ts";
12+import { canonicalizePath } from "./paths.ts";
613 import {
714 buildSystemPrompt,
815 discoverAgentsMd,
@@ -40,9 +47,11 @@ describe("discoverAgentsMd", () => {
4047
4148 // Should be ordered root-to-leaf
4249 expect(files).toHaveLength(2);
43- expect(files[0]!.path).toBe(join(tmp, "AGENTS.md"));
50+ expect(files[0]!.path).toBe(canonicalizePath(join(tmp, "AGENTS.md")));
4451 expect(files[0]!.content).toBe("Root instructions");
45- expect(files[1]!.path).toBe(join(tmp, "src", "AGENTS.md"));
52+ expect(files[1]!.path).toBe(
53+ canonicalizePath(join(tmp, "src", "AGENTS.md")),
54+ );
4655 expect(files[1]!.content).toBe("Src instructions");
4756 });
4857
@@ -95,6 +104,44 @@ describe("discoverAgentsMd", () => {
95104 expect(files[1]!.content).toBe("level-1");
96105 expect(files[2]!.content).toBe("level-2");
97106 });
107+
108+ test("does not walk above the scan root when cwd uses a symlinked path", () => {
109+ const project = join(tmp, "project");
110+ const linkedProject = join(tmp, "linked-project");
111+ const child = join(linkedProject, "src");
112+
113+ mkdirSync(join(project, "src"), { recursive: true });
114+ symlinkSync(project, linkedProject);
115+
116+ writeFileSync(join(tmp, "AGENTS.md"), "Above root");
117+ writeFileSync(join(project, "AGENTS.md"), "At root");
118+
119+ const files = discoverAgentsMd(child, canonicalizePath(project));
120+ expect(files).toHaveLength(1);
121+ expect(files[0]!.content).toBe("At root");
122+ });
123+
124+ test("includes intermediate AGENTS.md files from the canonical parent chain", () => {
125+ const home = join(tmp, "home");
126+ const work = join(home, "work");
127+ const project = join(work, "project");
128+ const linkedProject = join(tmp, "project-link");
129+ const child = join(linkedProject, "src");
130+
131+ mkdirSync(join(project, "src"), { recursive: true });
132+ symlinkSync(project, linkedProject);
133+
134+ writeFileSync(join(home, "AGENTS.md"), "Home instructions");
135+ writeFileSync(join(work, "AGENTS.md"), "Work instructions");
136+ writeFileSync(join(project, "AGENTS.md"), "Project instructions");
137+
138+ const files = discoverAgentsMd(child, home);
139+ expect(files.map((file) => file.content)).toEqual([
140+ "Home instructions",
141+ "Work instructions",
142+ "Project instructions",
143+ ]);
144+ });
98145 });
99146
100147 // ---------------------------------------------------------------------------
src/prompt.ts+5−4
@@ -9,8 +9,9 @@
99 */
1010
1111 import { existsSync, readFileSync } from "node:fs";
12-import { dirname, join, resolve } from "node:path";
12+import { dirname, join } from "node:path";
1313 import type { GitState } from "./git.ts";
14+import { canonicalizePath } from "./paths.ts";
1415 import { buildSkillCatalog, type Skill } from "./skills.ts";
1516
1617 // ---------------------------------------------------------------------------
@@ -65,10 +66,10 @@ export function discoverAgentsMd(
6566 scanRoot: string,
6667 globalAgentsDir?: string,
6768 ): AgentsMdFile[] {
68- const root = resolve(scanRoot);
69- const start = resolve(cwd);
69+ const root = canonicalizePath(scanRoot);
70+ const start = canonicalizePath(cwd);
7071
71- // Collect directories from scanRoot to cwd
72+ // Collect canonical directories from scanRoot to cwd
7273 const dirs: string[] = [];
7374 let current = start;
7475 while (true) {
src/ui.ts+2−2
@@ -758,7 +758,7 @@ function handleEffortCommand(state: AppState): void {
758758
759759 /** Handle the /session command: list and resume sessions. */
760760 function handleSessionCommand(state: AppState): void {
761- const sessions = listSessions(state.db, state.cwd);
761+ const sessions = listSessions(state.db, state.canonicalCwd);
762762 if (sessions.length === 0) {
763763 return;
764764 }
@@ -847,7 +847,7 @@ function handleNewCommand(state: AppState): void {
847847 ? `${state.model.provider}/${state.model.id}`
848848 : undefined;
849849 state.session = createSession(state.db, {
850- cwd: state.cwd,
850+ cwd: state.canonicalCwd,
851851 model: modelLabel,
852852 effort: state.effort,
853853 });