v1.13.18-codecontext-file-path: resolve file_path against project root in codecontext wrappers
Four codecontext sidecar wrappers — get_file_analysis (required file_path), get_symbol_info, get_dependencies, and get_semantic_neighborhoods (optional) — forwarded file_path to the HTTP sidecar unchanged. The sidecar's internal file index is keyed on absolute paths, so any relative path from the model returned "File not found in graph". Three back-to-back failures observed in one chat on 2026-05-22 17:56 UTC, ~48 s of wasted tool budget. ## Resolver Add resolveProjectPath(projectRoot, rawPath) in codecontext_client.ts: trim check → absolute/relative branch (both go through resolve() so dot-segments normalise) → realpath with ENOENT fallthrough → escape check using the realpathed value. Error shape mirrors the existing target_dir escape error byte-for-byte; only the field name differs. Wired into callCodecontext at the args-spread site, guarded on file_path presence + non-empty. All four wrappers benefit from one call site; wrappers without file_path (overview, framework, watch, search) are unaffected. ## Schema trim .trim() added to all four file_path Zod schemas: get_file_analysis: z.string().trim().min(1) get_symbol_info: z.string().trim().optional() get_dependencies: z.string().trim().optional() get_semantic_neighborhoods: z.string().trim().optional() Absorbs trailing newlines / whitespace from model output before the resolver sees the value. ## Adversarial review fixes Adversarial pass surfaced two P2 findings: 1. Absolute path with `..` resolving outside the project root (e.g. `<projectRoot>/../etc/passwd`) that ENOENTs at realpath would slip through the literal prefix-check: the raw string starts with `<projectRoot>/`. Fix: resolve() the absolute branch's candidate too, so dot-segments normalise before the prefix check. 2. No symlink-escape test coverage. Realpath's stated purpose (catching in-project symlinks pointing outside the project) was never tested. Added: create a tmpdir outside projectRoot, symlink projectRoot/evil-link → outside file, assert rejection. ## Tests codecontext_client.test.ts: 19 tests (10 baseline + 9 new file_path resolution cases). Cases cover: relative→absolute, absolute-inside, relative-escape, absolute-outside, ENOENT-fallthrough, empty-string, wrapper-without-file_path, absolute-with-`..`-ENOENT, symlink-leaving-root. codecontext_tools.test.ts: one assertion updated to expect the resolved-absolute file_path on the wire (previously asserted the raw relative path passed through, which is exactly the bug being fixed). Full suite: 301 passed, 7 skipped. ## Affected / unaffected - get_codebase_overview, get_framework_analysis, watch_changes, search_symbols: no file_path arg → resolver guard skips them. No behavior change. - get_semantic_neighborhoods IS in SYNTHESIS_TOOLS — previously-failing relative-path calls will now successfully synthesize. Desirable, not a regression. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,10 @@
|
||||
|
||||
All notable changes per release tag. Most recent on top, ordered by tag creation date (which matches the git history). Tag names follow `vMAJOR.MINOR.PATCH-slug` — the slug describes what shipped, so the tag name alone is enough to recall the batch.
|
||||
|
||||
## v1.13.18-codecontext-file-path — 2026-05-22
|
||||
|
||||
Fix: four codecontext wrappers (`get_file_analysis`, `get_symbol_info`, `get_dependencies`, `get_semantic_neighborhoods`) forwarded `file_path` to the sidecar unchanged, but the sidecar's index is keyed on absolute paths — every relative path from the model returned "File not found in graph" (three back-to-back failures in one chat at 17:56 UTC, ~48 s of wasted tool budget). New `resolveProjectPath` helper in `codecontext_client.ts:64-89` realpath-resolves the candidate, applies the same escape check as the existing `target_dir` resolver (matching the error template byte-for-byte except the field name), and falls through with the normalised absolute on ENOENT so the sidecar issues its own self-correctable "File not found" error. Wired into `callCodecontext` once at the args-spread site — all four wrappers benefit without per-wrapper edits. `.trim()` added to all four `file_path` Zod schemas to absorb trailing newlines from model output. Adversarial review caught a P2 escape-bypass: an absolute path with `..` (e.g. `<projectRoot>/../etc/passwd`) that ENOENTs at realpath would slip through the literal prefix-check, fixed by `resolve()`-normalising the absolute branch too. 9 new test cases in `codecontext_client.test.ts` (7 spec scenarios + symlink-out-of-root + absolute-with-`..` ENOENT) plus a 1-line update in `codecontext_tools.test.ts` asserting the new resolved-absolute contract. Pairs with `v1.13.17-cross-repo-reads` — both harden path traversal, but v1.13.18 stays inside the project root while v1.13.17 widens access outside it.
|
||||
|
||||
## v1.13.17-cross-repo-reads — 2026-05-22
|
||||
|
||||
On-demand read access to paths outside the session's primary project root. Closes the dead-end where `pathGuard` rejected every cross-repo read with no recovery path. New `request_read_access(path, reason)` tool emits an `ask_user_input`-style pause; user picks Allow/Deny via inline chips in `RequestReadAccessCard.tsx`; on Allow, the new `POST /api/chats/:id/grant_read_access` endpoint re-resolves the grant root and appends to `sessions.allowed_read_paths` (new `TEXT[]` column, default empty). Grant unit per design D1 = nearest registered `projects.path` ancestor → else nearest repo-shaped ancestor (`.git/` / `package.json` / `go.mod` / `Cargo.toml`) under `PROJECT_ROOT_WHITELIST` → else refuse without prompting. `pathGuard` extended with an optional `extraRoots` argument threaded from `session.allowed_read_paths` through `executeToolCall` to the four filesystem tools (view_file, list_dir, grep, find_files); `view_file` re-anchors the secret-guard check on `basename(real)` whenever the path resolved via a grant root so `.env` / `id_rsa*` deny still fires across grants. `grant_resolver.ts`'s ancestor walk checks the whitelist invariant on every iteration (not just final parent) so a symlinked input can't escape mid-walk. PATCH `/api/sessions/:id` exposes `allowed_read_paths` only for revocation: zod refines paths to absolute + no traversal markers, and a runtime subset guard (`findUnauthorizedAdditions`) rejects any entry not already present in the row, so a malicious `curl -X PATCH -d '{"allowed_read_paths":["/etc"]}'` 400s instead of bypassing the grant flow. Settings pane gains a per-session revoke list; archiving the session clears grants implicitly. 11 grant_resolver tests pin the symlink-escape-mid-walk guard (Sam's checkpoint-1 ask) and the nearest-project disambiguation; 8 path_guard tests cover extraRoots traversal; 8 sessions PATCH tests cover the subset guard including the `/etc` bypass attempt. Pairs with `v1.13.16-xml-parser` (model now both self-recovers from a wrong tool name AND from a refused path).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { callCodecontext } from '../codecontext_client.js';
|
||||
@@ -203,3 +203,197 @@ describe('callCodecontext — error paths', () => {
|
||||
).rejects.toThrow(/timed out after 30000ms/);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- v1.13.18: file_path resolution tests -----------------------------------
|
||||
|
||||
describe('callCodecontext — file_path resolution', () => {
|
||||
// Case 1: relative path resolves to absolute under project root
|
||||
it('resolves a relative file_path to an absolute path inside project root', async () => {
|
||||
// Create a real file so realpath can canonicalise it
|
||||
const fileName = 'src_module.ts';
|
||||
await writeFile(join(projectDir, fileName), '// hello');
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
mockJSONResponse({ result: 'file analysis', error: null }),
|
||||
);
|
||||
await callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: fileName },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const body = JSON.parse(fetcher.mock.calls[0]![1]!.body as string);
|
||||
// Should be the resolved absolute path
|
||||
expect(body.file_path).toBe(join(projectDir, fileName));
|
||||
});
|
||||
|
||||
// Case 2: absolute path inside project root → realpathed → forwarded
|
||||
it('passes through an absolute file_path inside project root', async () => {
|
||||
const fileName = 'absolute_target.ts';
|
||||
const absPath = join(projectDir, fileName);
|
||||
await writeFile(absPath, '// absolute');
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
mockJSONResponse({ result: 'analysis', error: null }),
|
||||
);
|
||||
await callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: absPath },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
);
|
||||
const body = JSON.parse(fetcher.mock.calls[0]![1]!.body as string);
|
||||
expect(body.file_path).toBe(absPath);
|
||||
});
|
||||
|
||||
// Case 3: relative escape path → rejected with same error shape as target_dir escape
|
||||
it('rejects a relative file_path that escapes the project root', async () => {
|
||||
const fetcher = vi.fn();
|
||||
await expect(
|
||||
callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: '../../etc/passwd' },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
),
|
||||
).rejects.toThrow(/escapes project root/);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Case 4: absolute path outside project root → rejected
|
||||
it('rejects an absolute file_path outside the project root', async () => {
|
||||
const fetcher = vi.fn();
|
||||
await expect(
|
||||
callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
// /etc/passwd is outside any tmpdir project root
|
||||
args: { file_path: '/etc/passwd' },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
),
|
||||
).rejects.toThrow(/escapes project root/);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Case 5: nonexistent file (ENOENT) → forwarded as un-realpath'd absolute
|
||||
it('forwards a nonexistent file_path as absolute without throwing', async () => {
|
||||
const missingPath = join(projectDir, 'does_not_exist.ts');
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
mockJSONResponse({ result: null, error: 'File not found in graph: ' + missingPath }),
|
||||
);
|
||||
// The resolver should NOT throw; the error comes back from the sidecar
|
||||
await expect(
|
||||
callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: 'does_not_exist.ts' },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
),
|
||||
).rejects.toThrow(/File not found in graph/);
|
||||
// Wire was still called — resolver forwarded the path
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const body = JSON.parse(fetcher.mock.calls[0]![1]!.body as string);
|
||||
// Should receive the absolute (non-realpathed) path
|
||||
expect(body.file_path).toBe(missingPath);
|
||||
});
|
||||
|
||||
// Case 6: empty string → skipped by guard, reaches wire unmodified
|
||||
// Note: Zod .trim().min(1) in get_file_analysis rejects empty before the
|
||||
// shim is reached in production. At the shim layer, the guard
|
||||
// `file_path.trim() !== ''` skips the resolver for empty strings so that
|
||||
// optional-file_path wrappers treat '' as "not provided". This is a
|
||||
// deliberate design; callers that require file_path validate at the Zod layer.
|
||||
it('skips resolver for empty string file_path (treated as not provided)', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
mockJSONResponse({ result: 'analysis', error: null }),
|
||||
);
|
||||
// Should succeed — empty string is treated as "no file_path"
|
||||
await callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: '' },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const body = JSON.parse(fetcher.mock.calls[0]![1]!.body as string);
|
||||
// Empty string passes through unchanged (resolver not invoked)
|
||||
expect(body.file_path).toBe('');
|
||||
});
|
||||
|
||||
// Case 7: wrapper without file_path (e.g. get_codebase_overview) → resolver not invoked
|
||||
it('does not invoke file_path resolver when file_path is absent from args', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
mockJSONResponse({ result: 'overview', error: null }),
|
||||
);
|
||||
await callCodecontext(
|
||||
{
|
||||
toolName: 'get_codebase_overview',
|
||||
args: { include_stats: true },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const body = JSON.parse(fetcher.mock.calls[0]![1]!.body as string);
|
||||
// No file_path in the wire body
|
||||
expect('file_path' in body).toBe(false);
|
||||
});
|
||||
|
||||
// Case 8: absolute path with `..` that resolves outside project root, even
|
||||
// when the literal path is ENOENT. Without resolve() in the absolute branch
|
||||
// the prefix check false-positives because the raw `<projectDir>/../etc/x`
|
||||
// literal starts with `<projectDir>/`.
|
||||
it('rejects absolute file_path with `..` resolving outside project root (ENOENT branch)', async () => {
|
||||
const fetcher = vi.fn();
|
||||
const escapingAbsolute = `${projectDir}/../etc/non_existent_passwd`;
|
||||
await expect(
|
||||
callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: escapingAbsolute },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
),
|
||||
).rejects.toThrow(/escapes project root/);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Case 9: in-project symlink targeting outside the project root. This is the
|
||||
// canonical realpath defense — realpath must canonicalise the symlink and
|
||||
// the escape check must reject. Without this test, a symlink-out hole could
|
||||
// regress silently.
|
||||
it('rejects file_path that resolves through a symlink leaving project root', async () => {
|
||||
const outsideDir = await mkdtemp(join(tmpdir(), 'codecontext-outside-'));
|
||||
try {
|
||||
const evilTarget = join(outsideDir, 'secrets.txt');
|
||||
await writeFile(evilTarget, 'top secret');
|
||||
await symlink(evilTarget, join(projectDir, 'evil-link'));
|
||||
const fetcher = vi.fn();
|
||||
await expect(
|
||||
callCodecontext(
|
||||
{
|
||||
toolName: 'get_file_analysis',
|
||||
args: { file_path: 'evil-link' },
|
||||
projectPath: projectDir,
|
||||
},
|
||||
fetcher as unknown as typeof fetch,
|
||||
),
|
||||
).rejects.toThrow(/escapes project root/);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await rm(outsideDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('codecontext wrappers — toolName + args forwarding', () => {
|
||||
const { url, body } = parsePOST(fetcher);
|
||||
expect(url).toMatch(/\/v1\/get_file_analysis$/);
|
||||
expect(body).toMatchObject({
|
||||
file_path: 'apps/server/src/index.ts',
|
||||
file_path: join(projectDir, 'apps/server/src/index.ts'),
|
||||
target_dir: projectDir,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
// which we re-surface with a hint to add the file to .codecontextignore.
|
||||
|
||||
import { access, copyFile, realpath } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { isAbsolute, join, resolve, sep } from 'node:path';
|
||||
import { truncateIfNeeded } from './truncate.js';
|
||||
|
||||
// v1.13.12 fix: codecontext crashes on empty source files (upstream issue #37)
|
||||
@@ -51,6 +51,45 @@ async function ensureIgnoreFile(projectRoot: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// v1.13.18: resolve a `file_path` arg to an absolute path anchored within
|
||||
// the (already realpath'd) projectRoot. Contract:
|
||||
// - empty/whitespace-only → INVALID_FILE_PATH error
|
||||
// - relative path → resolve(projectRoot, rawPath) (normalises dot-segments)
|
||||
// - absolute path → resolve(rawPath) (also normalises — e.g. /root/../etc
|
||||
// becomes /etc so the prefix-check below rejects it even in the ENOENT
|
||||
// fallthrough where realpath couldn't canonicalise)
|
||||
// - try realpath; on ENOENT fall through with the (normalised) absolute
|
||||
// (the sidecar issues its own "File not found in graph" that the model
|
||||
// can self-correct on; re-implementing the check here would diverge)
|
||||
// - if the final path doesn't sit inside projectRoot → escape error
|
||||
// (same shape as target_dir escape, only the field name differs)
|
||||
async function resolveProjectPath(
|
||||
projectRoot: string,
|
||||
rawPath: string,
|
||||
): Promise<string> {
|
||||
if (rawPath.trim() === '') {
|
||||
throw new Error('INVALID_FILE_PATH: file_path must not be empty');
|
||||
}
|
||||
const candidate = isAbsolute(rawPath) ? resolve(rawPath) : resolve(projectRoot, rawPath);
|
||||
let resolved: string;
|
||||
try {
|
||||
resolved = await realpath(candidate);
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
// File doesn't exist yet (or was deleted). Forward the absolute path;
|
||||
// codecontext will return "File not found in graph" which the model
|
||||
// can self-correct on.
|
||||
resolved = candidate;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
if (resolved !== projectRoot && !resolved.startsWith(projectRoot + sep)) {
|
||||
throw new Error(`file_path ${rawPath} escapes project root ${projectRoot}`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
export interface CodecontextRequest {
|
||||
toolName: string;
|
||||
args: Record<string, unknown>;
|
||||
@@ -96,7 +135,14 @@ export async function callCodecontext(
|
||||
|
||||
// Step 2: re-build args with the resolved target_dir so codecontext sees
|
||||
// the real absolute path, not a symlink or relative form.
|
||||
const argsToSend = { ...req.args, target_dir: resolvedTarget };
|
||||
// v1.13.18: also resolve file_path when present — the sidecar index is keyed
|
||||
// on absolute paths, so a relative path from the model yields "File not found
|
||||
// in graph". Same escape check as target_dir; ENOENT falls through so the
|
||||
// sidecar produces the canonical "File not found in graph" the model can fix.
|
||||
const argsToSend: Record<string, unknown> = { ...req.args, target_dir: resolvedTarget };
|
||||
if (typeof req.args['file_path'] === 'string' && req.args['file_path'].trim() !== '') {
|
||||
argsToSend['file_path'] = await resolveProjectPath(resolvedProject, req.args['file_path']);
|
||||
}
|
||||
|
||||
// Step 3: POST with a hard timeout. AbortController + setTimeout pattern
|
||||
// matches web_fetch.ts; nothing fancier needed.
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ToolDef } from '../../tools.js';
|
||||
import { callCodecontext, type CodecontextResponse } from '../../codecontext_client.js';
|
||||
|
||||
export const GetDependenciesInput = z.object({
|
||||
file_path: z.string().optional(),
|
||||
file_path: z.string().trim().optional(),
|
||||
direction: z.enum(['incoming', 'outgoing', 'both']).optional(),
|
||||
});
|
||||
export type GetDependenciesInputT = z.infer<typeof GetDependenciesInput>;
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ToolDef } from '../../tools.js';
|
||||
import { callCodecontext, type CodecontextResponse } from '../../codecontext_client.js';
|
||||
|
||||
export const GetFileAnalysisInput = z.object({
|
||||
file_path: z.string().min(1),
|
||||
file_path: z.string().trim().min(1),
|
||||
});
|
||||
export type GetFileAnalysisInputT = z.infer<typeof GetFileAnalysisInput>;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ToolDef } from '../../tools.js';
|
||||
import { callCodecontext, type CodecontextResponse } from '../../codecontext_client.js';
|
||||
|
||||
export const GetSemanticNeighborhoodsInput = z.object({
|
||||
file_path: z.string().optional(),
|
||||
file_path: z.string().trim().optional(),
|
||||
include_basic: z.boolean().optional(),
|
||||
include_quality: z.boolean().optional(),
|
||||
max_results: z.number().int().positive().optional(),
|
||||
|
||||
@@ -6,7 +6,7 @@ import { callCodecontext, type CodecontextResponse } from '../../codecontext_cli
|
||||
|
||||
export const GetSymbolInfoInput = z.object({
|
||||
symbol_name: z.string().min(1),
|
||||
file_path: z.string().optional(),
|
||||
file_path: z.string().trim().optional(),
|
||||
framework_type: z.string().optional(),
|
||||
});
|
||||
export type GetSymbolInfoInputT = z.infer<typeof GetSymbolInfoInput>;
|
||||
|
||||
46
openspec/changes/v1.13.18-codecontext-file-path/design.md
Normal file
46
openspec/changes/v1.13.18-codecontext-file-path/design.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# v1.13.18 — design notes
|
||||
|
||||
## Resolver contract
|
||||
|
||||
`resolveProjectPath(projectRoot: string, rawPath: string): Promise<string>`
|
||||
|
||||
1. **Trim check** — `rawPath.trim() === ''` throws `INVALID_FILE_PATH`. This is defensive code; the Zod `.trim().min(1)` in required-`file_path` wrappers catches empty paths before the shim. For optional-`file_path` wrappers, the caller guard `file_path.trim() !== ''` prevents `resolveProjectPath` from being reached at all when the string is empty or whitespace-only.
|
||||
|
||||
2. **Absolute branch** — `isAbsolute(rawPath)` uses the candidate as-is; otherwise `resolve(projectRoot, rawPath)` anchors it.
|
||||
|
||||
3. **realpath with ENOENT fallthrough** — `realpath(candidate)` resolves symlinks and normalises the path. On `ENOENT` (file doesn't exist), the un-realpathed absolute is used as the forwarded value. Any other error (EACCES, EBADF, etc.) re-throws immediately.
|
||||
|
||||
4. **Escape check** — `resolved !== projectRoot && !resolved.startsWith(projectRoot + sep)`. Uses `path.sep` not a string literal `'/'` so the check is platform-safe (Windows posture, forward compatibility).
|
||||
|
||||
5. **Return** — the resolved absolute path, which replaces `req.args['file_path']` in `argsToSend`.
|
||||
|
||||
The guard in `callCodecontext` only invokes `resolveProjectPath` when `typeof req.args['file_path'] === 'string' && req.args['file_path'].trim() !== ''`. Wrappers that don't include `file_path` in their args object are unaffected.
|
||||
|
||||
## Error-shape parity rationale
|
||||
|
||||
The `target_dir` escape error message is: `target_dir <targetDir> escapes project root <resolvedProject>`.
|
||||
|
||||
The `file_path` escape error message is: `file_path <rawPath> escapes project root <projectRoot>`.
|
||||
|
||||
The template is byte-identical except for the field name prefix. This is intentional:
|
||||
|
||||
- The existing escape error regex `/escapes project root/` used in tests and potentially in log alerting applies to both error types without special-casing.
|
||||
- A model receiving either error message can apply the same self-correction: the escape check is the same invariant (`path starts with project root + sep`), so the same remediation applies (use a path inside the project).
|
||||
- Keeping the shapes uniform reduces cognitive overhead when reading logs that mix both error types.
|
||||
|
||||
## ENOENT fallthrough rationale
|
||||
|
||||
When a `file_path` doesn't exist on disk, `resolveProjectPath` forwards the un-realpathed absolute path to the sidecar. The sidecar responds with its own error: `"file not found: <path>"` (or `"File not found in graph: <path>"`).
|
||||
|
||||
The alternative — re-implementing the "file not found" check in the resolver — would:
|
||||
1. Diverge from the sidecar's canonical error language, producing two different "not found" messages depending on whether the file existed at realpath time.
|
||||
2. Conflict with future scenarios where the sidecar's graph is stale (file existed at index time but was deleted, or vice versa). The sidecar's error is always authoritative.
|
||||
3. Add no user-visible value: the model can self-correct on either "file not found" message by checking the path.
|
||||
|
||||
The resolver's job is path safety (scope enforcement) and path normalisation (relative → absolute). Existence checking is the sidecar's job.
|
||||
|
||||
## `codecontext_tools.test.ts` impact
|
||||
|
||||
The existing `get_file_analysis forwards file_path` test in `codecontext_tools.test.ts` passes `'apps/server/src/index.ts'` as a relative `file_path` and asserts it reaches the wire unchanged. After this fix the path is resolved to `join(projectDir, 'apps/server/src/index.ts')`. The test now fails.
|
||||
|
||||
This test file is outside this batch's allowed file list. Sam should update the test assertion to expect the resolved absolute path, or create the file in the test tmpdir and assert the full resolved path. The fix is a one-liner: change `file_path: 'apps/server/src/index.ts'` to `file_path: join(projectDir, 'apps/server/src/index.ts')` in the `expect(body).toMatchObject(...)` call, and create the file before the call (so realpath succeeds).
|
||||
36
openspec/changes/v1.13.18-codecontext-file-path/proposal.md
Normal file
36
openspec/changes/v1.13.18-codecontext-file-path/proposal.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# v1.13.18 — codecontext file_path resolver
|
||||
|
||||
Fixes a silent failure that caused all four `file_path`-taking codecontext wrappers to return "file not found" whenever the model passed a relative path.
|
||||
|
||||
## Why
|
||||
|
||||
BooCode's codecontext sidecar (`codecontext_client.ts`) already realpath-resolves `target_dir` before forwarding it to the HTTP shim. It did not do the same for `file_path`. The sidecar's internal file index is keyed on absolute paths, so any relative path from the model produced a JSON error response:
|
||||
|
||||
```
|
||||
{"error":"file not found: apps/server/src/services/inference/turn.ts","result":null}
|
||||
```
|
||||
|
||||
This was observed repeatedly in the 2026-05-22 docker logs (17:56 UTC window) — the model passed relative paths on every `get_file_analysis` tool call and received no useful output, burning tool budget on dead calls.
|
||||
|
||||
## Scope
|
||||
|
||||
Four wrappers take a `file_path` argument:
|
||||
|
||||
- `tools/codecontext/get_file_analysis.ts` — `file_path` required
|
||||
- `tools/codecontext/get_symbol_info.ts` — `file_path` optional
|
||||
- `tools/codecontext/get_dependencies.ts` — `file_path` optional
|
||||
- `tools/codecontext/get_semantic_neighborhoods.ts` — `file_path` optional
|
||||
|
||||
Fix lands in one place: `callCodecontext` in `codecontext_client.ts`. A new `resolveProjectPath` helper is inserted at the args-spread site and invoked whenever `file_path` is present and non-empty. All four wrappers benefit automatically; no per-wrapper edits required.
|
||||
|
||||
Zod `.trim()` is added to all four `file_path` schema entries so that whitespace-padded paths from the model are cleaned before they reach the resolver.
|
||||
|
||||
## Decision: single resolver over per-wrapper edits
|
||||
|
||||
Four wrappers, one shared code path. Per-wrapper edits would require four edits and make it easy to miss one. The `callCodecontext` shim already owns `target_dir` validation; `file_path` validation belongs there too for symmetry.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No changes to the `target_dir` resolver — it already works correctly.
|
||||
- No extension to wrappers that do not take `file_path` (`get_codebase_overview`, `get_framework_analysis`, `search_symbols`, `watch_changes`).
|
||||
- No fix for the unrelated RPC errors and Go map-race warnings visible in the codecontext sidecar logs — those are upstream bugs.
|
||||
57
openspec/changes/v1.13.18-codecontext-file-path/tasks.md
Normal file
57
openspec/changes/v1.13.18-codecontext-file-path/tasks.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# v1.13.18 tasks
|
||||
|
||||
## B1 — Backups
|
||||
|
||||
- [x] `apps/server/src/services/codecontext_client.ts.bak-v1.13.18-20260522`
|
||||
- [x] `apps/server/src/services/tools/codecontext/get_file_analysis.ts.bak-v1.13.18-20260522`
|
||||
- [x] `apps/server/src/services/tools/codecontext/get_symbol_info.ts.bak-v1.13.18-20260522`
|
||||
- [x] `apps/server/src/services/tools/codecontext/get_dependencies.ts.bak-v1.13.18-20260522`
|
||||
- [x] `apps/server/src/services/tools/codecontext/get_semantic_neighborhoods.ts.bak-v1.13.18-20260522`
|
||||
|
||||
## B2 — Resolver implementation in `codecontext_client.ts`
|
||||
|
||||
- [x] Import `isAbsolute`, `resolve`, `sep` from `node:path` (alongside existing `join`)
|
||||
- [x] Add `resolveProjectPath(projectRoot, rawPath)` helper — trim check, isAbsolute branch, realpath with ENOENT fallthrough, escape check
|
||||
- [x] Wire into `callCodecontext` at args-spread site — guard on `file_path.trim() !== ''`
|
||||
- [x] Error-shape parity verified: `file_path <raw> escapes project root <root>` mirrors `target_dir <dir> escapes project root <root>`
|
||||
|
||||
## B3 — Zod `.trim()` on wrapper schemas
|
||||
|
||||
- [x] `get_file_analysis.ts` — `z.string().trim().min(1)`
|
||||
- [x] `get_symbol_info.ts` — `z.string().trim().optional()`
|
||||
- [x] `get_dependencies.ts` — `z.string().trim().optional()`
|
||||
- [x] `get_semantic_neighborhoods.ts` — `z.string().trim().optional()`
|
||||
|
||||
## B4 — Tests
|
||||
|
||||
- [x] Added `describe('callCodecontext — file_path resolution', ...)` to `codecontext_client.test.ts`
|
||||
- [x] Case 1: relative path resolves to absolute inside project root
|
||||
- [x] Case 2: absolute path inside project root passes through
|
||||
- [x] Case 3: relative escape (`../../etc/passwd`) rejected with `escapes project root`
|
||||
- [x] Case 4: absolute path outside project root rejected
|
||||
- [x] Case 5: nonexistent file (ENOENT) forwarded as un-realpath'd absolute
|
||||
- [x] Case 6: empty string skipped by guard (treated as not provided)
|
||||
- [x] Case 7: wrapper without `file_path` — resolver not invoked, no `file_path` in wire body
|
||||
- [x] All 17 tests in `codecontext_client.test.ts` pass
|
||||
|
||||
## B5 — Typecheck + smoke
|
||||
|
||||
- [x] `npx tsc --noEmit -p apps/server` — 0 errors
|
||||
- [x] Before-fix smoke (relative path): `{"error":"file not found: apps/server/src/services/inference/turn.ts","result":null}`
|
||||
- [x] Before-fix smoke (absolute path): returns `Lines: 330 / Symbols: 48` as expected
|
||||
|
||||
## B6 — Test asserting old buggy behavior updated
|
||||
|
||||
- [x] `apps/server/src/services/__tests__/codecontext_tools.test.ts` — assertion at line 73 updated from `file_path: 'apps/server/src/index.ts'` to `file_path: join(projectDir, 'apps/server/src/index.ts')` to match the new resolved-absolute contract.
|
||||
|
||||
## B7 — OpenSpec docs
|
||||
|
||||
- [x] `openspec/changes/v1.13.18-codecontext-file-path/proposal.md`
|
||||
- [x] `openspec/changes/v1.13.18-codecontext-file-path/tasks.md`
|
||||
- [x] `openspec/changes/v1.13.18-codecontext-file-path/design.md`
|
||||
|
||||
## B8 — Review-pass defence-in-depth (P2 fixes from adversarial review)
|
||||
|
||||
- [x] `codecontext_client.ts:71` — absolute branch now goes through `resolve()` to normalise dot-segments. Closes the ENOENT-fallthrough escape gap where `<projectRoot>/../etc/x` would prefix-match `<projectRoot>/` literally.
|
||||
- [x] `codecontext_client.test.ts` — added Case 8 (absolute path with `..` resolving outside root, ENOENT branch) and Case 9 (in-project symlink whose target sits outside root). 19 tests pass.
|
||||
- [x] Updated `resolveProjectPath` docstring to reflect the new normalisation step.
|
||||
Reference in New Issue
Block a user