Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve-code): let grep and apply_patch work outside /workspace and git checkouts (#3975)

Rui47f1f180863c
diff --git a/.changeset/eve-code-workspace-roots.md b/.changeset/eve-code-workspace-roots.md
new file mode 100644
index 000000000..c4b9d6237
--- /dev/null
+++ b/.changeset/eve-code-workspace-roots.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`grep` and `apply_patch` in `eve/extensions/code` now work in sandboxes whose workspace is not `/workspace`, such as `/app`. `apply_patch` no longer requires a git checkout: `root` is optional and defaults to the workspace root, and outside git it still reports whitespace problems the patch introduced. It also accepts unified-diff range headers such as `@@ -118,8 +118,8 @@ def second():`, using the function context to pick between identical blocks.
diff --git a/packages/eve-code/extension/lib/diagnostics.ts b/packages/eve-code/extension/lib/diagnostics.ts
index 67a483ecf..768bef305 100644
--- a/packages/eve-code/extension/lib/diagnostics.ts
+++ b/packages/eve-code/extension/lib/diagnostics.ts
@@ -23,21 +23,32 @@ export async function runPostEditDiagnostics(input: {
readonly addedPaths?: readonly string[];
readonly changedPaths: readonly string[];
readonly deletedPaths: readonly string[];
- readonly repoRoot: string;
+ readonly patchRoot: string;
+ /** Content each written path had before the patch; null or absent for new files. */
+ readonly previousContents?: ReadonlyMap<string, string | null>;
readonly sandbox: DiagnosticsSandbox;
}): Promise<PostEditDiagnostic[]> {
const allPaths = [...new Set([...input.changedPaths, ...input.deletedPaths])];
const diagnostics: PostEditDiagnostic[] = [];
+ let inWorkTree = false;
if (allPaths.length > 0) {
try {
- const result = await input.sandbox.run({
- command: `git -C ${shellQuote(input.repoRoot)} diff --check -- ${allPaths.map(shellQuote).join(" ")}`,
+ const root = shellQuote(input.patchRoot);
+ const probe = await input.sandbox.run({
+ command: `git -C ${root} rev-parse --is-inside-work-tree`,
});
- if (result.exitCode !== 0) {
- diagnostics.push({
- check: "git-diff",
- message: boundedDiagnostic(result.stderr || result.stdout || "git diff --check failed"),
+ // Exit 0 with "false" means a .git directory or a bare repository.
+ inWorkTree = probe.exitCode === 0 && probe.stdout.trim() === "true";
+ if (inWorkTree) {
+ const result = await input.sandbox.run({
+ command: `git -C ${root} diff --check -- ${allPaths.map(shellQuote).join(" ")}`,
});
+ if (result.exitCode !== 0) {
+ diagnostics.push({
+ check: "git-diff",
+ message: boundedDiagnostic(result.stderr || result.stdout || "git diff --check failed"),
+ });
+ }
}
} catch (error) {
diagnostics.push({
@@ -47,11 +58,14 @@ export async function runPostEditDiagnostics(input: {
}
}
- for (const path of input.addedPaths ?? []) {
+ // git diff --check covers edits to tracked files; without it, check every
+ // written file so updates to existing files are not skipped.
+ const whitespacePaths = inWorkTree ? (input.addedPaths ?? []) : input.changedPaths;
+ for (const path of whitespacePaths) {
try {
- const content = await input.sandbox.readTextFile({ path: `${input.repoRoot}/${path}` });
+ const content = await input.sandbox.readTextFile({ path: `${input.patchRoot}/${path}` });
if (content === null) continue;
- const issues = whitespaceIssues(content);
+ const issues = whitespaceIssues(content, input.previousContents?.get(path));
if (issues.length > 0) {
diagnostics.push({ check: "whitespace", path, message: issues.join("\n") });
}
@@ -59,7 +73,7 @@ export async function runPostEditDiagnostics(input: {
diagnostics.push({
check: "whitespace",
path,
- message: `Could not inspect added file: ${errorMessage(error)}`,
+ message: `Could not inspect written file: ${errorMessage(error)}`,
});
}
}
@@ -67,7 +81,7 @@ export async function runPostEditDiagnostics(input: {
for (let index = 0; index < input.changedPaths.length; index += 8) {
const syntaxResults = await Promise.all(
input.changedPaths.slice(index, index + 8).map(async (path) => {
- const command = syntaxCommand(input.repoRoot, path);
+ const command = syntaxCommand(input.patchRoot, path);
if (command === null) return null;
try {
const result = await input.sandbox.run({ command });
@@ -91,7 +105,7 @@ export async function runPostEditDiagnostics(input: {
diagnostics.push(
...(await runTypeScriptDiagnostics({
paths: input.changedPaths,
- repoRoot: input.repoRoot,
+ patchRoot: input.patchRoot,
sandbox: input.sandbox,
})),
);
@@ -105,7 +119,7 @@ export async function runPostEditDiagnostics(input: {
*/
export async function runTypeScriptDiagnostics(input: {
readonly paths: readonly string[];
- readonly repoRoot: string;
+ readonly patchRoot: string;
readonly sandbox: DiagnosticsSandbox;
}): Promise<PostEditDiagnostic[]> {
const typePaths = input.paths.filter(isTypeScriptPath);
@@ -120,7 +134,7 @@ export async function runTypeScriptDiagnostics(input: {
const request = Buffer.from(
JSON.stringify({
filePath: path,
- repoRoot: input.repoRoot,
+ patchRoot: input.patchRoot,
typescriptPath: tooling.typescriptModule,
}),
"utf8",
@@ -197,8 +211,8 @@ function isTypeScriptPath(path: string): boolean {
return /\.(?:cts|mts|ts|tsx)$/u.test(path);
}
-function syntaxCommand(repoRoot: string, path: string): string | null {
- const quoted = shellQuote(`${repoRoot}/${path}`);
+function syntaxCommand(patchRoot: string, path: string): string | null {
+ const quoted = shellQuote(`${patchRoot}/${path}`);
switch (extname(path).toLowerCase()) {
case ".cjs":
case ".js":
@@ -231,9 +245,13 @@ function boundedDiagnostic(value: string): string {
return omitted > 0 ? `[${omitted} earlier lines omitted]\n${kept.join("\n")}` : kept.join("\n");
}
-function whitespaceIssues(content: string): string[] {
+// A line already present before the patch (same text, anywhere in the file) is
+// not reported, so edits to files with existing whitespace stay quiet.
+function whitespaceIssues(content: string, previous?: string | null): string[] {
+ const existing = new Set(previous?.split(/\r?\n/u) ?? []);
const issues: string[] = [];
for (const [index, line] of content.split(/\r?\n/u).entries()) {
+ if (existing.has(line)) continue;
if (/^(?:<<<<<<<|=======|>>>>>>>)(?: |$)/u.test(line)) {
issues.push(`line ${index + 1}: unresolved conflict marker`);
} else if (/[\t ]+$/u.test(line)) {
diff --git a/packages/eve-code/extension/lib/grep-search.ts b/packages/eve-code/extension/lib/grep-search.ts
index 145a41616..d6af89881 100644
--- a/packages/eve-code/extension/lib/grep-search.ts
+++ b/packages/eve-code/extension/lib/grep-search.ts
@@ -1,4 +1,5 @@
import { shellQuote } from "./shell.ts";
+import { resolveInWorkspace, type WorkspaceSandbox } from "./workspace-root.ts";
const DEFAULT_GREP_LIMIT = 50;
export const MAX_GREP_LIMIT = 200;
@@ -31,14 +32,6 @@ export interface GrepSearchResult {
readonly truncated: boolean;
}
-interface GrepSandbox {
- resolvePath(path: string): string;
- run(input: {
- abortSignal?: AbortSignal;
- command: string;
- }): PromiseLike<{ exitCode: number; stderr: string; stdout: string }>;
-}
-
interface GrepToolInput {
readonly context?: number;
readonly glob?: string;
@@ -65,14 +58,13 @@ export function effectiveLimit(limit: number | undefined): number {
return Math.min(Math.max(1, limit ?? DEFAULT_GREP_LIMIT), MAX_GREP_LIMIT);
}
-export function assertWorkspacePath(resolved: string, requested?: string): string {
- if (requested !== undefined && requested.split(/[\\/]/u).includes("..")) {
- throw new Error("grep path must not contain '..'");
- }
- if (resolved !== "/workspace" && !resolved.startsWith("/workspace/")) {
- throw new Error(`grep path must stay under /workspace: ${resolved}`);
- }
- if (resolved.split("/").includes("..")) {
+// Containment is enforced on real paths in executeGrepSearch; the workspace
+// root differs by provider (/workspace, /app, ...), so no literal prefix here.
+export function assertNoParentSegments(resolved: string, requested?: string): string {
+ if (
+ (requested !== undefined && requested.split(/[\\/]/u).includes("..")) ||
+ resolved.split("/").includes("..")
+ ) {
throw new Error("grep path must not contain '..'");
}
return resolved;
@@ -80,18 +72,16 @@ export function assertWorkspacePath(resolved: string, requested?: string): strin
export async function executeGrepSearch(
input: GrepToolInput,
- sandbox: GrepSandbox,
+ sandbox: WorkspaceSandbox,
abortSignal?: AbortSignal,
): Promise<GrepSearchResult> {
- const path = assertWorkspacePath(sandbox.resolvePath(input.path ?? "/workspace"), input.path);
- const workspaceRealPath = await sandboxRealPath(
+ const path = assertNoParentSegments(sandbox.resolvePath(input.path ?? ""), input.path);
+ const { path: searchRealPath } = await resolveInWorkspace(
sandbox,
- sandbox.resolvePath(""),
- "sandbox workspace",
+ path,
+ "grep path",
abortSignal,
);
- const searchRealPath = await sandboxRealPath(sandbox, path, "grep path", abortSignal);
- assertRealPathWithinWorkspace(searchRealPath, workspaceRealPath);
const outputMode = effectiveOutputMode(input.outputMode);
const limit = effectiveLimit(input.limit);
@@ -126,35 +116,6 @@ export async function executeGrepSearch(
});
}
-async function sandboxRealPath(
- sandbox: GrepSandbox,
- path: string,
- label: string,
- abortSignal?: AbortSignal,
-): Promise<string> {
- const result = await sandbox.run({
- abortSignal,
- command: `realpath -z -- ${shellQuote(path)}`,
- });
- if (result.exitCode !== 0) {
- const detail = result.stderr.trim() || result.stdout.trim() || "no command output";
- throw new Error(
- `${label} could not be resolved: ${truncateUtf8(detail, MAX_GREP_LINE_BYTES).value}`,
- );
- }
- const realPath = result.stdout.endsWith("\0") ? result.stdout.slice(0, -1) : result.stdout;
- if (realPath.length === 0 || realPath.includes("\0")) {
- throw new Error(`${label} returned an invalid realpath`);
- }
- return realPath;
-}
-
-function assertRealPathWithinWorkspace(realPath: string, workspaceRealPath: string): void {
- if (realPath !== workspaceRealPath && !realPath.startsWith(`${workspaceRealPath}/`)) {
- throw new Error(`grep path resolves outside /workspace: ${realPath}`);
- }
-}
-
export function buildSearchCommand(input: GrepCommandInput): string {
return [
"set -o pipefail",
diff --git a/packages/eve-code/extension/lib/patch.ts b/packages/eve-code/extension/lib/patch.ts
index 60807ab25..1ee68f92d 100644
--- a/packages/eve-code/extension/lib/patch.ts
+++ b/packages/eve-code/extension/lib/patch.ts
@@ -18,6 +18,8 @@ interface UpdateChunk {
readonly oldLines: readonly string[];
readonly newLines: readonly string[];
readonly changeContext?: string;
+ /** Function context from a unified-diff range header; git may have truncated it. */
+ readonly contextHint?: string;
readonly endOfFile?: boolean;
}
@@ -27,6 +29,11 @@ export interface AppliedPatchFile {
readonly previousPath?: string;
}
+/** A verified change about to be written, with the content it replaces. */
+export interface PlannedPatchFile extends AppliedPatchFile {
+ readonly previousContent: string | null;
+}
+
interface PlannedChange extends AppliedPatchFile {
readonly absolutePath: string;
readonly previousAbsolutePath?: string;
@@ -42,20 +49,20 @@ const MISMATCH_EXPECTED_MAX_LINES = 20;
const patchLocks = new Map<string, Promise<void>>();
export async function applyPatchToSandbox(input: {
- readonly beforeCommit?: (files: readonly AppliedPatchFile[]) => Promise<void>;
+ readonly beforeCommit?: (files: readonly PlannedPatchFile[]) => Promise<void>;
readonly patchText: string;
- readonly repoRoot: string;
+ readonly patchRoot: string;
readonly sandbox: SandboxSession;
/** Serializes patches per eve session; every `ctx.getSandbox()` call returns a new handle. */
readonly sessionId: string;
}): Promise<AppliedPatchFile[]> {
- return withPatchLock(`${input.sessionId}:${input.repoRoot}`, () => applyPatchUnlocked(input));
+ return withPatchLock(`${input.sessionId}:${input.patchRoot}`, () => applyPatchUnlocked(input));
}
async function applyPatchUnlocked(input: {
- readonly beforeCommit?: (files: readonly AppliedPatchFile[]) => Promise<void>;
+ readonly beforeCommit?: (files: readonly PlannedPatchFile[]) => Promise<void>;
readonly patchText: string;
- readonly repoRoot: string;
+ readonly patchRoot: string;
readonly sandbox: SandboxSession;
}): Promise<AppliedPatchFile[]> {
const hunks = parsePatch(input.patchText);
@@ -64,12 +71,13 @@ async function applyPatchUnlocked(input: {
throw new Error(`patch rejected: at most ${MAX_PATCH_FILES} file operations are allowed`);
}
- const changes = await planChanges(input.sandbox, input.repoRoot, hunks);
+ const changes = await planChanges(input.sandbox, input.patchRoot, hunks);
await input.beforeCommit?.(
- changes.map(({ operation, path, previousPath }) => {
- const file: { -readonly [Key in keyof AppliedPatchFile]: AppliedPatchFile[Key] } = {
+ changes.map(({ operation, path, previousPath, oldContent }) => {
+ const file: { -readonly [Key in keyof PlannedPatchFile]: PlannedPatchFile[Key] } = {
operation,
path,
+ previousContent: oldContent,
};
if (previousPath !== undefined) file.previousPath = previousPath;
return file;
@@ -78,7 +86,7 @@ async function applyPatchUnlocked(input: {
const committed: PlannedChange[] = [];
try {
for (const change of changes) {
- await revalidateChange(input.sandbox, input.repoRoot, change);
+ await revalidateChange(input.sandbox, input.patchRoot, change);
committed.push(change);
await commitChange(input.sandbox, change);
}
@@ -210,6 +218,23 @@ function parseAdd(lines: readonly string[], start: number, end: number) {
return { content: content.join("\n"), next: index };
}
+// Models often write unified-diff range headers (`@@ -118,8 +118,8 @@ fn`).
+// The numbers are not searchable text. The trailing function context can be
+// the only thing that tells identical blocks apart, but git truncates it, so it
+// becomes a prefix hint rather than an exact anchor.
+const UNIFIED_RANGE_HEADER = /^-\d+(?:,\d+)? \+\d+(?:,\d+)? @@\s*(.*)$/u;
+
+function chunkHeader(headerLine: string): Pick<UpdateChunk, "changeContext" | "contextHint"> {
+ const anchor = headerLine.slice(2).trim();
+ if (anchor.length === 0) return { changeContext: undefined };
+ const range = UNIFIED_RANGE_HEADER.exec(anchor);
+ if (!range) return { changeContext: anchor };
+ const hint = range[1]!.trim();
+ return hint.length === 0
+ ? { changeContext: undefined }
+ : { changeContext: undefined, contextHint: hint };
+}
+
function parseUpdate(lines: readonly string[], start: number, end: number) {
const chunks: UpdateChunk[] = [];
let index = start;
@@ -219,7 +244,7 @@ function parseUpdate(lines: readonly string[], start: number, end: number) {
if (!hasHeader && chunks.length > 0) {
throw new Error(`invalid update file line: ${lines[index]}`);
}
- const changeContext = hasHeader ? headerLine.slice(2).trim() || undefined : undefined;
+ const header = hasHeader ? chunkHeader(headerLine) : { changeContext: undefined };
const oldLines: string[] = [];
const newLines: string[] = [];
let endOfFile = false;
@@ -248,20 +273,20 @@ function parseUpdate(lines: readonly string[], start: number, end: number) {
}
index += 1;
}
- chunks.push({ oldLines, newLines, changeContext, endOfFile: endOfFile || undefined });
+ chunks.push({ oldLines, newLines, ...header, endOfFile: endOfFile || undefined });
}
return { chunks, next: index };
}
async function planChanges(
sandbox: SandboxSession,
- repoRoot: string,
+ patchRoot: string,
hunks: readonly PatchHunk[],
): Promise<PlannedChange[]> {
- const resolvedRoot = await realPath(sandbox, repoRoot);
- if (resolvedRoot !== repoRoot) {
+ const resolvedRoot = await realPath(sandbox, patchRoot);
+ if (resolvedRoot !== patchRoot) {
throw new Error(
- `apply_patch verification failed: repository root resolves outside itself: ${repoRoot}`,
+ `apply_patch verification failed: patch root resolves outside itself: ${patchRoot}`,
);
}
const claimed = new Set<string>();
@@ -269,7 +294,7 @@ async function planChanges(
const errors: string[] = [];
for (const hunk of hunks) {
try {
- changes.push(await planHunk(sandbox, repoRoot, claimed, hunk));
+ changes.push(await planHunk(sandbox, patchRoot, claimed, hunk));
} catch (error) {
errors.push(error instanceof Error ? error.message : String(error));
}
@@ -282,12 +307,12 @@ async function planChanges(
async function planHunk(
sandbox: SandboxSession,
- repoRoot: string,
+ patchRoot: string,
claimed: Set<string>,
hunk: PatchHunk,
): Promise<PlannedChange> {
- const source = resolvePatchPath(repoRoot, hunk.path);
- await assertRealPath(sandbox, repoRoot, source.absolutePath);
+ const source = resolvePatchPath(patchRoot, hunk.path);
+ await assertRealPath(sandbox, patchRoot, source.absolutePath);
claimPath(claimed, source.absolutePath);
if (hunk.type === "add") {
@@ -322,9 +347,9 @@ async function planHunk(
};
}
- const target = hunk.movePath === undefined ? source : resolvePatchPath(repoRoot, hunk.movePath);
+ const target = hunk.movePath === undefined ? source : resolvePatchPath(patchRoot, hunk.movePath);
if (target.absolutePath !== source.absolutePath) {
- await assertRealPath(sandbox, repoRoot, target.absolutePath);
+ await assertRealPath(sandbox, patchRoot, target.absolutePath);
claimPath(claimed, target.absolutePath);
if ((await sandbox.readTextFile({ path: target.absolutePath })) !== null) {
throw new Error(
@@ -379,10 +404,10 @@ async function commitChange(sandbox: SandboxSession, change: PlannedChange): Pro
async function revalidateChange(
sandbox: SandboxSession,
- repoRoot: string,
+ patchRoot: string,
change: PlannedChange,
): Promise<void> {
- await assertRealPath(sandbox, repoRoot, change.absolutePath);
+ await assertRealPath(sandbox, patchRoot, change.absolutePath);
if (change.operation === "add") {
if ((await sandbox.readTextFile({ path: change.absolutePath })) !== null) {
throw new Error(`apply_patch stale write: add target now exists: ${change.path}`);
@@ -390,7 +415,7 @@ async function revalidateChange(
return;
}
if (change.operation === "move" && change.previousAbsolutePath !== undefined) {
- await assertRealPath(sandbox, repoRoot, change.previousAbsolutePath);
+ await assertRealPath(sandbox, patchRoot, change.previousAbsolutePath);
const [source, target] = await Promise.all([
sandbox.readTextFile({ path: change.previousAbsolutePath }),
sandbox.readTextFile({ path: change.absolutePath }),
@@ -474,11 +499,11 @@ async function rollbackChanges(
async function assertRealPath(
sandbox: SandboxSession,
- repoRoot: string,
+ patchRoot: string,
absolutePath: string,
): Promise<void> {
const resolved = await realPath(sandbox, absolutePath);
- if (resolved !== absolutePath || !resolved.startsWith(`${repoRoot}/`)) {
+ if (resolved !== absolutePath || !resolved.startsWith(`${patchRoot}/`)) {
throw new Error(
`apply_patch verification failed: path crosses a symlink or repository boundary: ${absolutePath}`,
);
@@ -552,7 +577,7 @@ async function restoreMode(
if (result.exitCode !== 0) throw new Error(`failed to restore file mode for ${path}`);
}
-function resolvePatchPath(repoRoot: string, candidate: string) {
+function resolvePatchPath(patchRoot: string, candidate: string) {
const normalized = candidate.replaceAll("\\", "/").trim();
if (
normalized.length === 0 ||
@@ -562,7 +587,7 @@ function resolvePatchPath(repoRoot: string, candidate: string) {
) {
throw new Error(`invalid patch path: ${candidate}`);
}
- return { absolutePath: posix.join(repoRoot, normalized), path: normalized };
+ return { absolutePath: posix.join(patchRoot, normalized), path: normalized };
}
function claimPath(claimed: Set<string>, path: string): void {
@@ -592,6 +617,15 @@ function computeReplacements(
}
lineIndex = context + 1;
}
+ if (chunk.contextHint !== undefined) {
+ const hinted = seekPrefix(lines, chunk.contextHint, lineIndex);
+ if (hinted !== -1) {
+ lineIndex = hinted + 1;
+ } else if (occurrences(lines, chunk, lineIndex) !== 1) {
+ // Without the hint, only an unambiguous hunk is safe to apply.
+ throw new Error(formatMissingContextError(path, chunk.contextHint, lines, lineIndex));
+ }
+ }
if (chunk.oldLines.length === 0) {
replacements.push([lines.length, 0, chunk.newLines]);
continue;
@@ -736,6 +770,42 @@ function seek(
return -1;
}
+function occurrences(lines: readonly string[], chunk: UpdateChunk, start: number): number {
+ const found = seekAll(lines, chunk.oldLines, start, chunk.endOfFile);
+ if (found.length > 0 || chunk.oldLines.at(-1) !== "") return found.length;
+ return seekAll(lines, chunk.oldLines.slice(0, -1), start, chunk.endOfFile).length;
+}
+
+// Offsets of every match at the strictest comparison that matches at all, so
+// ambiguity is judged the same way seek() would pick a location.
+function seekAll(
+ lines: readonly string[],
+ pattern: readonly string[],
+ start: number,
+ endOfFile = false,
+): number[] {
+ if (pattern.length === 0) return [];
+ for (const compare of [exact, trimEnd, trim, normalized]) {
+ const tail = lines.length - pattern.length;
+ // seek() prefers the end-of-file position, which makes that match unambiguous.
+ if (endOfFile && tail >= start && matches(lines, pattern, tail, compare)) return [tail];
+ const found: number[] = [];
+ for (let offset = start; offset <= tail; offset += 1) {
+ if (matches(lines, pattern, offset, compare)) found.push(offset);
+ }
+ if (found.length > 0) return found;
+ }
+ return [];
+}
+
+function seekPrefix(lines: readonly string[], hint: string, start: number): number {
+ const wanted = normalizeTypography(hint.trim());
+ for (let index = start; index < lines.length; index += 1) {
+ if (normalizeTypography(lines[index]!.trim()).startsWith(wanted)) return index;
+ }
+ return -1;
+}
+
function matches(
lines: readonly string[],
pattern: readonly string[],
diff --git a/packages/eve-code/extension/lib/repository-root.ts b/packages/eve-code/extension/lib/repository-root.ts
index f256dab38..d051726df 100644
--- a/packages/eve-code/extension/lib/repository-root.ts
+++ b/packages/eve-code/extension/lib/repository-root.ts
@@ -1,16 +1,12 @@
-import type { SandboxSession } from "eve/sandbox";
-
import { shellQuote } from "./shell.ts";
+import { resolveWorkspaceDirectory, type WorkspaceSandbox } from "./workspace-root.ts";
-type RootSandbox = Pick<SandboxSession, "resolvePath" | "run">;
-
-export async function validateRepositoryRoot(sandbox: RootSandbox, root: string): Promise<string> {
- if (!root.startsWith("/")) throw new Error("root must be an absolute sandbox path");
- const workspace = await realPath(sandbox, sandbox.resolvePath(""), "sandbox workspace");
- const resolved = await realPath(sandbox, root, "root");
- if (resolved !== workspace && !resolved.startsWith(`${workspace}/`)) {
- throw new Error(`root must be inside the sandbox workspace: ${root}`);
- }
+/** A workspace directory that must also be the top of a git work tree. */
+export async function validateRepositoryRoot(
+ sandbox: WorkspaceSandbox,
+ root: string,
+): Promise<string> {
+ const resolved = await resolveWorkspaceDirectory(sandbox, root);
const top = await sandbox.run({
command: `git -C ${shellQuote(resolved)} rev-parse --show-toplevel`,
});
@@ -19,10 +15,3 @@ export async function validateRepositoryRoot(sandbox: RootSandbox, root: string)
}
return resolved;
}
-
-async function realPath(sandbox: RootSandbox, path: string, label: string): Promise<string> {
- const result = await sandbox.run({ command: `realpath -e -- ${shellQuote(path)}` });
- if (result.exitCode !== 0)
- throw new Error(`Could not resolve ${label} ${path}: ${result.stderr}`);
- return result.stdout.trim();
-}
diff --git a/packages/eve-code/extension/lib/tooling.ts b/packages/eve-code/extension/lib/tooling.ts
index 2cf448a7e..ccc3105d1 100644
--- a/packages/eve-code/extension/lib/tooling.ts
+++ b/packages/eve-code/extension/lib/tooling.ts
@@ -60,7 +60,7 @@ export function typescriptInstallCommand(sandbox: Pick<SandboxSession, "resolveP
/**
* Runs inside the sandbox with `node`. Reads one base64 JSON request from
- * `EVE_CODE_DIAGNOSTICS_REQUEST` (`{ repoRoot, filePath }`), loads only the
+ * `EVE_CODE_DIAGNOSTICS_REQUEST` (`{ patchRoot, filePath }`), loads only the
* bootstrap-installed compiler, and prints `{ diagnostics }`.
*/
export const DIAGNOSTICS_WORKER_SOURCE = String.raw`const fs = require("node:fs");
@@ -68,9 +68,9 @@ const path = require("node:path");
const { EVE_CODE_DIAGNOSTICS_REQUEST = "" } = require("node:process").env;
const request = JSON.parse(Buffer.from(EVE_CODE_DIAGNOSTICS_REQUEST, "base64").toString());
-const repoRoot = fs.realpathSync(request.repoRoot);
-const fileName = fs.realpathSync(path.join(repoRoot, request.filePath));
-if (fileName !== repoRoot && !fileName.startsWith(repoRoot + path.sep)) {
+const patchRoot = fs.realpathSync(request.patchRoot);
+const fileName = fs.realpathSync(path.join(patchRoot, request.filePath));
+if (fileName !== patchRoot && !fileName.startsWith(patchRoot + path.sep)) {
throw new Error("file escapes repository: " + request.filePath);
}
@@ -100,7 +100,7 @@ const host = {
directoryExists: ts.sys.directoryExists,
fileExists: ts.sys.fileExists,
getCompilationSettings: () => options,
- getCurrentDirectory: () => repoRoot,
+ getCurrentDirectory: () => patchRoot,
getDefaultLibFileName: (compilerOptions) => ts.getDefaultLibFilePath(compilerOptions),
getNewLine: () => ts.sys.newLine,
getScriptFileNames: () => fileNames,
@@ -135,12 +135,12 @@ process.stdout.write(JSON.stringify({ diagnostics }));
function nearestConfig(start) {
let current = start;
- while (current === repoRoot || current.startsWith(repoRoot + path.sep)) {
+ while (current === patchRoot || current.startsWith(patchRoot + path.sep)) {
for (const name of ["tsconfig.json", "jsconfig.json"]) {
const candidate = path.join(current, name);
if (fs.existsSync(candidate)) return candidate;
}
- if (current === repoRoot) break;
+ if (current === patchRoot) break;
current = path.dirname(current);
}
return null;
diff --git a/packages/eve-code/extension/lib/workspace-root.ts b/packages/eve-code/extension/lib/workspace-root.ts
new file mode 100644
index 000000000..b42869c5a
--- /dev/null
+++ b/packages/eve-code/extension/lib/workspace-root.ts
@@ -0,0 +1,75 @@
+import { shellQuote } from "./shell.ts";
+
+/**
+ * The single containment check for sandbox paths that tools read or write.
+ * The workspace root differs by provider (`/workspace`, `/app`, ...), so the
+ * boundary is the real path of `resolvePath("")`, never a literal prefix.
+ */
+export interface WorkspaceSandbox {
+ resolvePath(path: string): string;
+ run(input: {
+ abortSignal?: AbortSignal;
+ command: string;
+ }): PromiseLike<{ exitCode: number; stderr: string; stdout: string }>;
+}
+
+const MAX_ERROR_DETAIL_CHARS = 2_000;
+
+/** NUL-delimited output keeps paths that contain newlines unambiguous. */
+export async function sandboxRealPath(
+ sandbox: WorkspaceSandbox,
+ path: string,
+ label: string,
+ abortSignal?: AbortSignal,
+): Promise<string> {
+ const result = await sandbox.run({
+ abortSignal,
+ command: `realpath -e -z -- ${shellQuote(path)}`,
+ });
+ if (result.exitCode !== 0) {
+ const detail = result.stderr.trim() || result.stdout.trim() || "no command output";
+ throw new Error(`${label} could not be resolved: ${detail.slice(0, MAX_ERROR_DETAIL_CHARS)}`);
+ }
+ const realPath = result.stdout.endsWith("\0") ? result.stdout.slice(0, -1) : result.stdout;
+ if (realPath.length === 0 || realPath.includes("\0")) {
+ throw new Error(`${label} returned an invalid realpath`);
+ }
+ return realPath;
+}
+
+/**
+ * Resolves `path` (default: the workspace root) to a real path inside the real
+ * workspace. Symlinks are followed before the check, so a link cannot escape.
+ */
+export async function resolveInWorkspace(
+ sandbox: WorkspaceSandbox,
+ path: string | undefined,
+ label: string,
+ abortSignal?: AbortSignal,
+): Promise<{ readonly path: string; readonly workspace: string }> {
+ const workspace = await sandboxRealPath(
+ sandbox,
+ sandbox.resolvePath(""),
+ "sandbox workspace",
+ abortSignal,
+ );
+ if (path === undefined) return { path: workspace, workspace };
+ const real = await sandboxRealPath(sandbox, path, label, abortSignal);
+ const inside = workspace === "/" || real === workspace || real.startsWith(`${workspace}/`);
+ if (!inside) throw new Error(`${label} resolves outside the workspace ${workspace}: ${real}`);
+ return { path: real, workspace };
+}
+
+/**
+ * An absolute directory inside the workspace (default: the workspace root).
+ * Git is not required; `validateRepositoryRoot` adds that check.
+ */
+export async function resolveWorkspaceDirectory(
+ sandbox: WorkspaceSandbox,
+ root?: string,
+): Promise<string> {
+ if (root !== undefined && !root.startsWith("/")) {
+ throw new Error("root must be an absolute sandbox path");
+ }
+ return (await resolveInWorkspace(sandbox, root, "root")).path;
+}
diff --git a/packages/eve-code/extension/tools/apply_patch.ts b/packages/eve-code/extension/tools/apply_patch.ts
index 400b5625c..aef41f565 100644
--- a/packages/eve-code/extension/tools/apply_patch.ts
+++ b/packages/eve-code/extension/tools/apply_patch.ts
@@ -10,7 +10,7 @@ import {
} from "../lib/diagnostics.ts";
import { findGeneratedPatchTargets, generatedPatchTargetsError } from "../lib/generated-paths.ts";
import { applyPatchToSandbox } from "../lib/patch.ts";
-import { validateRepositoryRoot } from "../lib/repository-root.ts";
+import { resolveWorkspaceDirectory } from "../lib/workspace-root.ts";
const DiagnosticSchema = z.object({
check: z.enum(["git-diff", "syntax", "typescript", "whitespace"]),
@@ -23,7 +23,7 @@ const DiagnosticSchema = z.object({
export default defineTool({
description: [
- "Apply targeted changes inside a git checkout in the sandbox workspace.",
+ "Apply targeted changes to files in the sandbox workspace. No git checkout is required.",
"Use this instead of rewriting complete files or writing through bash.",
"Write small hunks against current file contents. If a hunk misses, re-read that file and rewrite only the failed hunk. Do not retry the same patch text.",
"The patch is fully parsed and every source file is verified before any write.",
@@ -35,16 +35,22 @@ export default defineTool({
"*** Update File: path (optional *** Move to: new-path, followed by @@ chunks)",
"*** Delete File: path",
"*** End Patch",
- "Paths are relative to the repository and may not escape it.",
+ "Paths are relative to root and may not escape it.",
"Generated files (lockfiles, dist/, vendor-compiled/) are rejected: change them",
"through the command that generates them, never through a patch.",
].join("\n"),
approval: never(),
label: {
- start: ({ root }) => `Patch ${root}`,
+ start: ({ root }) => `Patch ${root ?? "workspace"}`,
},
inputSchema: z.object({
- root: z.string().min(1).describe("absolute git checkout root inside the sandbox workspace"),
+ root: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ "absolute directory inside the sandbox workspace that patch paths are relative to; defaults to the workspace root",
+ ),
patchText: z.string().min(1).max(500_000).describe("complete *** Begin Patch text"),
}),
outputSchema: z.object({
@@ -63,19 +69,21 @@ export default defineTool({
throw new Error(generatedPatchTargetsError(generatedTargets));
}
const sandbox = await ctx.getSandbox();
- const repoRoot = await validateRepositoryRoot(sandbox, root);
+ const patchRoot = await resolveWorkspaceDirectory(sandbox, root);
let baseline: readonly PostEditDiagnostic[] = [];
+ const previousContents = new Map<string, string | null>();
const files = await applyPatchToSandbox({
async beforeCommit(planned) {
+ for (const file of planned) previousContents.set(file.path, file.previousContent);
baseline = await runTypeScriptDiagnostics({
paths: planned.filter((file) => file.operation === "update").map((file) => file.path),
- repoRoot,
+ patchRoot,
sandbox,
});
},
patchText,
- repoRoot,
+ patchRoot,
sandbox,
sessionId: ctx.session.id,
});
@@ -91,7 +99,14 @@ export default defineTool({
),
];
const diagnostics = onlyNewTypeDiagnostics(
- await runPostEditDiagnostics({ addedPaths, changedPaths, deletedPaths, repoRoot, sandbox }),
+ await runPostEditDiagnostics({
+ addedPaths,
+ changedPaths,
+ deletedPaths,
+ patchRoot,
+ previousContents,
+ sandbox,
+ }),
baseline,
);
return { diagnostics, files };
diff --git a/packages/eve-code/extension/tools/grep.ts b/packages/eve-code/extension/tools/grep.ts
index 8405696b3..fbdb62fec 100644
--- a/packages/eve-code/extension/tools/grep.ts
+++ b/packages/eve-code/extension/tools/grep.ts
@@ -34,7 +34,9 @@ const InputSchema = z.object({
path: z
.string()
.optional()
- .describe("Directory or file under /workspace. Defaults to /workspace. Narrow this first."),
+ .describe(
+ "Directory or file inside the workspace. Defaults to the workspace root. Narrow this first.",
+ ),
pattern: z.string().min(1).describe("Regex or literal to search for."),
});
diff --git a/packages/eve-code/test/integration/diagnostics.test.ts b/packages/eve-code/test/integration/diagnostics.test.ts
index 9506fd1a7..9841a996a 100644
--- a/packages/eve-code/test/integration/diagnostics.test.ts
+++ b/packages/eve-code/test/integration/diagnostics.test.ts
@@ -12,6 +12,9 @@ test("reports git and supported-file syntax diagnostics", async () => {
const commands: string[] = [];
const sandbox = commandSandbox(async ({ command }) => {
commands.push(command);
+ if (command.includes("rev-parse --is-inside-work-tree")) {
+ return { exitCode: 0, stdout: "true\n", stderr: "" };
+ }
if (command.includes("diff --check")) {
return { exitCode: 2, stdout: "", stderr: "src/file.ts: trailing whitespace" };
}
@@ -35,7 +38,7 @@ test("reports git and supported-file syntax diagnostics", async () => {
const diagnostics = await runPostEditDiagnostics({
changedPaths: ["src/file.ts", "README.md"],
deletedPaths: ["old.ts"],
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
});
@@ -54,12 +57,49 @@ test("reports git and supported-file syntax diagnostics", async () => {
assert.equal(commands.filter((command) => command.includes("README.md")).length, 1);
});
+for (const [name, probe] of [
+ ["outside a git checkout", { exitCode: 128, stdout: "", stderr: "fatal: not a git repository" }],
+ ["inside a .git directory or bare repository", { exitCode: 0, stdout: "false\n", stderr: "" }],
+] as const) {
+ test(`checks whitespace in updated files ${name}`, async () => {
+ const commands: string[] = [];
+ const sandbox = commandSandbox(
+ async ({ command }) => {
+ commands.push(command);
+ return command.includes("rev-parse") ? probe : { exitCode: 0, stdout: "", stderr: "" };
+ },
+ "worker",
+ { "/app/README.md": "# Title \nkept \nnew line \n" },
+ );
+
+ const diagnostics = await runPostEditDiagnostics({
+ changedPaths: ["README.md"],
+ deletedPaths: [],
+ patchRoot: "/app",
+ previousContents: new Map([["README.md", "# Title\nkept \n"]]),
+ sandbox,
+ });
+
+ assert.deepEqual(diagnostics, [
+ {
+ check: "whitespace",
+ path: "README.md",
+ message: "line 1: trailing whitespace\nline 3: trailing whitespace",
+ },
+ ]);
+ assert.equal(
+ commands.some((command) => command.includes("diff --check")),
+ false,
+ );
+ });
+}
+
test("skips TypeScript diagnostics when the worker is not installed", async () => {
const sandbox = commandSandbox(async () => ({ exitCode: 0, stdout: "", stderr: "" }), null);
assert.deepEqual(
await runTypeScriptDiagnostics({
paths: ["src/file.ts"],
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
}),
[],
@@ -73,7 +113,7 @@ test("reports diagnostic runner failures without failing a committed edit", asyn
const diagnostics = await runPostEditDiagnostics({
changedPaths: ["src/file.js"],
deletedPaths: [],
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
});
assert.deepEqual(diagnostics, [
@@ -89,6 +129,7 @@ test("reports diagnostic runner failures without failing a committed edit", asyn
function commandSandbox(
run: SandboxSession["run"],
worker: string | null = "worker",
+ files: Readonly<Record<string, string>> = {},
): SandboxSession {
return {
run,
@@ -96,7 +137,7 @@ function commandSandbox(
return `/workspace/${path}`;
},
async readTextFile({ path }) {
- return path.endsWith("diagnostics.cjs") ? worker : null;
+ return path.endsWith("diagnostics.cjs") ? worker : (files[path] ?? null);
},
async removePath() {},
async spawn() {
diff --git a/packages/eve-code/test/integration/github-shell.test.ts b/packages/eve-code/test/integration/github-shell.test.ts
index 7f4d5b343..6cce98319 100644
--- a/packages/eve-code/test/integration/github-shell.test.ts
+++ b/packages/eve-code/test/integration/github-shell.test.ts
@@ -187,10 +187,10 @@ test("mints a repository-scoped token only during execution and redacts output",
return fakeSandbox(
runs,
(run) => {
- const stdout = run.command.includes("realpath -e -- '/workspace/internal-agents'")
- ? "/workspace/internal-agents\n"
+ const stdout = run.command.includes("realpath -e -z -- '/workspace/internal-agents'")
+ ? "/workspace/internal-agents\0"
: run.command.includes("realpath -e")
- ? "/workspace\n"
+ ? "/workspace\0"
: run.command.includes("rev-parse --show-toplevel")
? "/workspace/internal-agents\n"
: run.command.includes("remote get-url")
diff --git a/packages/eve-code/test/integration/patch.test.ts b/packages/eve-code/test/integration/patch.test.ts
index c9907012a..88741eb12 100644
--- a/packages/eve-code/test/integration/patch.test.ts
+++ b/packages/eve-code/test/integration/patch.test.ts
@@ -96,6 +96,112 @@ test("accepts Codex environment metadata without treating it as an operation", (
);
});
+const DUPLICATE_BLOCKS =
+ "def first():\n enabled = false\n\ndef second():\n enabled = false\n";
+
+function rangeHeaderPatch(header: string): ReturnType<typeof parsePatch> {
+ return parsePatch(`*** Begin Patch
+*** Update File: flags.py
+${header}
+- enabled = false
++ enabled = true
+*** End Patch`);
+}
+
+function rangeHeaderChunks(header: string) {
+ const [hunk] = rangeHeaderPatch(header);
+ return hunk?.type === "update" ? hunk.chunks : [];
+}
+
+test("range-header function context picks the block among identical ones", () => {
+ assert.equal(
+ deriveUpdatedContent(
+ "flags.py",
+ rangeHeaderChunks("@@ -5 +5 @@ def second():"),
+ DUPLICATE_BLOCKS,
+ ),
+ "def first():\n enabled = false\n\ndef second():\n enabled = true\n",
+ );
+});
+
+test("range-header function context matches git's truncated form as a prefix", () => {
+ const content = DUPLICATE_BLOCKS.replace(
+ "def second():",
+ "def second(argument_with_a_long_name, other):",
+ );
+ assert.equal(
+ deriveUpdatedContent(
+ "flags.py",
+ rangeHeaderChunks("@@ -5 +5 @@ def second(argument_with"),
+ content,
+ ),
+ content.replace(/(other\):\n {4}enabled = )false/u, "$1true"),
+ );
+});
+
+test("a stale range-header hint still applies when the hunk is unambiguous", () => {
+ assert.equal(
+ deriveUpdatedContent(
+ "flags.py",
+ rangeHeaderChunks("@@ -2 +2 @@ def renamed():"),
+ "def first():\n enabled = false\n",
+ ),
+ "def first():\n enabled = true\n",
+ );
+});
+
+test("a stale range-header hint fails loudly when the hunk is ambiguous", () => {
+ assert.throws(
+ () =>
+ deriveUpdatedContent(
+ "flags.py",
+ rangeHeaderChunks("@@ -5 +5 @@ def renamed():"),
+ DUPLICATE_BLOCKS,
+ ),
+ /failed to find context 'def renamed\(\):' in flags\.py/u,
+ );
+});
+
+test("treats unified-diff range headers as bare chunk markers", () => {
+ const [hunk] = parsePatch(`*** Begin Patch
+*** Update File: process.py
+@@ -2,3 +2,3 @@ def main():
+ key = os.environ["KEY"]
+- token = "hf_secret"
++ token = "<your-huggingface-token>"
+@@ -9,1 +9,1 @@
+-debug = True
++debug = False
+*** End Patch`);
+ assert.equal(hunk?.type, "update");
+ const chunks = hunk?.type === "update" ? hunk.chunks : [];
+ assert.deepEqual(
+ chunks.map((chunk) => [chunk.changeContext, chunk.contextHint]),
+ [
+ [undefined, "def main():"],
+ [undefined, undefined],
+ ],
+ );
+ assert.equal(
+ deriveUpdatedContent(
+ "process.py",
+ chunks,
+ 'def main():\n key = os.environ["KEY"]\n token = "hf_secret"\n\ndebug = True\n',
+ ),
+ 'def main():\n key = os.environ["KEY"]\n token = "<your-huggingface-token>"\n\ndebug = False\n',
+ );
+});
+
+test("keeps a textual @@ anchor that only looks numeric", () => {
+ const [hunk] = parsePatch(`*** Begin Patch
+*** Update File: notes.txt
+@@ -1 is the sentinel
+-a
++b
+*** End Patch`);
+ assert.equal(hunk?.type === "update" && hunk.chunks[0]?.changeContext, "-1 is the sentinel");
+});
+
test("preserves BOM and CRLF while applying an update", () => {
const updated = deriveUpdatedContent(
"file.ts",
@@ -150,7 +256,7 @@ test("reports every planning failure before writing", async () => {
await assert.rejects(
applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
patchText: `*** Begin Patch
*** Update File: stale.ts
@@ -184,7 +290,7 @@ test("validates every operation before changing the sandbox", async () => {
await assert.rejects(
applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
patchText: `*** Begin Patch
*** Update File: existing.txt
@@ -210,7 +316,7 @@ test("applies add, update, move, and delete after prevalidation", async () => {
});
const files = await applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
patchText: `*** Begin Patch
*** Add File: nested/new.txt
@@ -246,7 +352,7 @@ test("serializes patches from distinct sandbox handles in one session", async ()
const patch = (from: string, to: string) =>
applyPatchToSandbox({
sessionId: "session-serialized",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
// Each ctx.getSandbox() call returns a new handle for the same sandbox.
sandbox: { ...sandbox },
patchText: `*** Begin Patch\n*** Update File: file.txt\n@@\n-${from}\n+${to}\n*** End Patch`,
@@ -264,9 +370,11 @@ test("collects pre-commit evidence inside the patch lock before writing", async
sessionId: "session-1",
async beforeCommit(files) {
observed = (await sandbox.readTextFile({ path: "/workspace/eve/file.txt" })) ?? "";
- assert.deepEqual(files, [{ operation: "update", path: "file.txt" }]);
+ assert.deepEqual(files, [
+ { operation: "update", path: "file.txt", previousContent: "before\n" },
+ ]);
},
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
patchText: `*** Begin Patch
*** Update File: file.txt
@@ -284,7 +392,7 @@ test("rejects paths outside the selected repository", async () => {
await assert.rejects(
applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox: memorySandbox({}),
patchText: `*** Begin Patch
*** Add File: ../outside.txt
@@ -299,7 +407,7 @@ test("rejects paths that cross a repository symlink", async () => {
await assert.rejects(
applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox: memorySandbox({}, { "/workspace/eve/escape/file.txt": "/workspace/other/file.txt" }),
patchText: `*** Begin Patch
*** Add File: escape/file.txt
@@ -326,7 +434,7 @@ test("a partial temporary write leaves the target unchanged", async () => {
await assert.rejects(
applyPatchToSandbox({
sessionId: "session-1",
- repoRoot: "/workspace/eve",
+ patchRoot: "/workspace/eve",
sandbox,
patchText: `*** Begin Patch
*** Update File: file.txt
diff --git a/packages/eve-code/test/integration/repository-root.test.ts b/packages/eve-code/test/integration/repository-root.test.ts
index f441a0a51..179257cc1 100644
--- a/packages/eve-code/test/integration/repository-root.test.ts
+++ b/packages/eve-code/test/integration/repository-root.test.ts
@@ -1,42 +1,95 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { SandboxSession } from "eve/sandbox";
-
import { validateRepositoryRoot } from "../../extension/lib/repository-root.ts";
+import {
+ resolveInWorkspace,
+ resolveWorkspaceDirectory,
+ type WorkspaceSandbox,
+} from "../../extension/lib/workspace-root.ts";
+
+test("workspace directories default to the workspace and need no git checkout", async () => {
+ const runs: string[] = [];
+ const sandbox = workspaceSandbox("/app", {}, runs);
+ assert.equal(await resolveWorkspaceDirectory(sandbox), "/app");
+ assert.equal(await resolveWorkspaceDirectory(sandbox, "/app/src"), "/app/src");
+ assert.equal(
+ runs.some((command) => command.startsWith("git ")),
+ false,
+ );
+});
+
+test("workspace directories must be absolute and stay inside the workspace", async () => {
+ await assert.rejects(
+ resolveWorkspaceDirectory(workspaceSandbox("/app"), "/etc"),
+ /root resolves outside the workspace \/app: \/etc/u,
+ );
+ await assert.rejects(resolveWorkspaceDirectory(workspaceSandbox("/app"), "src"), /absolute/u);
+});
+
+test("containment follows symlinks before comparing", async () => {
+ await assert.rejects(
+ resolveInWorkspace(workspaceSandbox("/app", { "/app/link": "/etc" }), "/app/link", "grep path"),
+ /grep path resolves outside the workspace \/app: \/etc/u,
+ );
+});
-test("accepts a git root inside the sandbox workspace", async () => {
- const sandbox = rootSandbox("/workspace/repo");
- assert.equal(await validateRepositoryRoot(sandbox, "/workspace/repo"), "/workspace/repo");
+test("real paths are read NUL-delimited, so newlines in names survive", async () => {
+ const sandbox = workspaceSandbox("/app", { "/app/odd": "/app/line\nbreak" });
+ assert.deepEqual(await resolveInWorkspace(sandbox, "/app/odd", "root"), {
+ path: "/app/line\nbreak",
+ workspace: "/app",
+ });
});
-test("rejects roots outside the workspace and nested git paths", async () => {
+test("a missing path reports the provider's error", async () => {
+ const sandbox: WorkspaceSandbox = {
+ resolvePath: () => "/app",
+ async run({ command }) {
+ return command.includes("'/app'")
+ ? { exitCode: 0, stdout: "/app\0", stderr: "" }
+ : { exitCode: 1, stdout: "", stderr: "realpath: /app/missing: No such file or directory" };
+ },
+ };
await assert.rejects(
- validateRepositoryRoot(rootSandbox("/outside/repo"), "/outside/repo"),
- /inside the sandbox workspace/u,
+ resolveWorkspaceDirectory(sandbox, "/app/missing"),
+ /root could not be resolved: realpath: \/app\/missing: No such file/u,
+ );
+});
+
+test("repository roots add the git toplevel check", async () => {
+ assert.equal(
+ await validateRepositoryRoot(workspaceSandbox("/workspace"), "/workspace/repo"),
+ "/workspace/repo",
);
await assert.rejects(
- validateRepositoryRoot(rootSandbox("/workspace/repo", "/workspace"), "/workspace/repo"),
+ validateRepositoryRoot(workspaceSandbox("/workspace", {}, [], "/workspace"), "/workspace/repo"),
/not a git work tree root/u,
);
+ await assert.rejects(
+ validateRepositoryRoot(workspaceSandbox("/workspace"), "/outside/repo"),
+ /resolves outside the workspace/u,
+ );
});
-function rootSandbox(
- resolvedRoot: string,
- gitTop = resolvedRoot,
-): Pick<SandboxSession, "resolvePath" | "run"> {
+function workspaceSandbox(
+ workspace: string,
+ links: Readonly<Record<string, string>> = {},
+ runs: string[] = [],
+ gitTop?: string,
+): WorkspaceSandbox {
return {
- resolvePath() {
- return "/workspace";
- },
+ resolvePath: () => workspace,
async run({ command }) {
- if (command.includes("realpath") && command.includes(`'${resolvedRoot}'`)) {
- return { exitCode: 0, stdout: `${resolvedRoot}\n`, stderr: "" };
- }
- if (command.includes("realpath")) {
- return { exitCode: 0, stdout: "/workspace\n", stderr: "" };
+ runs.push(command);
+ const realpath = /^realpath -e -z -- '([^']*)'$/u.exec(command);
+ if (realpath) {
+ const path = realpath[1]!;
+ return { exitCode: 0, stdout: `${links[path] ?? path}\0`, stderr: "" };
}
- return { exitCode: 0, stdout: `${gitTop}\n`, stderr: "" };
+ const git = /^git -C '([^']*)' rev-parse --show-toplevel$/u.exec(command);
+ if (git) return { exitCode: 0, stdout: `${gitTop ?? git[1]}\n`, stderr: "" };
+ throw new Error(`unexpected command: ${command}`);
},
};
}
diff --git a/packages/eve-code/test/scenario/code-query-worker.test.ts b/packages/eve-code/test/scenario/code-query-worker.test.ts
index ed94ae1bb..06a8d1fb8 100644
--- a/packages/eve-code/test/scenario/code-query-worker.test.ts
+++ b/packages/eve-code/test/scenario/code-query-worker.test.ts
@@ -38,7 +38,7 @@ Module._resolveFilename = function(id, ...args) {
);
return async (filePath: string, requestedCompiler = typescriptPath) => {
const request = Buffer.from(
- JSON.stringify({ repoRoot: root, filePath, typescriptPath: requestedCompiler }),
+ JSON.stringify({ patchRoot: root, filePath, typescriptPath: requestedCompiler }),
).toString("base64");
const { stdout } = await execFileAsync(process.execPath, ["--require", preload, worker], {
cwd: root,
diff --git a/packages/eve-code/test/scenario/grep-search.test.ts b/packages/eve-code/test/scenario/grep-search.test.ts
index 83776b247..7bd43c504 100644
--- a/packages/eve-code/test/scenario/grep-search.test.ts
+++ b/packages/eve-code/test/scenario/grep-search.test.ts
@@ -6,7 +6,7 @@ import {
MAX_GREP_COMMAND_BYTES,
MAX_GREP_LINE_BYTES,
MAX_GREP_RETURN_BYTES,
- assertWorkspacePath,
+ assertNoParentSegments,
buildPosixGrepCommand,
buildRipgrepCommand,
buildSearchCommand,
@@ -116,14 +116,74 @@ test("search command prefers rg when it is on PATH", () => {
assert.match(command, /else/u);
});
-test("workspace path checks reject escapes before the sandbox runs", () => {
- assert.equal(assertWorkspacePath("/workspace", undefined), "/workspace");
- assert.equal(assertWorkspacePath("/workspace/src", "src"), "/workspace/src");
+test("parent-segment checks reject escapes before the sandbox runs", () => {
+ assert.equal(assertNoParentSegments("/workspace", undefined), "/workspace");
+ assert.equal(assertNoParentSegments("/app/src", "src"), "/app/src");
assert.throws(
- () => assertWorkspacePath("/etc/passwd", "/etc/passwd"),
- /must stay under \/workspace/u,
+ () => assertNoParentSegments("/workspace/src", "../etc"),
+ /must not contain '\.\.'/u,
+ );
+ assert.throws(() => assertNoParentSegments("/app/../etc"), /must not contain '\.\.'/u);
+});
+
+test("executeGrepSearch accepts absolute paths in a workspace rooted outside /workspace", async () => {
+ let command = "";
+ const result = await executeGrepSearch(
+ { pattern: "secret_key", path: "/app/dclm" },
+ {
+ resolvePath: (value) => (value.startsWith("/") ? value : value ? `/app/${value}` : "/app"),
+ async run(input) {
+ if (input.command.startsWith("realpath")) {
+ return {
+ exitCode: 0,
+ stderr: "",
+ stdout: input.command.includes("/app/dclm") ? "/app/dclm\0" : "/app\0",
+ };
+ }
+ command = input.command;
+ return { exitCode: 0, stderr: "", stdout: "/app/dclm/README.md\n" };
+ },
+ },
+ );
+ assert.match(command, /'\/app\/dclm'/u);
+ assert.equal(result.path, "/app/dclm");
+ assert.equal(result.matchCount, 1);
+});
+
+test("executeGrepSearch defaults to the sandbox workspace root", async () => {
+ const searched: string[] = [];
+ await executeGrepSearch(
+ { pattern: "needle" },
+ {
+ resolvePath: (value) => (value ? `/app/${value}` : "/app"),
+ async run(input) {
+ if (input.command.startsWith("realpath"))
+ return { exitCode: 0, stderr: "", stdout: "/app\0" };
+ searched.push(input.command);
+ return { exitCode: 1, stderr: "", stdout: "" };
+ },
+ },
+ );
+ assert.match(searched[0] ?? "", /'\/app'/u);
+});
+
+test("executeGrepSearch rejects an absolute path outside the workspace", async () => {
+ await assert.rejects(
+ executeGrepSearch(
+ { pattern: "root", path: "/etc" },
+ {
+ resolvePath: (value) => (value.startsWith("/") ? value : "/app"),
+ async run({ command }) {
+ return {
+ exitCode: 0,
+ stderr: "",
+ stdout: command.includes("/etc") ? "/etc\0" : "/app\0",
+ };
+ },
+ },
+ ),
+ /resolves outside the workspace \/app: \/etc/u,
);
- assert.throws(() => assertWorkspacePath("/workspace/src", "../etc"), /must not contain '\.\.'/u);
});
test("processGrepOutput caps rows and drops zero-count files", () => {
@@ -301,7 +361,7 @@ test("executeGrepSearch rejects a symlink target whose realpath escapes the work
},
},
),
- /resolves outside \/workspace/u,
+ /resolves outside the workspace \/workspace: \/etc/u,
);
assert.equal(runCount, 2);
});