diff --git a/NOTICE b/NOTICE index 03af142..63d495a 100644 --- a/NOTICE +++ b/NOTICE @@ -7,3 +7,20 @@ Third-party code ---------------- Portions of this product that are derived from third-party projects are listed below together with their copyright notices and licenses. + +Turnpack + Files: src/tools/edit-match.ts, src/tools/edit-match.test.ts (ported), + src/tools/journal.ts and src/tools/jail.ts (design and parts adapted) + Source: https://github.com/OnlyTerp/turnpack (commit b14330d) + License: Apache License, Version 2.0 + Modified by the agent-code-mode authors (see the header of each file). + Turnpack's NOTICE: + + Turnpack + Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + + This product is licensed under the Apache License, Version 2.0. + You may obtain a copy of the License in the LICENSE file, or at + http://www.apache.org/licenses/LICENSE-2.0 + + Project home: https://github.com/OnlyTerp/turnpack diff --git a/package-lock.json b/package-lock.json index 596f70d..0b8cab9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, @@ -21,7 +22,34 @@ "vitest": "^5.1.0" }, "engines": { - "node": ">=22" + "node": ">=22.12.0" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime": { + "version": "0.0.81", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.81.tgz", + "integrity": "sha512-bjHDu87gjIR7+Oxy9jPiK3v8CvSELCzfpXa3fjqfSKdvlZET2iF51xcXILWPayTpowB3xtZeQVf2JR916nVW/w==", + "license": "Apache-2.0", + "dependencies": { + "@pondwader/socks5-server": "^1.0.10", + "commander": "^12.1.0", + "node-forge": "^1.4.0", + "zod": "^3.25.0" + }, + "bin": { + "srt": "dist/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" } }, "node_modules/@emnapi/core": { @@ -175,6 +203,12 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@pondwader/socks5-server": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz", + "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==", + "license": "MIT" + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.19", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", @@ -1057,6 +1091,15 @@ "node": ">=18" } }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/content-disposition": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", @@ -2054,6 +2097,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/node-forge": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", diff --git a/package.json b/package.json index 1d1997d..5709af6 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "NOTICE" ], "engines": { - "node": ">=22" + "node": ">=22.12.0" }, "repository": { "type": "git", @@ -27,6 +27,7 @@ "bench": "node -e \"console.log('bench: not implemented yet')\"" }, "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, diff --git a/src/core/errors.ts b/src/core/errors.ts index 0fa9c1c..7bd475a 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -18,6 +18,22 @@ export class ToolError extends Error { } } +/** + * Thrown by `Transaction.dispose()` when the journal could not be finalized. + * `committed: false`: the journal is intact and can still be rolled back. + * `committed: true`: the journal is out of recovery's reach (the changes are + * kept), but the step that makes that durable failed. + */ +export class TransactionFinalizeError extends Error { + override readonly name = 'TransactionFinalizeError'; + readonly committed: boolean; + + constructor(committed: boolean, message: string) { + super(message); + this.committed = committed; + } +} + /** Message of any thrown value, without trusting its shape. */ export function errorMessage(err: unknown): string { if (err instanceof Error) return err.message; diff --git a/src/core/run.test.ts b/src/core/run.test.ts index 7918581..5139759 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -3,6 +3,7 @@ import { makeContext } from '../testing/context.js'; import { FakeSandbox, type FakeStep } from '../testing/fake-sandbox.js'; import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; import { StaticHostAdapter, type StaticHostAdapterOptions } from '../testing/static-host-adapter.js'; +import { TransactionFinalizeError } from './errors.js'; import { resolveTimeoutMs, runScript, toRunRequest } from './run.js'; import type { Sandbox } from './types.js'; @@ -281,6 +282,172 @@ describe('runScript', () => { await vi.waitFor(() => expect(events).toEqual(['rollback', 'dispose'])); }); + it('reports success only after the journal is finalized', async () => { + const d = deps(); + let finalize = (): void => undefined; + const gate = new Promise((r) => (finalize = r)); + let disposeCalls = 0; + const begin = d.tools.beginTransaction.bind(d.tools); + d.tools.beginTransaction = () => { + const tx = begin(); + const dispose = tx.dispose.bind(tx); + tx.dispose = async () => { + disposeCalls++; + await gate; + await dispose(); + }; + return tx; + }; + let settled = false; + const running = runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'x' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ).then((r) => ((settled = true), r)); + await vi.waitFor(() => expect(disposeCalls).toBe(1)); + await new Promise((r) => setTimeout(r, 20)); + expect(settled).toBe(false); + finalize(); + const result = await running; + expect(result.ok).toBe(true); + expect(d.tools.read('a.txt')).toBe('x'); + await new Promise((r) => setTimeout(r, 10)); + expect(disposeCalls).toBe(1); + }); + + it('fails and rolls back a successful script when the journal cannot be finalized', async () => { + const d = deps({}, { 'a.txt': 'original' }); + const begin = d.tools.beginTransaction.bind(d.tools); + const rollbacks = vi.fn(); + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + tx.dispose = async () => { + throw new TransactionFinalizeError(false, 'rename failed'); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionNotFinalized' }); + expect(result.error?.message).toContain('rename failed'); + expect(rollbacks).toHaveBeenCalledTimes(1); + expect(result.rolledBack?.restored).toEqual(['/ws/a.txt']); + expect(d.tools.read('a.txt')).toBe('original'); + }); + + it('reports an indeterminate outcome when the journal was committed but not flushed, without rolling back', async () => { + const d = deps({}, { 'a.txt': 'original' }); + const begin = d.tools.beginTransaction.bind(d.tools); + const rollbacks = vi.fn(); + let disposeCalls = 0; + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + tx.dispose = async () => { + disposeCalls++; + throw new TransactionFinalizeError(true, 'the transaction journal was finalized, but flushing it to disk failed'); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.rolledBack).toBeUndefined(); + expect(result.warnings.join('\n')).toContain('are on disk and were not rolled back'); + await new Promise((r) => setTimeout(r, 20)); + expect(rollbacks).not.toHaveBeenCalled(); + expect(disposeCalls).toBe(1); + expect(d.tools.read('a.txt')).toBe('changed'); + }); + + /** A transaction whose finalization waits for `gate` and then ends as `end` says. */ + function slowFinalization(d: ReturnType, gate: Promise, end: () => Promise, onDispose = (): void => undefined) { + const rollbacks = vi.fn(); + const begin = d.tools.beginTransaction.bind(d.tools); + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + const dispose = tx.dispose.bind(tx); + tx.dispose = async () => { + onDispose(); + await gate; + await end(); + await dispose(); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + return rollbacks; + } + + it('stops waiting for a finalization that outlasts the run, and reports neither success nor a rollback', async () => { + const d = { ...deps({}, { 'a.txt': 'original' }), stopGraceMs: 20 }; + let release = (): void => undefined; + const rollbacks = slowFinalization(d, new Promise((r) => (release = r)), async () => undefined); + const result = await runScript({ code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 50 }, d); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.error?.message).toContain('time limit'); + expect(result.rolledBack).toBeUndefined(); + release(); + await new Promise((r) => setTimeout(r, 20)); + expect(rollbacks).not.toHaveBeenCalled(); + expect(d.tools.read('a.txt')).toBe('changed'); + }); + + it('rolls back once a finalization that outlasted the run fails to commit', async () => { + const d = { ...deps({}, { 'a.txt': 'original' }), stopGraceMs: 20 }; + let release = (): void => undefined; + const rollbacks = slowFinalization(d, new Promise((r) => (release = r)), async () => { + throw new TransactionFinalizeError(false, 'rename failed'); + }); + const result = await runScript({ code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 50 }, d); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + release(); + await vi.waitFor(() => expect(rollbacks).toHaveBeenCalledTimes(1)); + await vi.waitFor(() => expect(d.tools.read('a.txt')).toBe('original')); + }); + + it('does not report success when the client cancels while the journal is being finalized', async () => { + const controller = new AbortController(); + const d = deps({}, { 'a.txt': 'original' }); + let release = (): void => undefined; + slowFinalization(d, new Promise((r) => (release = r)), async () => undefined, () => controller.abort()); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + { ...d, signal: controller.signal }, + ); + release(); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.error?.message).toContain('cancelled'); + }); + + it('fails and rolls back a successful script whose write is still running after the grace', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', commitDelayMs: 60, honorAbortInCommit: false }); + const sandbox: Sandbox = { + run: async (_code, opts) => { + void opts.onCall('write', { path: 'late.txt', content: 'late' }); + await new Promise((r) => setTimeout(r, 5)); + return { ok: true, value: 'done' }; + }, + }; + const result = await runScript({ code: 'x', transaction: true, timeoutMs: 5_000 }, { ...deps(), tools, sandbox, stopGraceMs: 10 }); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionNotFinalized' }); + expect(result.warnings.join('\n')).toContain('the rollback is pending'); + await vi.waitFor(() => expect(tools.commits).toHaveLength(1)); + await vi.waitFor(() => expect(tools.read('late.txt')).toBeUndefined()); + }); + it('counts policy loading against the deadline and gives the sandbox only the time left', async () => { let clock = 0; const budgets: number[] = []; diff --git a/src/core/run.ts b/src/core/run.ts index ddc3185..b3b35e0 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -1,5 +1,5 @@ import { Dispatcher, type StopReason } from './dispatcher.js'; -import { errorMessage } from './errors.js'; +import { TransactionFinalizeError, errorMessage } from './errors.js'; import { DEFAULT_RUN_TIMEOUT_MS, MAX_RUN_TIMEOUT_MS, type RunArgs } from './schemas.js'; import type { CallLogEntry, @@ -216,6 +216,8 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise | undefined; + /** Set once the journal was committed (durably or not); nothing after may roll back or finalize again. */ + let finalized = false; const stop = (reason: StopReason): void => { if (stopReason !== undefined) return; @@ -282,10 +284,50 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise journal.dispose()); + try { + // Bounded like the rest of the run: the script's deadline plus the stop grace, and cancellation. + const r = await bounded(() => finalizing, { signal: controller.signal, ms: deadline + graceMs - now() }); + finalized = true; + if (!r.done) { + const why = r.why === 'aborted' ? 'the run was cancelled' : 'the run reached its time limit'; + error = { + kind: 'internal', + name: 'TransactionIndeterminate', + message: `${why} while the transaction was being finalized; the outcome is not known yet`, + }; + warnings.push('the writes of this run are kept if the finalization still completes, and rolled back if it fails.'); + // Not a rollback: the finalization is left to end, and only a failed commit is undone. + void finalizing.catch((err: unknown) => { + if (err instanceof TransactionFinalizeError && err.committed) return undefined; + return journal.rollback(); + }).catch(() => undefined); + } + } catch (err) { + if (err instanceof TransactionFinalizeError && err.committed) { + finalized = true; + error = { kind: 'internal', name: 'TransactionIndeterminate', message: err.message }; + warnings.push('the writes of this run are on disk and were not rolled back, but they may not survive a power loss or crash.'); + } else { + error = { kind: 'internal', name: 'TransactionNotFinalized', message: `the transaction could not be finalized: ${errorMessage(err)}` }; + } + } + } + } + if (tx && error && !finalized) { const rollback = await rollbackBounded(tx, journalBusy, rollbackMs, warnings); journalBusy = rollback.done; rolledBack = rollback.report; @@ -309,7 +351,7 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise(req: RunRequest, deps: RunDeps

): Promise undefined).then(() => journal.dispose()).catch(() => undefined); diff --git a/src/core/types.ts b/src/core/types.ts index 34193eb..acf6462 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -499,7 +499,11 @@ export interface RollbackReport { export interface Transaction { /** Restores every journaled file whose content is still what this run wrote. */ rollback(): Promise; - /** Releases the journal (keeps the changes). Idempotent. */ + /** + * Finalizes the journal (keeps the changes): once it resolves, no recovery + * can undo them. Idempotent; a no-op after a rollback. Rejects with a + * `TransactionFinalizeError` when finalization failed. + */ dispose(): Promise; } diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts new file mode 100644 index 0000000..0568d85 --- /dev/null +++ b/src/tools/bash.test.ts @@ -0,0 +1,166 @@ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { BashContainment, BashResult, PolicySnapshot, SessionContext } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { bootstrapEnv } from './bash.js'; +import { NodeToolRuntime } from './runtime.js'; +import { containmentUnavailableReason } from './sandbox.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let ctx: SessionContext; +let seq = 0; + +function policyWith(bashContainment: BashContainment): PolicySnapshot { + return { host: 'generic', bashContainment, protectedPaths: [], payload: null }; +} + +async function bash( + command: string, + opts: { timeoutMs?: number; signal?: AbortSignal; containment?: BashContainment; capBytes?: number } = {}, +): Promise { + const rt = new NodeToolRuntime({ stateDir: path.join(base, 'state'), ...(opts.capBytes ? { bashOutputCapBytes: opts.capBytes } : {}) }); + const prepared = await rt.prepare( + { id: `c${++seq}`, tool: 'bash', args: { command, ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) } }, + ctx, + policyWith(opts.containment ?? { mode: 'none' }), + ); + const result = await rt.commit(prepared, opts.signal ?? new AbortController().signal); + if (!('exitCode' in result)) throw new Error('not a bash result'); + return result; +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function eventually(check: () => boolean, ms = 3000): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (check()) return true; + await new Promise((r) => setTimeout(r, 50)); + } + return check(); +} + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + ctx = makeContext(ws); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe.skipIf(IS_WINDOWS)('bash', () => { + it('returns exit code and output; a non-zero exit is a result', async () => { + const r = await bash('echo out; echo err >&2; exit 3'); + expect(r).toEqual({ exitCode: 3, signal: null, stdout: 'out\n', stderr: 'err\n', truncated: false, timedOut: false }); + }); + + it('kills the whole process group on timeout, grandchildren included', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $! > bg.pid; sleep 100', { timeoutMs: 500 }); + expect(r.timedOut).toBe(true); + expect(r.signal).toBe('SIGKILL'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(readFileSync(path.join(ws, 'bg.pid'), 'utf8')); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('does not leave background processes behind after a normal exit', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $!'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(r.stdout.trim()); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('never starts when the signal is already aborted', async () => { + const ac = new AbortController(); + ac.abort(); + await expect(bash('touch spawned.txt', { signal: ac.signal })).rejects.toMatchObject({ code: 'cancelled' }); + expect(existsSync(path.join(ws, 'spawned.txt'))).toBe(false); + }); + + it('stops a running command on abort', async () => { + const ac = new AbortController(); + setTimeout(() => ac.abort(), 200); + const started = Date.now(); + await expect(bash('sleep 30', { signal: ac.signal })).rejects.toBeInstanceOf(ToolError); + expect(Date.now() - started).toBeLessThan(5000); + }); + + it('caps stdout and stderr', async () => { + const r = await bash("head -c 5000 /dev/zero | tr '\\0' a; head -c 3000 /dev/zero | tr '\\0' b >&2", { capBytes: 1000 }); + expect(r.stdout).toBe('a'.repeat(1000)); + expect(r.stderr).toBe('b'.repeat(1000)); + expect(r.truncated).toBe(true); + }); + + it('does not report a timeout when the shell exited and only its output was draining', async () => { + const r = await bash('sleep 5 & exit 0', { timeoutMs: 100 }); + expect([r.exitCode, r.timedOut]).toEqual([0, false]); + }); + + it('gives the sandbox bootstrap shell no startup files, exported functions or shell options', () => { + const env = bootstrapEnv({ PATH: '/bin', BASH_ENV: '/x', ENV: '/y', SHELLOPTS: 'xtrace', BASHOPTS: 'extglob', 'BASH_FUNC_example%%': 'unused' }); + expect(env).toEqual({ PATH: '/bin' }); + }); + + it('refuses a containment with a relative writable root', async () => { + await expect(bash('true', { containment: { mode: 'sandbox', readOnly: false, writableRoots: ['rel'], network: false } })).rejects.toMatchObject({ + code: 'containment-unavailable', + }); + }); +}); + +const unavailable = await containmentUnavailableReason(); +if (unavailable !== null) { + // Logged so a CI run shows why the containment tests were skipped. + console.log(`bash containment tests skipped: ${unavailable}`); +} + +describe.skipIf(unavailable !== null)('bash containment (OS sandbox)', () => { + const readOnly: BashContainment = { mode: 'sandbox', readOnly: true, writableRoots: [], network: false }; + + it('blocks writes under a read-only sandbox', async () => { + const r = await bash('touch x', { containment: readOnly }); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(ws, 'x'))).toBe(false); + }); + + it('allows writes only under the writable roots', async () => { + const r = await bash(`touch y && touch ${JSON.stringify(path.join(base, 'z'))}`, { + containment: { mode: 'sandbox', readOnly: false, writableRoots: [ws], network: false }, + }); + expect(existsSync(path.join(ws, 'y'))).toBe(true); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(base, 'z'))).toBe(false); + }); + + it('blocks the network when network is off', async () => { + const r = await bash("exec 3<>/dev/tcp/1.1.1.1/80 && echo connected", { containment: readOnly, timeoutMs: 15_000 }); + expect(r.exitCode).not.toBe(0); + expect(r.stdout).not.toContain('connected'); + }); + + it('kills the sandboxed command on timeout', async () => { + const started = Date.now(); + const r = await bash('sleep 100', { containment: readOnly, timeoutMs: 1000 }); + expect(r.timedOut).toBe(true); + expect(Date.now() - started).toBeLessThan(8000); + }); +}); diff --git a/src/tools/bash.ts b/src/tools/bash.ts new file mode 100644 index 0000000..bc6c7a7 --- /dev/null +++ b/src/tools/bash.ts @@ -0,0 +1,206 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import type { BashEffect, BashResult } from '../core/types.js'; +import { withSandbox } from './sandbox.js'; + +/** Default `bash` timeout. */ +export const DEFAULT_BASH_TIMEOUT_MS = 120_000; +/** Largest `bash` timeout. */ +export const MAX_BASH_TIMEOUT_MS = 600_000; +/** Bytes kept of each of stdout and stderr. */ +export const DEFAULT_OUTPUT_CAP_BYTES = 1024 * 1024; +/** After the shell exits, how long to wait for the output pipes to close. */ +const DRAIN_MS = 200; + +/** Quotes a string for POSIX sh as one word. */ +export function shellQuote(s: string): string { + return `'${s.replace(/'/g, `'\\''`)}'`; +} + +let cachedShell: string | null | undefined; + +/** The bash to run commands with: `/bin/bash` or `bash` on PATH; Git Bash on Windows. Null when none. */ +export function findBash(): string | null { + if (cachedShell !== undefined) return cachedShell; + if (process.platform === 'win32') { + const candidates = [ + process.env['ProgramFiles'] && path.join(process.env['ProgramFiles'], 'Git', 'bin', 'bash.exe'), + process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'), + process.env['LOCALAPPDATA'] && path.join(process.env['LOCALAPPDATA'], 'Programs', 'Git', 'bin', 'bash.exe'), + ].filter((p): p is string => typeof p === 'string' && p !== ''); + cachedShell = candidates.find((p) => existsSync(p)) ?? null; + return cachedShell; + } + if (existsSync('/bin/bash')) cachedShell = '/bin/bash'; + else { + const which = spawnSync('sh', ['-c', 'command -v bash'], { encoding: 'utf8' }); + const found = which.status === 0 ? which.stdout.trim() : ''; + cachedShell = found !== '' ? found : null; + } + return cachedShell; +} + +class Capture { + readonly #chunks: Buffer[] = []; + #size = 0; + truncated = false; + + constructor(private readonly cap: number) {} + + push(chunk: Buffer): void { + if (this.#size >= this.cap) { + this.truncated = true; + return; + } + const room = this.cap - this.#size; + const kept = chunk.length > room ? chunk.subarray(0, room) : chunk; + if (kept.length < chunk.length) this.truncated = true; + this.#chunks.push(kept); + this.#size += kept.length; + } + + text(): string { + // A cut in the middle of a multi-byte character becomes U+FFFD. + return Buffer.concat(this.#chunks).toString('utf8'); + } +} + +/** Kills the whole process group of `child` (POSIX) or its tree (Windows). */ +function killGroup(child: ChildProcess): void { + const pid = child.pid; + if (pid === undefined) return; + if (process.platform === 'win32') { + spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }); + return; + } + try { + process.kill(-pid, 'SIGKILL'); + } catch { + try { + child.kill('SIGKILL'); + } catch { + // Already gone. + } + } +} + +export interface BashRunOptions { + readonly outputCapBytes?: number; + /** Paths a sandboxed command may never write (from the host's protected paths). */ + readonly denyWrite?: readonly string[]; +} + +export function spawnAndWait( + argv: readonly string[], + env: NodeJS.ProcessEnv, + cwd: string, + timeoutMs: number, + signal: AbortSignal, + cap: number, +): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new ToolError('cancelled', 'the run was stopped before bash started')); + return; + } + const [file, ...args] = argv; + if (file === undefined) { + reject(new ToolError('tool-error', 'empty command line')); + return; + } + const child = spawn(file, args, { + cwd, + env, + stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + windowsHide: true, + }); + const out = new Capture(cap); + const err = new Capture(cap); + child.stdout?.on('data', (c: Buffer) => out.push(c)); + child.stderr?.on('data', (c: Buffer) => err.push(c)); + + let timedOut = false; + let settled = false; + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + let drainTimer: NodeJS.Timeout | undefined; + + const finish = (): void => { + if (settled || !exit) return; + settled = true; + clearTimeout(timer); + if (drainTimer) clearTimeout(drainTimer); + signal.removeEventListener('abort', onAbort); + // No process of the call outlives it: background children are killed too. + killGroup(child); + if (signal.aborted && !timedOut) { + reject(new ToolError('cancelled', 'bash was stopped because the run stopped')); + return; + } + resolve({ + exitCode: exit.code, + signal: exit.signal, + stdout: out.text(), + stderr: err.text(), + truncated: out.truncated || err.truncated, + timedOut, + }); + }; + const onAbort = (): void => killGroup(child); + const timer = setTimeout(() => { + // The shell already exited: only its output was still draining. + if (exit) return finish(); + timedOut = true; + killGroup(child); + }, timeoutMs); + signal.addEventListener('abort', onAbort, { once: true }); + + child.once('error', (e) => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + reject(new ToolError('tool-error', `bash failed to start: ${e.message}`)); + }); + child.once('exit', (code, sig) => { + exit = { code, signal: sig }; + // Background children may keep the pipes open; do not wait for them long. + drainTimer = setTimeout(finish, DRAIN_MS); + }); + child.once('close', () => finish()); + }); +} + +/** + * The environment of the sandbox bootstrap: the wrapper runs ` -c` + * before the sandbox applies, so nothing may make that shell run code of its + * own first (startup files, exported functions, shell options). + */ +export function bootstrapEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const out: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(env)) { + if (key === 'BASH_ENV' || key === 'ENV' || key === 'SHELLOPTS' || key === 'BASHOPTS' || key.startsWith('BASH_FUNC_')) continue; + out[key] = value; + } + return out; +} + +/** Runs a prepared `bash` effect. */ +export async function runBash(effect: BashEffect, signal: AbortSignal, opts: BashRunOptions = {}): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + const shell = findBash(); + if (shell === null) { + throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); + } + const cap = opts.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES; + const containment = effect.containment; + if (containment.mode === 'none') { + return spawnAndWait([shell, '-c', effect.command], process.env, effect.cwd, effect.timeoutMs, signal, cap); + } + return withSandbox(effect.command, shell, effect.cwd, containment, opts.denyWrite ?? [], signal, (wrapped) => { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + return spawnAndWait(wrapped.argv, bootstrapEnv({ ...process.env, ...wrapped.env }), effect.cwd, effect.timeoutMs, signal, cap); + }); +} diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts new file mode 100644 index 0000000..d7ec748 --- /dev/null +++ b/src/tools/diff.test.ts @@ -0,0 +1,76 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { quotePath, unifiedDiff } from './diff.js'; + +const hasGit = spawnSync('git', ['--version']).status === 0; + +/** Applies `diff` with `git apply` in a scratch repo and returns the result. */ +function gitApply(before: string | null, diff: string): string { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-diff-')); + try { + if (before !== null) writeFileSync(path.join(dir, 'f.txt'), before); + writeFileSync(path.join(dir, 'p.diff'), diff); + const r = spawnSync('git', ['-c', 'core.autocrlf=false', 'apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); + if (r.status !== 0) throw new Error(`git apply failed: ${r.stderr}\n${diff}`); + return readFileSync(path.join(dir, 'f.txt'), 'utf8'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function randomText(rand: () => number): string { + const lines: string[] = []; + const n = Math.floor(rand() * 30); + for (let i = 0; i < n; i++) lines.push(['a', 'b', 'c', 'd', '', 'x y'][Math.floor(rand() * 6)] ?? ''); + return lines.join('\n') + (rand() < 0.5 ? '\n' : ''); +} + +function mulberry(seed: number): () => number { + let t = seed; + return () => { + t = (t + 0x6d2b79f5) | 0; + let r = Math.imul(t ^ (t >>> 15), 1 | t); + r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r; + return ((r ^ (r >>> 14)) >>> 0) / 4294967296; + }; +} + +describe('unifiedDiff', () => { + it('produces a standard hunk with context', () => { + const diff = unifiedDiff('src/a.ts', 'one\ntwo\nthree\n', 'one\n2\nthree\n'); + expect(diff).toBe('--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1,3 +1,3 @@\n one\n-two\n+2\n three\n'); + }); + + it('marks creation and a missing final newline', () => { + expect(unifiedDiff('n.txt', null, 'hi')).toBe('--- /dev/null\n+++ b/n.txt\n@@ -0,0 +1,1 @@\n+hi\n\\ No newline at end of file\n'); + expect(unifiedDiff('n.txt', 'same\n', 'same\n')).toBe(''); + }); + + it.skipIf(!hasGit)('round-trips through git apply on random edits', () => { + const rand = mulberry(42); + for (let i = 0; i < 150; i++) { + const before = randomText(rand); + const after = randomText(rand); + if (before === after) continue; + const diff = unifiedDiff('f.txt', before, after); + expect(gitApply(before, diff)).toBe(after); + } + }); +}); + +describe('diff headers', () => { + it('quotes a path that a quote, a backslash or a control character would change', () => { + expect(unifiedDiff('plain name.txt', 'a\n', 'b\n')).toContain('--- a/plain name.txt\n+++ b/plain name.txt\n'); + expect(unifiedDiff('x\n+++ b/y', 'a\n', 'b\n')).toContain('--- "a/x\\n+++ b/y"\n+++ "b/x\\n+++ b/y"\n'); + expect(quotePath('a/q"b\\c\td')).toBe('"a/q\\"b\\\\c\\td"'); + }); + + it.skipIf(!hasGit)('describes the creation of an empty file in a patch git applies', () => { + const diff = unifiedDiff('f.txt', null, ''); + expect(diff).toContain('new file mode'); + expect(gitApply(null, diff)).toBe(''); + }); +}); diff --git a/src/tools/diff.ts b/src/tools/diff.ts new file mode 100644 index 0000000..1659203 --- /dev/null +++ b/src/tools/diff.ts @@ -0,0 +1,198 @@ +/** + * Unified diff of two texts (line based, Myers O(ND) with a bounded edit + * distance). When the texts differ by more than the bound, the changed middle + * is reported as one replace block, which is wider than the minimal diff but + * never wrong. + */ + +const CONTEXT = 3; +const MAX_EDIT_DISTANCE = 1000; + +interface Line { + readonly text: string; + /** False only for a last line without a trailing newline. */ + readonly eol: boolean; +} + +function splitLines(text: string): Line[] { + if (text === '') return []; + const parts = text.split('\n'); + const last = parts.pop() ?? ''; + const lines: Line[] = parts.map((t) => ({ text: t, eol: true })); + if (last !== '') lines.push({ text: last, eol: false }); + return lines; +} + +type Op = { readonly kind: ' ' | '-' | '+'; readonly line: Line }; + +function same(a: Line | undefined, b: Line | undefined): boolean { + return a !== undefined && b !== undefined && a.text === b.text && a.eol === b.eol; +} + +/** Edit script between a[lo..] and b[lo..] (already trimmed of common prefix/suffix). */ +function myers(a: readonly Line[], b: readonly Line[]): Op[] | null { + const n = a.length; + const m = b.length; + const max = Math.min(n + m, MAX_EDIT_DISTANCE); + const offset = max + 1; + const v = new Int32Array(2 * max + 3); + const trace: Int32Array[] = []; + for (let d = 0; d <= max; d++) { + trace.push(v.slice()); + for (let k = -d; k <= d; k += 2) { + let x: number; + if (k === -d || (k !== d && (v[offset + k - 1] ?? 0) < (v[offset + k + 1] ?? 0))) x = v[offset + k + 1] ?? 0; + else x = (v[offset + k - 1] ?? 0) + 1; + let y = x - k; + while (x < n && y < m && same(a[x], b[y])) { + x++; + y++; + } + v[offset + k] = x; + if (x >= n && y >= m) { + // Backtrack. + const ops: Op[] = []; + let cx = n; + let cy = m; + for (let dd = d; dd > 0; dd--) { + const pv = trace[dd] ?? v; + const kk = cx - cy; + let prevK: number; + if (kk === -dd || (kk !== dd && (pv[offset + kk - 1] ?? 0) < (pv[offset + kk + 1] ?? 0))) prevK = kk + 1; + else prevK = kk - 1; + const prevX = pv[offset + prevK] ?? 0; + const prevY = prevX - prevK; + while (cx > prevX && cy > prevY) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + if (cx === prevX) { + cy--; + ops.push({ kind: '+', line: b[cy] as Line }); + } else { + cx--; + ops.push({ kind: '-', line: a[cx] as Line }); + } + } + while (cx > 0 && cy > 0) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + return ops.reverse(); + } + } + } + return null; +} + +function editScript(a: readonly Line[], b: readonly Line[]): Op[] { + let start = 0; + while (start < a.length && start < b.length && same(a[start], b[start])) start++; + let endA = a.length; + let endB = b.length; + while (endA > start && endB > start && same(a[endA - 1], b[endB - 1])) { + endA--; + endB--; + } + const midA = a.slice(start, endA); + const midB = b.slice(start, endB); + const middle = myers(midA, midB) ?? [ + ...midA.map((line): Op => ({ kind: '-', line })), + ...midB.map((line): Op => ({ kind: '+', line })), + ]; + return [ + ...a.slice(0, start).map((line): Op => ({ kind: ' ', line })), + ...middle, + ...a.slice(endA).map((line): Op => ({ kind: ' ', line })), + ]; +} + +function renderLine(op: Op): string { + const out = `${op.kind}${op.line.text}\n`; + return op.line.eol ? out : `${out}\\ No newline at end of file\n`; +} + +/** + * Unified diff from `before` to `after`. `before === null` means the file did + * not exist. `file` is shown as `a/` and `b/`. Returns '' when + * nothing changed. + */ +export function unifiedDiff(file: string, before: string | null, after: string): string { + if (before !== null && before === after) return ''; + const a = before === null ? [] : splitLines(before); + const b = splitLines(after); + const ops = editScript(a, b); + if (ops.every((op) => op.kind === ' ')) { + // Only possible when before is null and after is empty: a creation has no hunk, so git's header says it. + return `diff --git ${quotePath(`a/${file}`)} ${quotePath(`b/${file}`)}\nnew file mode 100644\n`; + } + const header = `--- ${before === null ? '/dev/null' : quotePath(`a/${file}`)}\n+++ ${quotePath(`b/${file}`)}\n`; + + let out = header; + let i = 0; + // Line counters at the start of ops[i]. + const posA: number[] = []; + const posB: number[] = []; + let la = 0; + let lb = 0; + for (const op of ops) { + posA.push(la); + posB.push(lb); + if (op.kind !== '+') la++; + if (op.kind !== '-') lb++; + } + while (i < ops.length) { + while (i < ops.length && ops[i]?.kind === ' ') i++; + if (i >= ops.length) break; + const hunkStart = Math.max(0, i - CONTEXT); + let end = i; + // Extend while changes are within 2*CONTEXT of each other. + for (;;) { + while (end < ops.length && ops[end]?.kind !== ' ') end++; + let next = end; + while (next < ops.length && ops[next]?.kind === ' ') next++; + if (next < ops.length && next - end <= 2 * CONTEXT) { + end = next; + continue; + } + break; + } + const hunkEnd = Math.min(ops.length, end + CONTEXT); + const slice = ops.slice(hunkStart, hunkEnd); + const countA = slice.filter((op) => op.kind !== '+').length; + const countB = slice.filter((op) => op.kind !== '-').length; + const startA = countA === 0 ? (posA[hunkStart] ?? 0) : (posA[hunkStart] ?? 0) + 1; + const startB = countB === 0 ? (posB[hunkStart] ?? 0) : (posB[hunkStart] ?? 0) + 1; + out += `@@ -${startA},${countA} +${startB},${countB} @@\n`; + out += slice.map(renderLine).join(''); + i = hunkEnd; + } + return out; +} + +/** Diff header for a binary change. */ +export function binaryDiff(file: string, existed: boolean): string { + return `--- ${existed ? quotePath(`a/${file}`) : '/dev/null'}\n+++ ${quotePath(`b/${file}`)}\nBinary files differ\n`; +} + +const ESCAPES: Record = { '"': '\\"', '\\': '\\\\', '\t': '\\t', '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f', '\v': '\\v', '\x07': '\\a' }; + +/** + * A path as git writes it in a patch header: unchanged when plain, else in + * double quotes with C escapes, so a quote, a backslash, a control character + * or a trailing space cannot change which file the header names. + */ +export function quotePath(p: string): string { + if (!/["\\\x00-\x1f\x7f]|\s$/.test(p)) return p; + let out = ''; + for (const ch of p) { + const code = ch.charCodeAt(0); + const escaped = ESCAPES[ch]; + if (escaped !== undefined) out += escaped; + else if (code < 0x20 || code === 0x7f) out += `\\${code.toString(8).padStart(3, '0')}`; + else out += ch; + } + return `"${out}"`; +} diff --git a/src/tools/edit-match.test.ts b/src/tools/edit-match.test.ts new file mode 100644 index 0000000..30cf2f9 --- /dev/null +++ b/src/tools/edit-match.test.ts @@ -0,0 +1,133 @@ +// Test cases ported from Turnpack's test/edit-match.test.mjs +// (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). +// Modified by the agent-code-mode authors: vitest, typed, and checks of the +// `matched` text this port adds. +import { describe, expect, it } from 'vitest'; +import { applySearchReplace, type EditApplied, type EditMiss, type EditOutcome } from './edit-match.js'; + +const apply = (text: string, search: string, replace: string, all = false): EditOutcome => applySearchReplace(text, search, replace, all); + +function ok(out: EditOutcome): EditApplied { + if (!out.ok) throw new Error(`expected a match: ${out.message}`); + return out; +} +function miss(out: EditOutcome): EditMiss { + if (out.ok) throw new Error(`expected no match, got ${out.how}`); + return out; +} + +describe('edit matching (ported from Turnpack)', () => { + it('uses the exact text when it is there, and says where an ambiguous one occurs', () => { + const text = 'a = 1\nb = 2\na = 1\n'; + const once = ok(apply(text, 'b = 2', 'b = 3')); + expect([once.how, once.count, once.text, once.matched]).toEqual(['exact', 1, 'a = 1\nb = 3\na = 1\n', 'b = 2']); + + const twice = miss(apply(text, 'a = 1', 'a = 9')); + expect(twice.kind).toBe('ambiguous'); + expect(twice.message).toMatch(/matches 2 places \(lines 1, 3\)/); + + const all = ok(apply(text, 'a = 1', 'a = 9', true)); + expect([all.count, all.text]).toEqual([2, 'a = 9\nb = 2\na = 9\n']); + + // The replacement is inserted as written: no "$&" or "$1" expansion. + expect(ok(apply('x = 1\n', 'x = 1', "x = '$&$1'")).text).toBe("x = '$&$1'\n"); + expect(miss(apply('x\n', '', 'y')).kind).toBe('empty'); + }); + + it("matches LF text against a CRLF file and keeps the file's line endings", () => { + const out = ok(apply('a\r\nb\r\nc\r\n', 'a\nb', 'x\ny')); + expect([out.how, out.text, out.matched]).toEqual(['line-endings', 'x\r\ny\r\nc\r\n', 'a\r\nb']); + }); + + it('finds a block whose indentation was remembered wrongly, and re-indents what replaces it', () => { + const file = 'function f() {\n if (x) {\n return 1;\n }\n}\n'; + const out = ok(apply(file, 'if (x) {\n return 1;\n}', 'if (x) {\n log();\n return 2;\n}')); + expect(out.how).toBe('indentation'); + expect(out.text).toBe('function f() {\n if (x) {\n log();\n return 2;\n }\n}\n'); + expect(out.matched).toBe(' if (x) {\n return 1;\n }'); + + // Spaces remembered where the file has tabs: converted level by level. + const tabbed = 'class A {\n\trun() {\n\t\treturn 1;\n\t}\n}\n'; + const tabs = ok(apply(tabbed, ' run() {\n return 1;\n }', ' run() {\n if (ok) {\n return 2;\n }\n }')); + expect(tabs.how).toBe('indentation'); + expect(tabs.text).toBe('class A {\n\trun() {\n\t\tif (ok) {\n\t\t\treturn 2;\n\t\t}\n\t}\n}\n'); + + // And the other way round, in a CRLF file, with the trailing newline included in the search. + const crlf = ' a();\r\n b();\r\nend\r\n'; + const mixed = ok(apply(crlf, '\ta();\n\tb();\n', '\ta();\n\tc();\n')); + expect(mixed.text).toBe(' a();\r\n c();\r\nend\r\n'); + }); + + it('ignores line numbers copied from a listing, trailing spaces, and typographic quotes', () => { + const file = 'export const TAX = 0.08;\n\nexport function tax(n) {\n return n * TAX;\n}\n'; + const listing = ok( + apply(file, '3 | export function tax(n) {\n4 | return n * TAX;\n5 | }', '3 | export function tax(n) {\n4 | return round(n * TAX);\n5 | }'), + ); + expect(listing.how).toBe('line-numbers'); + expect(listing.text).toBe('export const TAX = 0.08;\n\nexport function tax(n) {\n return round(n * TAX);\n}\n'); + + // A file that really does contain "12 | x" is matched exactly, not stripped. + expect(ok(apply('12 | x\n', '12 | x', '13 | y')).how).toBe('exact'); + + const spaced = ok(apply('foo(); \nbar();\n', 'foo();\nbar();', 'baz();')); + expect([spaced.how, spaced.text, spaced.matched]).toEqual(['trailing-whitespace', 'baz();\n', 'foo(); \nbar();']); + + const quoted = ok(apply(' const s = “hello”; // it’s\n', 'const s = "hello"; // it\'s', 'const s = "bye";')); + expect([quoted.how, quoted.text, quoted.matched]).toEqual(['punctuation', ' const s = "bye";\n', ' const s = “hello”; // it’s']); + }); + + it('never picks between two places that only match loosely', () => { + const file = 'if (a) {\n go();\n}\nif (b) {\n go();\n}\n'; + const out = miss(apply(file, ' go();', ' stop();')); + expect(out.kind).toBe('ambiguous'); + expect(out.message).toMatch(/matches 2 places \(lines 2, 5\) when indentation is ignored/); + + const all = ok(apply(file, ' go();', ' stop();', true)); + expect(all.text).toBe('if (a) {\n stop();\n}\nif (b) {\n stop();\n}\n'); + + // Blank lines alone are not a place. + expect(miss(apply('a\n\n\nb\n', ' \n ', 'x')).kind).toBe('not-found'); + }); + + it('shows the nearest text and the first difference when nothing matches', () => { + const file = [ + "import { TAX } from './rates.js';", + '', + 'export function invoiceTotal(subtotal) {', + ' const tax = Number((subtotal * TAX).toFixed(2));', + ' return subtotal + tax;', + '}', + '', + ].join('\n'); + const out = miss(apply(file, 'export function invoiceTotal(subtotal) {\n const tax = subtotal * TAX;\n return subtotal + tax;\n}', 'x')); + expect(out.kind).toBe('not-found'); + expect(out.message).toMatch(/closest text is lines 3-6 \(3 of 4 line\(s\) identical/); + expect(out.message).toMatch(/ 4 \| {3}const tax = Number\(\(subtotal \* TAX\)\.toFixed\(2\)\);/); + expect(out.message).toMatch(/First difference, at line 4:/); + expect(out.message).toMatch(/search has: " {2}const tax = subtotal \* TAX;"/); + expect(out.message).toMatch(/file has: {3}" {2}const tax = Number/); + + const nowhere = miss(apply(file, 'class Zebra extends Animal {}', 'x')); + expect(nowhere.message).toMatch(/nothing close to it is in the file \(7 lines\)/); + }); +}); + +describe('edit matching guards', () => { + it('treats overlapping occurrences as two places', () => { + expect(miss(apply('aaa', 'aa', 'b')).kind).toBe('ambiguous'); + expect(miss(apply('x\nx\nx\n', 'x\nx', 'y')).kind).toBe('ambiguous'); + expect(miss(apply('x\nx\nx\n', ' x\n x', 'y')).kind).toBe('ambiguous'); + }); + + it('refuses an indentation match where one indent of the search stands for two in the file', () => { + const out = miss(apply('\tif (a) {\n\t\tb();\n', 'if (a) {\nb();', 'if (a) {\nc();')); + expect(out.kind).toBe('ambiguous'); + expect(out.message).toMatch(/indentation/); + }); + + it('refuses an edit whose result would exceed the size limit', () => { + expect(miss(applySearchReplace('a b a', 'a', 'x'.repeat(100), true, 50)).kind).toBe('too-large'); + expect(miss(applySearchReplace(' a\n b\n', 'a\nb', 'x'.repeat(100), false, 50)).kind).toBe('too-large'); + expect(ok(applySearchReplace('a b a', 'a', 'xy', true, 50)).text).toBe('xy b xy'); + }); +}); diff --git a/src/tools/edit-match.ts b/src/tools/edit-match.ts new file mode 100644 index 0000000..9dbc4dc --- /dev/null +++ b/src/tools/edit-match.ts @@ -0,0 +1,525 @@ +/* + * Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Ported from Turnpack's src/tools/edit-match.ts + * (https://github.com/OnlyTerp/turnpack, commit b14330d). + * Modified by the agent-code-mode authors: the result also carries the exact + * text that was matched (`matched`), messages name this project's argument + * names, and the patch-hunk helpers that this project does not use were removed. + */ + +/** + * Search/replace matching for `edit`. + * + * A model writes an edit from its memory of a file, and that memory is often right about the + * code and wrong about the bytes: an indent one level off, tabs remembered as spaces, a + * trailing space dropped, the line numbers a listing printed copied along with the code, a curly + * quote typed straight. Refusing each of those costs a full extra turn (re-read, re-send) for a + * difference nobody meant. + * + * So matching is a ladder. The exact text is tried first and wins whenever it is there. Only if + * it is absent are looser comparisons tried, one at a time, each comparing whole lines: + * + * exact → line endings → copied line numbers → trailing whitespace → indentation → punctuation + * + * A looser rung is used only when it identifies the place unambiguously (or `replaceAll` is + * set), and the caller is told which rung matched so the reply can say so. Nothing here guesses + * between two candidate places. + * + * When no rung matches, `describeNearest` finds the most similar region and shows it with line + * numbers and the first differing line, so the next attempt can be written without re-reading. + */ + +export type MatchHow = + | "exact" + | "line-endings" + | "line-numbers" + | "trailing-whitespace" + | "indentation" + | "punctuation"; + +export interface EditApplied { + ok: true; + text: string; + how: MatchHow; + count: number; + /** The exact text of the file that the first match covers (what is replaced). */ + matched: string; +} + +export interface EditMiss { + ok: false; + kind: "empty" | "not-found" | "ambiguous" | "too-large"; + /** Complete, model-readable explanation, without the file name. */ + message: string; +} + +export type EditOutcome = EditApplied | EditMiss; + +/** What a looser match ignored, in the words used in replies. */ +export const HOW_LABEL: Record = { + exact: "exact", + "line-endings": "line endings", + "line-numbers": "line numbers copied from a listing", + "trailing-whitespace": "trailing whitespace", + indentation: "indentation", + punctuation: "indentation and typographic quotes or dashes", +}; + +interface FileLine { + /** Offset of the first character of the line. */ + start: number; + /** Offset just past the last character before the line ending. */ + bodyEnd: number; + /** Offset just past the line ending (equal to bodyEnd on a last line with none). */ + end: number; + body: string; +} + +function splitLines(text: string): FileLine[] { + const lines: FileLine[] = []; + let pos = 0; + for (;;) { + const nl = text.indexOf("\n", pos); + if (nl === -1) { + lines.push({ start: pos, bodyEnd: text.length, end: text.length, body: text.slice(pos) }); + return lines; + } + const bodyEnd = nl > pos && text[nl - 1] === "\r" ? nl - 1 : nl; + lines.push({ start: pos, bodyEnd, end: nl + 1, body: text.slice(pos, bodyEnd) }); + pos = nl + 1; + } +} + +function lineNumberAt(lines: FileLine[], offset: number): number { + let lo = 0; + let hi = lines.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if ((lines[mid]?.start ?? 0) <= offset) lo = mid; + else hi = mid - 1; + } + return lo + 1; +} + +function occurrences(haystack: string, needle: string): number[] { + const found: number[] = []; + if (!needle) return found; + let from = 0; + for (;;) { + const at = haystack.indexOf(needle, from); + if (at === -1) return found; + found.push(at); + from = at + needle.length; + } +} + +function listLines(numbers: number[]): string { + const shown = numbers.slice(0, 8).join(", "); + return numbers.length > 8 ? `${shown}, and ${numbers.length - 8} more` : shown; +} + +function ambiguous(lineNumbers: number[], ignoring?: string): EditMiss { + return { + ok: false, + kind: "ambiguous", + message: + `search text matches ${lineNumbers.length} places (lines ${listLines(lineNumbers)})` + + `${ignoring ? ` when ${ignoring} is ignored` : ""}. ` + + "Add a neighbouring line to oldString so it names one place, or pass replaceAll: true.", + }; +} + +// " 12 | code" is how Turnpack's pack prints a line; " 12\tcode" is `cat -n`; "12→code" is another +// common listing style. A search made only of such lines was copied from a listing. +const GUTTER = /^[>\s]*\d+(?: \|(?: |$)|\t|→)/; + +function stripGutter(lines: string[]): string[] | null { + const meaningful = lines.filter((line) => line.trim() !== ""); + if (meaningful.length === 0 || !meaningful.every((line) => GUTTER.test(line))) return null; + return lines.map((line) => line.replace(GUTTER, "")); +} + +const PUNCTUATION: Array<[RegExp, string]> = [ + [/[‘’‚‛′]/g, "'"], + [/[“”„‟″]/g, '"'], + [/[‐‑‒–—―−]/g, "-"], + [/[             ]/g, " "], + [/…/g, "..."], +]; + +function foldPunctuation(value: string): string { + let out = value; + for (const [pattern, plain] of PUNCTUATION) out = out.replace(pattern, plain); + return out; +} + +function leadingWhitespace(value: string): string { + return /^[ \t]*/.exec(value)?.[0] ?? ""; +} + +/** + * Rewrites the indentation of replacement lines from the way the model wrote the block to the + * way the file has it. + * + * The matched lines are the evidence: line k of the search was written with one indent and the + * file has another, which gives a small dictionary from "the model's indent" to "the file's + * indent" (no indent → one tab, four spaces → two tabs). A replacement line whose indent is in + * the dictionary is translated outright. One that is deeper than anything matched is + * extrapolated from the step between two matched depths, and failing that keeps its extra + * indentation on top of the nearest known depth. + */ +function reindentLike(replaceLines: string[], searchLines: string[], fileLines: string[]): string[] | null { + const known = new Map(); + for (let k = 0; k < searchLines.length; k++) { + const searchLine = searchLines[k] ?? ""; + const fileLine = fileLines[k] ?? ""; + if (searchLine.trim() === "" || fileLine.trim() === "") continue; + const indent = leadingWhitespace(searchLine); + const fileIndent = leadingWhitespace(fileLine); + const seen = known.get(indent); + // One indent of the search standing for two of the file: no translation is right for both. + if (seen !== undefined && seen !== fileIndent) return null; + known.set(indent, fileIndent); + } + if (known.size === 0 || [...known].every(([from, to]) => from === to)) return replaceLines; + + // One level of nesting, as the model writes it and as the file writes it. + const depths = [...known.keys()].sort((a, b) => a.length - b.length); + let step: { from: number; to: string } | null = null; + for (let i = 1; i < depths.length && !step; i++) { + const shallow = depths[i - 1] ?? ""; + const deep = depths[i] ?? ""; + const fileShallow = known.get(shallow) ?? ""; + const fileDeep = known.get(deep) ?? ""; + if (deep.startsWith(shallow) && fileDeep.startsWith(fileShallow) && fileDeep.length > fileShallow.length) { + step = { from: deep.length - shallow.length, to: fileDeep.slice(fileShallow.length) }; + } + } + // With one matched depth and a file that indents with tabs, a level is taken to be the + // smallest extra indent the replacement itself uses. + const extras = replaceLines + .filter((line) => line.trim() !== "") + .map((line) => leadingWhitespace(line)) + .map((indent) => { + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + return base === undefined ? 0 : indent.length - base.length; + }) + .filter((extra) => extra > 0); + const smallestExtra = extras.length > 0 ? Math.min(...extras) : 0; + + return replaceLines.map((line) => { + if (line.trim() === "") return line; + const indent = leadingWhitespace(line); + const rest = line.slice(indent.length); + const direct = known.get(indent); + if (direct !== undefined) return direct + rest; + + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + if (base === undefined) return line; // shallower than anything matched: leave it as written + const fileBase = known.get(base) ?? ""; + const extra = indent.slice(base.length); + if (step && extra.length % step.from === 0) { + return fileBase + step.to.repeat(extra.length / step.from) + rest; + } + if (/^\t+$/.test(fileBase) && /^ +$/.test(extra) && smallestExtra > 0 && extra.length % smallestExtra === 0) { + return fileBase + "\t".repeat(extra.length / smallestExtra) + rest; + } + return fileBase + extra + rest; + }); +} + +interface Rung { + how: MatchHow; + normalize: (line: string) => string; + /** Whether the replacement needs its indentation moved to where the file has it. */ + reindent: boolean; +} + +const RUNGS: Rung[] = [ + { how: "trailing-whitespace", normalize: (line) => line.replace(/[ \t]+$/, ""), reindent: false }, + { how: "indentation", normalize: (line) => line.trim(), reindent: true }, + { how: "punctuation", normalize: (line) => foldPunctuation(line).trim(), reindent: true }, +]; + +function findLineMatches(fileNorm: string[], wanted: string[], overlapping: boolean): number[] { + const hits: number[] = []; + const n = wanted.length; + const first = wanted[0]; + for (let i = 0; i + n <= fileNorm.length; i++) { + if (fileNorm[i] !== first) continue; + let same = true; + for (let k = 1; k < n; k++) { + if (fileNorm[i + k] !== wanted[k]) { + same = false; + break; + } + } + if (same) { + hits.push(i); + // Replacements may not overlap; counting places for uniqueness, they may. + if (!overlapping) i += n - 1; + } + } + return hits; +} + +/** + * Applies one search/replace to `text`. See the file comment for the order of attempts. + */ +export function applySearchReplace( + text: string, + search: string, + replace: string, + replaceAll: boolean, + maxResultLength = Number.MAX_SAFE_INTEGER, +): EditOutcome { + if (!search) { + return { ok: false, kind: "empty", message: "the search text is empty" }; + } + const tooLarge = (): EditMiss => ({ + ok: false, + kind: "too-large", + message: `the edited file would be longer than ${maxResultLength} characters`, + }); + + // Rung 1: the text exactly as written. + let exact = occurrences(text, search); + let how: MatchHow = "exact"; + let exactSearch = search; + let exactReplace = replace; + + // Rung 2: the same text with the file's line endings. + const fileUsesCrlf = text.includes("\r\n"); + const eol = fileUsesCrlf ? "\r\n" : "\n"; + const toFileEol = (value: string): string => { + const lf = value.replace(/\r\n/g, "\n"); + return fileUsesCrlf ? lf.replace(/\n/g, "\r\n") : lf; + }; + if (exact.length === 0 && /\n/.test(search)) { + const alt = toFileEol(search); + if (alt !== search) { + const altHits = occurrences(text, alt); + if (altHits.length > 0) { + exact = altHits; + exactSearch = alt; + exactReplace = toFileEol(replace); + how = "line-endings"; + } + } + } + + let fileLines: FileLine[] | undefined; + const linesOfFile = (): FileLine[] => (fileLines ??= splitLines(text)); + + // A second occurrence overlapping the first still names another place. + const overlap = exact.length === 1 && !replaceAll ? text.indexOf(exactSearch, (exact[0] ?? 0) + 1) : -1; + if (overlap !== -1) exact.push(overlap); + if (exact.length > 1 && !replaceAll) { + return ambiguous(exact.map((offset) => lineNumberAt(linesOfFile(), offset))); + } + if (exact.length > 0) { + if (text.length + exact.length * (exactReplace.length - exactSearch.length) > maxResultLength) return tooLarge(); + return { ok: true, text: text.split(exactSearch).join(exactReplace), how, count: exact.length, matched: exactSearch }; + } + + // From here on the comparison is line by line. + let searchLines = search.replace(/\r\n/g, "\n").split("\n"); + let replaceLines = replace.replace(/\r\n/g, "\n").split("\n"); + + // A search that ends in a newline covers its last line's ending too. + const coversLastEnding = searchLines.length > 1 && searchLines[searchLines.length - 1] === ""; + if (coversLastEnding) searchLines = searchLines.slice(0, -1); + + let gutterStripped = false; + const withoutGutter = stripGutter(searchLines); + if (withoutGutter) { + searchLines = withoutGutter; + replaceLines = replaceLines.map((line) => line.replace(GUTTER, "")); + gutterStripped = true; + } + + const file = linesOfFile(); + const bodies = file.map((line) => line.body); + + const rungs: Rung[] = gutterStripped + ? [{ how: "line-numbers", normalize: (line) => line, reindent: false }, ...RUNGS] + : RUNGS; + + for (const rung of rungs) { + const wanted = searchLines.map(rung.normalize); + // A search that normalises to nothing would match every blank line. + if (wanted.every((line) => line === "")) continue; + const hits = findLineMatches(bodies.map(rung.normalize), wanted, !replaceAll); + if (hits.length === 0) continue; + const label = rung.how; + if (hits.length > 1 && !replaceAll) { + return ambiguous( + hits.map((index) => index + 1), + HOW_LABEL[label], + ); + } + + const pieces: string[] = []; + let cursor = 0; + let length = 0; + let matched: string | undefined; + for (const index of hits) { + const firstLine = file[index]; + const lastLine = file[index + searchLines.length - 1]; + if (!firstLine || !lastLine) continue; + const lines = rung.reindent + ? reindentLike(replaceLines, searchLines, bodies.slice(index, index + searchLines.length)) + : replaceLines; + if (lines === null) { + return { + ok: false, + kind: "ambiguous", + message: + `search text matches at line ${index + 1} when ${HOW_LABEL[label]} is ignored, but one indentation of oldString ` + + "stands for two different indentations of the file there. Write oldString with the file's indentation.", + }; + } + const before = text.slice(cursor, firstLine.start); + const replaced = lines.join(eol); + length += before.length + replaced.length; + if (length > maxResultLength) return tooLarge(); + pieces.push(before, replaced); + cursor = coversLastEnding ? lastLine.end : lastLine.bodyEnd; + matched ??= text.slice(firstLine.start, cursor); + } + if (length + text.length - cursor > maxResultLength) return tooLarge(); + pieces.push(text.slice(cursor)); + return { ok: true, text: pieces.join(""), how: label, count: hits.length, matched: matched ?? "" }; + } + + return { ok: false, kind: "not-found", message: describeNearest(text, searchLines) }; +} + +function tokensOf(line: string): string[] { + return line.match(/[A-Za-z_$][\w$]*|\d+|[^\s\w]/g) ?? []; +} + +/** Token overlap between two lines, 0 to 1. Order-blind, which is fine for "is this the place". */ +function similarity(a: string, b: string): number { + if (a === b) return 1; + const ta = tokensOf(a); + const tb = tokensOf(b); + if (ta.length === 0 || tb.length === 0) return 0; + const counts = new Map(); + for (const token of ta) counts.set(token, (counts.get(token) ?? 0) + 1); + let common = 0; + for (const token of tb) { + const left = counts.get(token); + if (left) { + common += 1; + counts.set(token, left - 1); + } + } + return (2 * common) / (ta.length + tb.length); +} + +const MAX_SCAN_LINES = 60000; +const MAX_SNIPPET_LINES = 12; + +function quoteLine(line: string): string { + const shown = line.length > 160 ? `${line.slice(0, 160)}…` : line; + return JSON.stringify(shown); +} + +/** + * Explains a search that matched nowhere: the most similar region of the file with line + * numbers, how much of it agrees, and the first line that does not. + */ +export function describeNearest(text: string, searchLinesRaw: string[]): string { + const file = splitLines(text); + const total = file.length; + const wanted = searchLinesRaw.map((line) => line.trim()); + const fileTrim = file.slice(0, MAX_SCAN_LINES).map((line) => line.body.trim()); + const nothing = `search text not found, and nothing close to it is in the file (${total} lines). Read the file and write oldString from what is there.`; + + // Find candidate positions through the search's most distinctive line: its longest. + let probe = 0; + for (let k = 1; k < wanted.length; k++) { + if ((wanted[k]?.length ?? 0) > (wanted[probe]?.length ?? 0)) probe = k; + } + const probeLine = wanted[probe] ?? ""; + if (!probeLine) return nothing; + + const candidates: Array<{ start: number; score: number }> = []; + for (let j = 0; j < fileTrim.length; j++) { + const score = similarity(fileTrim[j] ?? "", probeLine); + if (score >= 0.5) candidates.push({ start: j - probe, score }); + } + candidates.sort((a, b) => b.score - a.score); + + let best: { start: number; score: number; identical: number } | null = null; + for (const candidate of candidates.slice(0, 12)) { + let sum = 0; + let identical = 0; + for (let k = 0; k < wanted.length; k++) { + const fileLine = fileTrim[candidate.start + k]; + if (fileLine === undefined) continue; + const score = similarity(fileLine, wanted[k] ?? ""); + sum += score; + if (fileLine === wanted[k]) identical += 1; + } + const mean = sum / wanted.length; + if (!best || mean > best.score) best = { start: candidate.start, score: mean, identical }; + } + if (!best || best.score < 0.35) return nothing; + + const from = Math.max(0, best.start); + const to = Math.min(total, best.start + wanted.length); // exclusive + let firstDiff = -1; + for (let k = 0; k < wanted.length; k++) { + if (fileTrim[best.start + k] !== wanted[k]) { + firstDiff = k; + break; + } + } + + // Show the whole region when it is short, otherwise the part around the first difference. + let showFrom = from; + let showTo = to; + if (to - from > MAX_SNIPPET_LINES) { + const centre = best.start + Math.max(0, firstDiff); + showFrom = Math.max(from, centre - 3); + showTo = Math.min(to, showFrom + MAX_SNIPPET_LINES); + } + const width = String(showTo).length; + const snippet: string[] = []; + for (let i = showFrom; i < showTo; i++) { + const body = file[i]?.body ?? ""; + snippet.push(` ${String(i + 1).padStart(width, " ")} | ${body.length > 200 ? `${body.slice(0, 200)}…` : body}`); + } + + const out = [ + `search text not found. The closest text is lines ${from + 1}-${to} (${best.identical} of ${wanted.length} line(s) identical apart from indentation):`, + ...snippet, + ]; + if (showTo < to || showFrom > from) out.push(` (showing lines ${showFrom + 1}-${showTo})`); + if (firstDiff !== -1) { + const fileLine = file[best.start + firstDiff]; + out.push( + fileLine + ? `First difference, at line ${best.start + firstDiff + 1}:` + : "First difference: the search runs past the end of the file:", + ` search has: ${quoteLine(searchLinesRaw[firstDiff] ?? "")}`, + ` file has: ${fileLine ? quoteLine(fileLine.body) : "(no such line)"}`, + ); + } + return out.join("\n"); +} diff --git a/src/tools/fs-ops.test.ts b/src/tools/fs-ops.test.ts new file mode 100644 index 0000000..c8ab6dc --- /dev/null +++ b/src/tools/fs-ops.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { readRegularFile, syncDirStrict } from './fs-ops.js'; + +const failWith = (code: string) => async (): Promise => { + throw Object.assign(new Error(`${code}: directory fsync`), { code }); +}; + +describe.skipIf(process.platform === 'win32')('syncDirStrict', () => { + it.each(['EINVAL', 'ENOTSUP', 'EOPNOTSUPP'])('treats %s as a file system without directory fsync', async (code) => { + await expect(syncDirStrict('/any', failWith(code))).resolves.toBeUndefined(); + }); + + it.each(['EIO', 'ENOSPC'])('rethrows %s', async (code) => { + await expect(syncDirStrict('/any', failWith(code))).rejects.toMatchObject({ code }); + }); + + it('flushes a real directory', async () => { + await expect(syncDirStrict(process.cwd())).resolves.toBeUndefined(); + }); +}); + +describe.skipIf(process.platform !== 'linux')('readRegularFile', () => { + it('stops at the byte limit even when the file is larger than its reported size', async () => { + // A /proc file reports size 0 and holds more. + await expect(readRegularFile(`/proc/${process.pid}/status`, 16)).rejects.toThrow(/more than the 16-byte limit/); + }); +}); diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts new file mode 100644 index 0000000..6565605 --- /dev/null +++ b/src/tools/fs-ops.ts @@ -0,0 +1,429 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants as FS, type Stats } from 'node:fs'; +import fs, { type FileHandle } from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; + +/** + * File operations that do not let a symlink or a race widen what was + * prepared. Every open of a final component uses `O_NOFOLLOW` where the + * platform has it; the opened file is then checked to be the one at the path + * (Linux: `/proc/self/fd`; elsewhere: `fstat` vs `lstat` identity). + */ + +const NOFOLLOW = FS.O_NOFOLLOW ?? 0; +/** Opening a FIFO or a device for reading must not wait for a writer before the type check. */ +const NONBLOCK = FS.O_NONBLOCK ?? 0; +const IS_LINUX = process.platform === 'linux'; +const IS_WINDOWS = process.platform === 'win32'; + +export function sha256(data: Buffer | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +export function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +function sameFile(a: Stats, b: Stats): boolean { + return a.ino === b.ino && a.dev === b.dev; +} + +/** Throws `stale` unless the real path of `dir` is still exactly `dir`. */ +export async function assertDirUnchanged(dir: string): Promise { + let real: string; + try { + real = await fs.realpath(dir); + } catch (err) { + throw new ToolError('stale', `${dir} changed since prepared (${errnoCode(err) ?? 'unresolvable'})`); + } + const same = IS_WINDOWS ? real.toLowerCase() === dir.toLowerCase() : real === dir; + if (!same) throw new ToolError('stale', `file changed since prepared: ${dir} now resolves to ${real}`); +} + +/** Verifies an open handle is the file at `abs` and not something reached through a link. */ +async function assertHandleAt(handle: FileHandle, abs: string): Promise { + const st = await handle.stat(); + if (IS_LINUX) { + let actual: string | undefined; + try { + actual = await fs.readlink(`/proc/self/fd/${handle.fd}`); + } catch { + actual = undefined; + } + if (actual !== undefined && actual !== abs) { + throw new ToolError('stale', `file changed since prepared: ${abs} opened as ${actual}`); + } + } + const lst = await fs.lstat(abs).catch(() => null); + if (!lst || lst.isSymbolicLink() || !sameFile(st, lst)) { + throw new ToolError('stale', `file changed since prepared: ${abs} was replaced while it was opened`); + } + // Without /proc, the directory holding the opened file must still be itself: + // a parent swapped for a link would make `lstat(abs)` agree with the handle. + if (!IS_LINUX) await assertDirUnchanged(path.dirname(abs)); + return st; +} + +/** + * Opens a regular file for reading and checks the handle is the file at + * `abs` reached without any link (final component or parent). Returns null + * when the file is not there or not a regular file reachable that way. + */ +export async function readFileInside(abs: string, maxBytes: number): Promise { + let handle: FileHandle; + try { + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW | NONBLOCK); + } catch { + return null; + } + try { + const st = await assertHandleAt(handle, abs); + if (!st.isFile() || st.size > maxBytes) return null; + return await readAtMost(handle, maxBytes); + } catch { + return null; + } finally { + await handle.close(); + } +} + +/** Reads an open file to its end, or returns null once it holds more than `maxBytes` (it may grow after the size check). */ +async function readAtMost(handle: FileHandle, maxBytes: number): Promise { + const chunks: Buffer[] = []; + let total = 0; + for (;;) { + const chunk = Buffer.allocUnsafe(64 * 1024); + const { bytesRead } = await handle.read(chunk, 0, chunk.length, null); + if (bytesRead === 0) return Buffer.concat(chunks, total); + total += bytesRead; + if (total > maxBytes) return null; + chunks.push(chunk.subarray(0, bytesRead)); + } +} + +// --------------------------------------------------------------------------- +// Identity: what a commit checks to know the path still names what prepare saw. +// --------------------------------------------------------------------------- + +/** dev+ino of a path and of each directory above it up to a root. */ +export interface PathIdentity { + readonly entries: readonly { readonly path: string; readonly dev: bigint; readonly ino: bigint }[]; +} + +/** + * Records the identity of `abs` (when it exists) and of every existing + * directory from its parent up to `root` (inclusive). + */ +export async function captureIdentity(abs: string, root: string): Promise { + const entries: { path: string; dev: bigint; ino: bigint }[] = []; + let cursor = abs; + for (;;) { + const st = await fs.lstat(cursor, { bigint: true }).catch(() => null); + if (st) entries.push({ path: cursor, dev: st.dev, ino: st.ino }); + const same = IS_WINDOWS ? cursor.toLowerCase() === root.toLowerCase() : cursor === root; + const parent = path.dirname(cursor); + if (same || parent === cursor) break; + cursor = parent; + } + return { entries }; +} + +/** Throws `stale` when any path recorded by `captureIdentity` now names something else. */ +export async function assertIdentity(identity: PathIdentity): Promise { + for (const e of identity.entries) { + const st = await fs.lstat(e.path, { bigint: true }).catch(() => null); + if (!st || st.dev !== e.dev || st.ino !== e.ino) { + throw new ToolError('stale', `file changed since prepared: ${e.path} was replaced`); + } + } +} + +// --------------------------------------------------------------------------- +// Per-path lock: check-and-replace of one path is atomic within the process. +// --------------------------------------------------------------------------- + +const locks = new Map>(); + +/** Runs `fn` while holding the in-process lock of `abs`. */ +export function withPathLock(abs: string, fn: () => Promise): Promise { + const key = IS_WINDOWS || process.platform === 'darwin' ? abs.toLowerCase() : abs; + const prev = locks.get(key) ?? Promise.resolve(); + const next = prev.then(fn, fn); + const tail = next.catch(() => undefined); + locks.set(key, tail); + void tail.then(() => { + if (locks.get(key) === tail) locks.delete(key); + }); + return next; +} + +export interface RegularFile { + readonly bytes: Buffer; + readonly mode: number; +} + +/** + * Reads a regular file without following a link at its final component. + * Returns null when it does not exist. `maxBytes` bounds the read. + */ +export async function readRegularFile(abs: string, maxBytes = Number.MAX_SAFE_INTEGER): Promise { + let handle: FileHandle; + try { + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW | NONBLOCK); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT') return null; + if (code === 'ELOOP' || code === 'EMLINK') throw new ToolError('stale', `${abs} is a symbolic link`); + if (code === 'EISDIR') throw new ToolError('invalid-args', `${abs} is a directory`); + throw new ToolError('tool-error', `cannot open ${abs}: ${code ?? String(err)}`); + } + try { + const st = await assertHandleAt(handle, abs); + if (st.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${abs} is not a regular file`); + const tooBig = (size: number | string): ToolError => new ToolError('tool-error', `${abs} is ${size} bytes, more than the ${maxBytes}-byte limit`); + if (st.size > maxBytes) throw tooBig(st.size); + const bytes = await readAtMost(handle, maxBytes); + if (bytes === null) throw tooBig(`over ${maxBytes}`); + return { bytes, mode: st.mode & 0o7777 }; + } finally { + await handle.close(); + } +} + +/** What a commit expects to find at the path before it writes. */ +export type Expectation = { readonly kind: 'absent' } | { readonly kind: 'hash'; readonly sha256: string }; + +export interface WriteOutcome { + /** Bytes that were there before (null when absent). */ + readonly before: RegularFile | null; + /** Directories this write created to hold the file (not ones that appeared meanwhile), outermost first. */ + readonly createdDirs: readonly string[]; +} + +async function missingDirs(dir: string): Promise { + const missing: string[] = []; + let cursor = dir; + for (;;) { + const st = await fs.lstat(cursor).catch(() => null); + if (st) { + if (st.isSymbolicLink() || !st.isDirectory()) { + throw new ToolError('stale', `file changed since prepared: ${cursor} is not a directory`); + } + break; + } + missing.push(cursor); + const parent = path.dirname(cursor); + if (parent === cursor) break; + cursor = parent; + } + return missing.reverse(); +} + +export interface AtomicWriteOptions { + /** Runs after the checks and before anything is written (the journal snapshots there). */ + readonly beforeWrite?: (before: RegularFile | null, createdDirs: readonly string[]) => Promise; + /** Checked again right before the rename; an abort refuses the write. */ + readonly signal?: AbortSignal; + /** Identity recorded at prepare; checked before writing and right before the rename. */ + readonly identity?: PathIdentity; + /** Mode of the new file; defaults to the mode of the file it replaces. */ + readonly mode?: number; +} + +function hashMatches(expect: Expectation, current: RegularFile | null): boolean { + if (expect.kind === 'absent') return current === null; + return current !== null && sha256(current.bytes) === expect.sha256; +} + +/** Atomically replaces (or creates) `abs` under its per-path lock; see `writeLocked`. */ +export function atomicWrite(abs: string, bytes: Buffer, expect: Expectation, opts: AtomicWriteOptions = {}): Promise { + return withPathLock(abs, () => writeLocked(abs, bytes, expect, opts)); +} + +function assertNotAborted(signal: AbortSignal | undefined, abs: string): void { + if (signal?.aborted) throw new ToolError('cancelled', `the run was stopped before ${abs} was written`); +} + +/** + * Replaces (or creates) `abs` with `bytes`, holding its per-path lock: + * 1. the parent directory must still resolve to itself (no symlink swapped in); + * 2. the identity recorded at prepare and the content must match (else `stale`, no write); + * 3. the bytes go to a temp file in the same directory (fsync), keep the old mode, + * and are renamed over the target; a create uses `link` so it never replaces + * a file that appeared meanwhile. + * Right before the rename the signal, the identity and the content hash are + * checked again. `beforeWrite` runs after the checks and before anything is written (the + * transaction journal snapshots the original there). + */ +async function writeLocked(abs: string, bytes: Buffer, expect: Expectation, opts: AtomicWriteOptions): Promise { + const { beforeWrite, signal, identity } = opts; + assertNotAborted(signal, abs); + if (identity) await assertIdentity(identity); + const dir = path.dirname(abs); + const toCreate = await missingDirs(dir); + const existingAncestor = toCreate.length > 0 ? path.dirname(toCreate[0] ?? dir) : dir; + await assertDirUnchanged(existingAncestor); + + const before = await readRegularFile(abs); + if (expect.kind === 'absent' && before !== null) { + throw new ToolError('stale', `file changed since prepared: ${abs} was created after the call was prepared`); + } + if (expect.kind === 'hash') { + if (before === null) throw new ToolError('stale', `file changed since prepared: ${abs} no longer exists`); + if (sha256(before.bytes) !== expect.sha256) throw new ToolError('stale', `file changed since prepared: ${abs}`); + } + + await beforeWrite?.(before, toCreate); + + const createdDirs: string[] = []; + for (const d of toCreate) { + try { + await fs.mkdir(d); + createdDirs.push(d); + } catch (err) { + if (errnoCode(err) !== 'EEXIST') throw err; + } + await assertDirUnchanged(d); + } + await assertDirUnchanged(dir); + + const tmp = path.join(dir, `.acm-${randomBytes(6).toString('hex')}.tmp`); + const mode = opts.mode ?? before?.mode ?? 0o666; + const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | NOFOLLOW, mode); + try { + try { + await handle.writeFile(bytes); + if ((opts.mode !== undefined || before) && !IS_WINDOWS) await handle.chmod(mode); + await handle.sync(); + } finally { + await handle.close(); + } + // Last checks before the irreversible step. + await assertDirUnchanged(dir); + if (identity) await assertIdentity(identity); + if (!hashMatches(expect, await readRegularFile(abs))) { + throw new ToolError('stale', `file changed since prepared: ${abs} changed while it was being written`); + } + assertNotAborted(signal, abs); + if (expect.kind === 'absent') { + try { + await fs.link(tmp, abs); + } catch (err) { + const code = errnoCode(err); + if (code === 'EEXIST') throw new ToolError('stale', `file changed since prepared: ${abs} was created meanwhile`); + throw err; + } + } else { + await fs.rename(tmp, abs); + } + return { before, createdDirs }; + } finally { + // After `link` the temp name is still there; after `rename` it is gone. + await fs.rm(tmp, { force: true }).catch(() => undefined); + } +} + +/** + * Removes `abs` when it is a regular file holding `expectHash`, reached + * without any link (its directory must still resolve to itself). + */ +export function removeRegularFile(abs: string, expectHash: string): Promise { + return withPathLock(abs, async () => { + await assertDirUnchanged(path.dirname(abs)); + const current = await readRegularFile(abs); + if (current === null) return; + if (sha256(current.bytes) !== expectHash) throw new ToolError('stale', `${abs} changed; not removed`); + await fs.unlink(abs); + }); +} + +/** + * Removes `dir` when it is an empty real directory (not a link, not reached + * through one) strictly inside one of `roots`. Returns whether it was removed. + */ +export async function removeEmptyDirInside(dir: string, roots: readonly string[]): Promise { + if (!path.isAbsolute(dir)) return false; + const st = await fs.lstat(dir).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return false; + const real = await fs.realpath(dir).catch(() => null); + const same = real !== null && (IS_WINDOWS ? real.toLowerCase() === dir.toLowerCase() : real === dir); + if (!same) return false; + const inside = roots.some((root) => { + const rel = path.relative(IS_WINDOWS ? root.toLowerCase() : root, IS_WINDOWS ? dir.toLowerCase() : dir); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); + }); + if (!inside) return false; + try { + await fs.rmdir(dir); + return true; + } catch { + return false; + } +} + +/** fsyncs a directory where the platform allows it. */ +export async function syncDir(dir: string): Promise { + try { + await syncDirStrict(dir); + } catch { + // Not every file system lets a directory be flushed. + } +} + +/** Opens a directory and fsyncs it. */ +async function flushDir(dir: string): Promise { + const handle = await fs.open(dir, FS.O_RDONLY); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Errors that mean the file system cannot fsync a directory at all (FUSE, 9p, some NFS). */ +const UNSUPPORTED_SYNC = new Set(['EINVAL', 'ENOTSUP', 'EOPNOTSUPP']); + +/** fsyncs a directory and rethrows any failure, except where directory fsync is not supported. */ +export async function syncDirStrict(dir: string, flush: (dir: string) => Promise = flushDir): Promise { + // Windows, and file systems that answer EINVAL/ENOTSUP/EOPNOTSUPP, cannot fsync a directory: a rename there stays atomic but is not guaranteed to survive a power loss. + if (IS_WINDOWS) return; + try { + await flush(dir); + } catch (err) { + const code = errnoCode(err); + if (code !== undefined && UNSUPPORTED_SYNC.has(code)) return; + throw err; + } +} + +/** Writes and fsyncs a private file (journal records). */ +export async function writeDurable(file: string, data: Buffer | string): Promise { + const handle = await fs.open(file, FS.O_WRONLY | FS.O_CREAT | FS.O_TRUNC, 0o600); + try { + await handle.writeFile(data); + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Whether a buffer looks like binary data: a NUL byte in the first 8 KiB, or invalid UTF-8. */ +export function isBinary(bytes: Buffer): boolean { + const head = bytes.subarray(0, 8192); + if (head.includes(0)) return true; + try { + new TextDecoder('utf-8', { fatal: true }).decode(bytes); + return false; + } catch { + return true; + } +} + +/** Decodes UTF-8 text, throwing `ToolError('tool-error', 'binary file')` for binary data. */ +export function decodeText(abs: string, bytes: Buffer): string { + if (isBinary(bytes)) throw new ToolError('tool-error', `binary file: ${abs}`); + return bytes.toString('utf8'); +} diff --git a/src/tools/hardening.test.ts b/src/tools/hardening.test.ts new file mode 100644 index 0000000..ab099df --- /dev/null +++ b/src/tools/hardening.test.ts @@ -0,0 +1,275 @@ +import { linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync, existsSync } from 'node:fs'; +import fsp from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, PreparedCall, SessionContext, ToolCall } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { FileTransaction, journalRoot, recoverStaleJournals } from './journal.js'; +import { NodeToolRuntime } from './runtime.js'; + +/** + * One test per defect found by the correctness review of the first version: + * each failed (or hung) before its fix. + */ + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let outside: string; +let ctx: SessionContext; +let rt: NodeToolRuntime; +let seq = 0; +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; + +async function code(p: Promise): Promise { + try { + await p; + } catch (err) { + if (err instanceof ToolError) return err.code; + throw err; + } + return 'resolved'; +} + +function prepWrite(rel: string, content: string, p: PolicySnapshot = policy): Promise { + return rt.prepare({ id: `c${++seq}`, tool: 'write', args: { path: rel, content } } satisfies ToolCall, ctx, p); +} + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-hard-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(ws); + mkdirSync(outside); + writeFileSync(path.join(outside, 'secret'), 'EXTERNAL_SECRET\n'); + ctx = makeContext(ws); + rt = new NodeToolRuntime({ stateDir: path.join(base, 'state') }); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe.skipIf(IS_WINDOWS)('1. grep and glob re-check every directory and file they open', () => { + /** Swaps `ws/sub` for a link to `outside` around the walk's listing of it. */ + async function withSwap(when: 'before-list' | 'after-list', fn: () => Promise): Promise { + const sub = path.join(ws, 'sub'); + const original = fsp.readdir; + let swapped = false; + const swap = async (): Promise => { + swapped = true; + renameSync(sub, `${sub}-old`); + symlinkSync(outside, sub, 'dir'); + }; + const patched = async function (this: unknown, ...args: Parameters): Promise { + if (args[0] === sub && !swapped && when === 'before-list') await swap(); + const result: unknown = await Reflect.apply(original, this, args); + if (args[0] === sub && !swapped && when === 'after-list') await swap(); + return result; + }; + Object.assign(fsp, { readdir: patched }); + try { + return await fn(); + } finally { + Object.assign(fsp, { readdir: original }); + } + } + + beforeEach(() => { + mkdirSync(path.join(ws, 'sub')); + writeFileSync(path.join(ws, 'sub', 'secret'), 'inside\n'); + }); + + it('grep does not read a file through a parent swapped for a link mid-walk', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'grep', args: { pattern: 'SECRET' } }, ctx, policy); + const result = await withSwap('after-list', () => rt.commit(prepared, new AbortController().signal)); + expect('matches' in result ? result.matches : null).toEqual([]); + }); + + it('glob does not list names from a directory swapped for a link before it is listed', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'glob', args: { pattern: '**/*' } }, ctx, policy); + const result = await withSwap('before-list', () => rt.commit(prepared, new AbortController().signal)); + expect('files' in result ? result.files : null).toEqual([]); + }); +}); + +describe.skipIf(IS_WINDOWS)('2. crash recovery never deletes through a link', () => { + it('leaves a directory outside the roots alone when a created dir path now goes through a link', async () => { + mkdirSync(path.join(outside, 'empty')); + symlinkSync(outside, path.join(ws, 'sub'), 'dir'); + const dir = path.join(journalRoot(path.join(base, 'state')), 'abc-99999999-dead'); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + writeFileSync( + path.join(dir, 'manifest.json'), + JSON.stringify({ version: 1, pid: 99_999_999, host: os.hostname(), startedAt: 0, roots: [ws], dirs: [path.join(ws, 'sub', 'empty')], entries: [] }), + ); + await recoverStaleJournals(path.join(base, 'state'), [ws], []); + expect(existsSync(path.join(outside, 'empty'))).toBe(true); + }); +}); + +describe.skipIf(IS_WINDOWS)('3. protected paths are checked on every path the resolution goes through', () => { + it('refuses writing a protected path that is a link to an unprotected file', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + symlinkSync(path.join(ws, 'f'), path.join(ws, 'config.json')); + const p = { ...policy, protectedPaths: [path.join(ws, 'config.json')] }; + expect(await code(prepWrite('config.json', 'overwritten', p))).toBe('protected-path'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('old'); + }); + + it('refuses writing through a final-component link even inside the workspace', async () => { + writeFileSync(path.join(ws, 'target.txt'), 'old'); + symlinkSync(path.join(ws, 'target.txt'), path.join(ws, 'alias.txt')); + expect(await code(prepWrite('alias.txt', 'new'))).toBe('invalid-args'); + expect(await code(rt.prepare({ id: 'e', tool: 'edit', args: { path: 'alias.txt', oldString: 'old', newString: 'new' } }, ctx, policy))).toBe('invalid-args'); + expect(readFileSync(path.join(ws, 'target.txt'), 'utf8')).toBe('old'); + }); +}); + +describe('4. abort stops a write that already entered commit', () => { + it('refuses the rename after the signal aborted', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const prepared = await prepWrite('f', 'new'); + const ac = new AbortController(); + const work = rt.commit(prepared, ac.signal); + ac.abort(); + expect(await code(work)).toBe('cancelled'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('old'); + }); +}); + +describe('5. concurrent commits on one path', () => { + it('lets only the first of two writes prepared against the same content succeed', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const a = await prepWrite('f', 'first'); + const b = await prepWrite('f', 'second'); + class SlowTransaction extends FileTransaction { + override async record(...args: Parameters): Promise { + await super.record(...args); + await new Promise((r) => setTimeout(r, 50)); + } + } + const tx = new SlowTransaction(path.join(base, 'state')); + const signal = new AbortController().signal; + const results = await Promise.allSettled([rt.commit(a, signal, tx), rt.commit(b, signal, tx)]); + expect(results.map((r) => r.status)).toEqual(['fulfilled', 'rejected']); + const second = results[1]; + expect(second?.status === 'rejected' && second.reason instanceof ToolError && second.reason.code).toBe('stale'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('first'); + await tx.dispose(); + }); +}); + +describe.skipIf(IS_WINDOWS)('6. identity of the file and its directories', () => { + it('refuses a commit when the file was replaced by a hard link with the same content', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const prepared = await prepWrite('f', 'new'); + writeFileSync(path.join(ws, 'other'), 'old'); + rmSync(path.join(ws, 'f')); + linkSync(path.join(ws, 'other'), path.join(ws, 'f')); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'other'), 'utf8')).toBe('old'); + }); + + it('refuses a commit when a parent directory was replaced by another one', async () => { + mkdirSync(path.join(ws, 'd')); + writeFileSync(path.join(ws, 'd', 'f'), 'old'); + const prepared = await prepWrite('d/f', 'new'); + const created = await prepWrite('d/new.txt', 'new'); + renameSync(path.join(ws, 'd'), path.join(ws, 'd-moved')); + mkdirSync(path.join(ws, 'd')); + writeFileSync(path.join(ws, 'd', 'f'), 'old'); + expect(statSync(path.join(ws, 'd')).isDirectory()).toBe(true); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('stale'); + expect(await code(rt.commit(created, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'd', 'f'), 'utf8')).toBe('old'); + }); +}); + +describe('7. a pathological grep pattern can be stopped', () => { + beforeEach(() => { + writeFileSync(path.join(ws, 'f'), `${'a'.repeat(40)}!\n`); + }); + + it('fails with a ToolError when the per-file budget runs out', async () => { + const budgeted = new NodeToolRuntime({ stateDir: path.join(base, 'state'), grepFileBudgetMs: 200 }); + const prepared = await budgeted.prepare({ id: 'g', tool: 'grep', args: { pattern: '(a+)+$' } }, ctx, policy); + const started = Date.now(); + const err = await budgeted.commit(prepared, new AbortController().signal).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ToolError); + expect(String(err)).toMatch(/too expensive/); + expect(Date.now() - started).toBeLessThan(5000); + }); + + it('stops on abort', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'grep', args: { pattern: '(a+)+$' } }, ctx, policy); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 50); + const started = Date.now(); + expect(await code(rt.commit(prepared, ac.signal))).toBe('cancelled'); + expect(Date.now() - started).toBeLessThan(5000); + }); +}); + +describe.skipIf(IS_WINDOWS)('8. path oracle: accepted iff the real path is inside the roots', () => { + it('agrees with the operating system on links followed by ..', async () => { + mkdirSync(path.join(outside, 'sub')); + mkdirSync(path.join(ws, 'dir')); + writeFileSync(path.join(ws, 'f'), 'inside'); + writeFileSync(path.join(outside, 'f'), 'outside'); + writeFileSync(path.join(outside, 'sub', 'f'), 'outside sub'); + symlinkSync(path.join(outside, 'sub'), path.join(ws, 'link')); + symlinkSync(path.join(ws, 'dir'), path.join(ws, 'inlink')); + symlinkSync('../outside/sub', path.join(ws, 'rel-link')); + const parts = ['f', '.', '..', 'link', 'inlink', 'rel-link', 'dir', 'sub', 'ws', 'outside']; + let seed = 1234; + let checked = 0; + for (let i = 0; i < 400; i++) { + const n = 1 + (i % 5); + const comps: string[] = []; + for (let k = 0; k < n; k++) { + seed = (1664525 * seed + 1013904223) >>> 0; + comps.push(parts[seed % parts.length] ?? 'f'); + } + comps.push('f'); + const input = comps.join('/'); + let real: string | null; + try { + // The kernel decides whether the path resolves (macOS realpath(3) alone + // accepts `file/..`); native realpath then gives where it lands. + await fsp.stat(`${ws}/${input}`); + real = await fsp.realpath(`${ws}/${input}`); + } catch { + real = null; + } + if (real === null) continue; // the OS cannot open it; the jail may refuse it any way it likes + checked++; + const inside = real === ws || real.startsWith(`${ws}${path.sep}`); + let prepared: PreparedCall | undefined; + try { + prepared = await rt.prepare({ id: `o${i}`, tool: 'read', args: { path: input } }, ctx, policy); + } catch { + prepared = undefined; + } + expect({ input, accepted: prepared !== undefined }).toEqual({ input, accepted: inside }); + if (prepared?.tool === 'read') expect({ input, abs: prepared.effect.absPath }).toEqual({ input, abs: real }); + } + expect(checked).toBeGreaterThan(30); + }); +}); + +describe('commit works on the copy the dispatcher hands it', () => { + it('commits a structured clone of the prepared call once', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const copy = structuredClone(await prepWrite('f', 'new')); + await rt.commit(copy, new AbortController().signal); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('new'); + expect(await code(rt.commit(structuredClone(copy), new AbortController().signal))).toBe('tool-error'); + }); +}); diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..925fd0c --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,5 @@ +export { NodeToolRuntime, DEFAULT_READ_LIMIT, READ_CAP_BYTES, MAX_FILE_BYTES, type NodeToolRuntimeOptions } from './runtime.js'; +export { FileTransaction, MAX_JOURNAL_BYTES, recoverStaleJournals, journalRoot, type RecoveredJournal } from './journal.js'; +export { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, DEFAULT_OUTPUT_CAP_BYTES } from './bash.js'; +export { DEFAULT_GREP_MAX_RESULTS, DEFAULT_GLOB_MAX_RESULTS } from './search.js'; +export { containmentUnavailableReason } from './sandbox.js'; diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts new file mode 100644 index 0000000..7d8b89a --- /dev/null +++ b/src/tools/integration.test.ts @@ -0,0 +1,62 @@ +import { existsSync, mkdirSync, readdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { runScript } from '../core/run.js'; +import { FakeSandbox, StaticHostAdapter, makeContext } from '../testing/index.js'; +import { NodeToolRuntime } from './runtime.js'; + +/** The real tool runtime behind the P0 dispatcher and run pipeline. */ +let base: string; +let ws: string; + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + writeFileSync(path.join(ws, 'a.txt'), 'alpha\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +function deps(adapter = new StaticHostAdapter({ protectedPaths: [] })) { + return { sandbox: new FakeSandbox(), adapter, tools: new NodeToolRuntime({ stateDir: path.join(base, 'state') }), ctx: makeContext(ws) }; +} + +describe('NodeToolRuntime in the run pipeline', () => { + it('commits writes and edits and reports the diff', async () => { + const code = JSON.stringify([ + { tool: 'edit', args: { path: 'a.txt', oldString: 'alpha', newString: 'beta' } }, + { tool: 'write', args: { path: 'b/c.txt', content: 'new\n' } }, + { tool: 'read', args: { path: 'b/c.txt' } }, + ]); + const result = await runScript({ code, transaction: false, timeoutMs: 10_000 }, deps()); + expect(result.ok).toBe(true); + expect(result.changedFiles).toEqual(['a.txt', 'b/c.txt']); + expect(result.diff).toContain('-alpha\n+beta\n'); + expect(result.diff).toContain('--- /dev/null\n+++ b/b/c.txt\n'); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('beta\n'); + }); + + it('rolls a transactional run back when a call is denied', async () => { + const adapter = new StaticHostAdapter({ + protectedPaths: [], + rules: [(p) => (p.tool === 'write' && p.effect.absPath.endsWith('denied.txt') ? { kind: 'deny', reason: 'no' } : undefined)], + }); + const code = JSON.stringify([ + { tool: 'write', args: { path: 'a.txt', content: 'changed\n' } }, + { tool: 'write', args: { path: 'fresh/new.txt', content: 'x' } }, + { tool: 'write', args: { path: 'denied.txt', content: 'x' } }, + ]); + const result = await runScript({ code, transaction: true, timeoutMs: 10_000 }, deps(adapter)); + expect(result.ok).toBe(false); + expect(result.rolledBack?.skipped).toEqual([]); + expect(result.rolledBack?.restored.length).toBe(2); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('alpha\n'); + expect(existsSync(path.join(ws, 'fresh'))).toBe(false); + // The journal is released once the run is over. + expect(readdirSync(path.join(base, 'state', 'journal'))).toEqual([]); + }); +}); diff --git a/src/tools/jail.ts b/src/tools/jail.ts new file mode 100644 index 0000000..e88b67b --- /dev/null +++ b/src/tools/jail.ts @@ -0,0 +1,365 @@ +/* + * `isInsideDir` and `windowsPathProblem` are adapted + * from Turnpack's src/security.ts (https://github.com/OnlyTerp/turnpack, + * Copyright 2026 OnlyTerp, licensed under the Apache License, Version 2.0: + * http://www.apache.org/licenses/LICENSE-2.0). + * Modified by the agent-code-mode authors: asynchronous, multiple roots, + * errors as ToolError, UNC and device prefixes refused. + */ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, findMatchingPattern } from '../core/paths.js'; + +/** + * Workspace jail: every path a tool touches is resolved to an absolute real + * path and must live under one of the allowed roots. + * + * Resolution walks the path one component at a time with `lstat` and follows + * each link by hand (`resolvePhysical`), so a dangling link and `link/..` are + * judged by where the operating system would really land. + */ + +const MAX_LINK_HOPS = 40; +const IS_WINDOWS = process.platform === 'win32'; + +function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +async function lstatOrNull(p: string): Promise { + try { + return await fs.lstat(p); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT' || code === 'ENOTDIR') return null; + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${p.slice(0, 120)}…`); + throw err; + } +} + +/** What resolving a path found. */ +export interface Resolution { + /** Absolute real path (the missing tail, if any, joined to the deepest existing real directory). */ + readonly real: string; + /** Absolute locations of every symbolic link followed on the way, in order. */ + readonly links: readonly string[]; + /** True when the path's own last component is a symbolic link. */ + readonly finalIsLink: boolean; +} + +function splitComponents(p: string): string[] { + return p.split(IS_WINDOWS ? /[\\/]+/ : /\/+/); +} + +function stripVerbatim(target: string): string { + return IS_WINDOWS && target.startsWith('\\\\?\\') ? target.slice(4) : target; +} + +/** + * Resolves `input` (absolute, or relative to the real directory `base`) + * component by component with POSIX semantics: a symbolic link is replaced + * by its target before the next component is looked at, so `link/..` is the + * parent of the link's target, not the directory holding the link. Nothing + * is normalized lexically first. A `..` after a component that does not + * exist is refused, as the operating system would refuse it. + */ +export async function resolvePhysical(input: string, base: string): Promise { + let current: string; + let rest: string; + if (path.isAbsolute(input)) { + const root = path.parse(input).root; + current = path.resolve(root); + rest = input.slice(root.length); + } else { + current = base; + rest = input; + } + const queue = splitComponents(rest); + const links: string[] = []; + const meaningful = (q: readonly string[]): boolean => q.some((c) => c !== '' && c !== '.'); + let hops = 0; + let missing = false; + let finalIsLink = false; + while (queue.length > 0) { + const c = queue.shift() ?? ''; + if (c === '' || c === '.') continue; + if (c === '..') { + if (missing) throw new ToolError('not-found', `${input}: ".." after a component that does not exist`); + current = path.dirname(current); + continue; + } + const next = path.join(current, c); + if (missing) { + current = next; + continue; + } + const st = await lstatOrNull(next); + if (!st) { + missing = true; + current = next; + continue; + } + if (st.isSymbolicLink()) { + if (++hops > MAX_LINK_HOPS) throw new ToolError('outside-workspace', `${input}: too many symbolic links`); + links.push(next); + if (!meaningful(queue)) finalIsLink = true; + const target = stripVerbatim(await fs.readlink(next)); + if (path.isAbsolute(target)) { + const root = path.parse(target).root; + current = path.resolve(root); + queue.unshift(...splitComponents(target.slice(root.length))); + } else { + queue.unshift(...splitComponents(target)); + } + continue; + } + if (!st.isDirectory() && meaningful(queue)) { + throw new ToolError('not-found', `${input}: ${next} is not a directory`); + } + current = next; + } + // Canonical spelling (case, Windows short names) of the existing part. + let existing = current; + const tail: string[] = []; + while (!(await lstatOrNull(existing))) { + const parent = path.dirname(existing); + if (parent === existing) break; + tail.unshift(path.basename(existing)); + existing = parent; + } + let realExisting = existing; + try { + realExisting = await fs.realpath(existing); + } catch { + // Dangling final link target: keep the spelling. + } + return { real: tail.length === 0 ? realExisting : path.join(realExisting, ...tail), links, finalIsLink }; +} + +/** True when `target` is `base` or below it. Both must be real absolute paths. */ +export function isInsideDir(base: string, target: string): boolean { + const b = IS_WINDOWS ? base.toLowerCase() : base; + const t = IS_WINDOWS ? target.toLowerCase() : target; + const rel = path.relative(b, t); + if (rel === '') return true; + return !(rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)); +} + +/** + * Windows spellings that alias another name: device and verbatim prefixes + * (`\\?\`, `\\.\`), UNC shares, NTFS alternate data streams (`name:stream`, + * `.git::$INDEX_ALLOCATION`) and segments ending in a dot or space. Plain + * string logic, tested everywhere; enforced only on Windows unless `force`. + */ +export function windowsPathProblem(target: string): string | null { + if (/^[\\/]{2}/.test(target)) return 'UNC, device and verbatim (\\\\?\\) paths are not accepted'; + const rest = target.slice(path.win32.parse(target).root.length); + for (const segment of rest.split(/[\\/]+/)) { + if (segment === '' || segment === '.' || segment === '..') continue; + if (segment.includes(':')) return `"${segment}" contains ":" (NTFS stream syntax is not accepted)`; + if (/[. ]$/.test(segment)) return `"${segment}" ends in a dot or a space, which Windows silently drops`; + } + return null; +} + +/** Expands a leading `~` or `~/` to the home directory. */ +export function expandTilde(p: string, home: string = os.homedir()): string { + if (p === '~') return home; + if (p.startsWith('~/') || (IS_WINDOWS && p.startsWith('~\\'))) return path.join(home, p.slice(2)); + return p; +} + +/** Whether any segment of `absPath` is a `.git` directory (as Windows would also open it). */ +export function isInsideGitDir(absPath: string): boolean { + return absPath + .split(/[\\/]+/) + .some((segment) => { + const lower = segment.toLowerCase(); + const plain = lower.replace(/:.*$/, '').replace(/[. ]+$/, ''); + return (DEFAULT_CASE_INSENSITIVE ? lower : segment) === '.git' || (IS_WINDOWS && plain === '.git'); + }); +} + +/** + * Adds, for each pattern, the same pattern with its literal directory prefix + * replaced by that directory's real path. Paths are checked as real paths, so + * a pattern written through an alias of the workspace (a symlinked cwd, + * macOS `/var` vs `/private/var`, a Windows 8.3 short name) must match too. + */ +async function withRealPrefixes(patterns: readonly string[]): Promise { + const out = new Set(patterns); + for (const pattern of patterns) { + const fwd = pattern.replace(/\\/g, '/'); + const wild = fwd.search(/[*?[]/); + const literal = wild === -1 ? fwd : fwd.slice(0, wild); + if (wild === -1) { + // A literal path that is a link protects what it names, too. + const real = await fs.realpath(fwd).then((r) => r.replace(/\\/g, '/'), () => null); + if (real !== null && real !== fwd) out.add(real); + } + const cut = literal.lastIndexOf('/'); + if (cut <= 0) continue; + // Resolve the deepest existing directory of the literal prefix. + let dir = fwd.slice(0, cut); + let rest = fwd.slice(cut); + for (;;) { + try { + const real = (await fs.realpath(dir)).replace(/\\/g, '/'); + if (real !== dir) out.add(real + rest); + break; + } catch { + const up = dir.lastIndexOf('/'); + if (up <= 0 || /^[A-Za-z]:$/.test(dir.slice(0, up))) break; + rest = dir.slice(up) + rest; + dir = dir.slice(0, up); + } + } + } + return [...out]; +} + +export interface JailOptions { + /** Absolute directory relative paths resolve against. */ + readonly cwd: string; + /** Allowed roots (absolute; resolved to real paths by `Jail.create`). */ + readonly roots: readonly string[]; + /** Protected path patterns (`~` expanded here). */ + readonly protectedPaths: readonly string[]; + /** Enforce the Windows alias checks even off Windows (tests). */ + readonly windowsChecks?: boolean; +} + +/** A resolved set of allowed roots for one call. */ +export class Jail { + /** Real path of the session cwd. */ + readonly cwd: string; + /** Real paths of the allowed roots; `roots[0]` is the session cwd. */ + readonly roots: readonly string[]; + readonly #protected: readonly string[]; + readonly #windowsChecks: boolean; + + private constructor(cwd: string, roots: readonly string[], protectedPaths: readonly string[], windowsChecks: boolean) { + this.cwd = cwd; + this.roots = roots; + this.#protected = protectedPaths; + this.#windowsChecks = windowsChecks; + } + + static async create(opts: JailOptions): Promise { + if (!path.isAbsolute(opts.cwd)) throw new ToolError('tool-error', `session cwd is not absolute: ${opts.cwd}`); + let cwd: string; + try { + cwd = await fs.realpath(opts.cwd); + } catch (err) { + throw new ToolError('tool-error', `session cwd ${opts.cwd} cannot be resolved: ${errnoCode(err) ?? String(err)}`); + } + const roots: string[] = [cwd]; + for (const root of opts.roots) { + if (!path.isAbsolute(root)) continue; + try { + const real = await fs.realpath(root); + if (!roots.includes(real)) roots.push(real); + } catch { + // A root that does not exist grants nothing. + } + } + const protectedPaths = await withRealPrefixes(opts.protectedPaths.map((p) => expandTilde(p))); + return new Jail(cwd, roots, protectedPaths, opts.windowsChecks ?? IS_WINDOWS); + } + + /** Protected path patterns with `~` expanded. */ + get protectedPaths(): readonly string[] { + return this.#protected; + } + + /** The root that contains `abs`, or undefined. */ + rootOf(abs: string): string | undefined { + return this.roots.find((root) => isInsideDir(root, abs)); + } + + /** + * Resolves `input` (relative to the session cwd, `~` expanded) to an + * absolute real path inside the roots, or throws `ToolError`. + */ + async resolve(input: string): Promise { + return (await this.#resolve(input)).real; + } + + /** + * Like `resolve`, for a write or an edit: also refuses a path whose last + * component is a symbolic link (write to its target instead), and refuses a + * protected path whether it is named by the real path or by any link the + * resolution went through. + */ + async resolveForWrite(input: string): Promise { + const r = await this.#resolve(input); + for (const p of [r.real, ...r.links]) this.assertWritable(p); + // The directories the write will create are names it affects too. + for (let dir = path.dirname(r.real); this.rootOf(dir) !== undefined && !(await lstatOrNull(dir)); dir = path.dirname(dir)) { + this.assertWritable(dir); + } + if (r.finalIsLink) { + throw new ToolError('invalid-args', `${input} is a symbolic link; write to its target (${r.real}) instead`); + } + return r.real; + } + + /** + * Like `resolve`, for the path grep and glob search: refuses a path whose + * last component is a symbolic link, since search never follows links. + */ + async resolveSearchRoot(input: string): Promise { + const r = await this.#resolve(input); + if (r.finalIsLink) throw new ToolError('invalid-args', `${input} is a symbolic link; search its target (${r.real}) instead`); + return r.real; + } + + async #resolve(input: string): Promise { + if (input.includes('\0')) throw new ToolError('invalid-args', 'path must not contain NUL characters'); + // Not trimmed: spaces are part of a file name. + if (input.trim() === '') throw new ToolError('invalid-args', 'path must not be empty'); + if (this.#windowsChecks) { + const problem = windowsPathProblem(input); + if (problem) throw new ToolError('outside-workspace', `${input}: ${problem}`); + } + const expanded = expandTilde(input); + let r: Resolution; + try { + r = await resolvePhysical(expanded, this.cwd); + } catch (err) { + if (err instanceof ToolError) throw err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${input.slice(0, 120)}…`); + if (code === 'ELOOP') throw new ToolError('outside-workspace', `${input}: too many symbolic links`); + throw new ToolError('tool-error', `cannot resolve ${input}: ${code ?? String(err)}`); + } + if (this.rootOf(r.real) === undefined) { + throw new ToolError('outside-workspace', `${input} resolves to ${r.real}, outside the workspace (${this.roots.join(', ')})`); + } + if (this.#windowsChecks) { + const problem = windowsPathProblem(r.real); + if (problem) throw new ToolError('outside-workspace', `${input}: ${problem}`); + } + return r; + } + + /** Throws `protected-path` when `abs` must not be written or edited. */ + assertWritable(abs: string): void { + if (isInsideGitDir(abs)) throw new ToolError('protected-path', `${abs} is inside a .git directory`); + const hit = findMatchingPattern(abs, this.#protected); + if (hit !== undefined) throw new ToolError('protected-path', `${abs} is a protected host policy path (${hit})`); + } + + /** Path for diffs and messages: relative to the first root when inside it, else absolute. */ + displayPath(abs: string): string { + const first = this.roots[0] ?? this.cwd; + if (isInsideDir(first, abs)) { + const rel = path.relative(first, abs); + return rel === '' ? '.' : rel.split(path.sep).join('/'); + } + return abs.split(path.sep).join('/'); + } +} diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts new file mode 100644 index 0000000..1a944c7 --- /dev/null +++ b/src/tools/journal.test.ts @@ -0,0 +1,363 @@ +import { spawnSync } from 'node:child_process'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { ToolError, TransactionFinalizeError } from '../core/errors.js'; +import type { PolicySnapshot, SessionContext, ToolCall, Transaction } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { COMMITTED, FileTransaction, type JournalIo, journalRoot, recoverStaleJournals } from './journal.js'; +import { atomicWrite, sha256, syncDirStrict } from './fs-ops.js'; +import { NodeToolRuntime } from './runtime.js'; + +let base: string; +let ws: string; +let outside: string; +let stateDir: string; +let ctx: SessionContext; +let rt: NodeToolRuntime; +let seq = 0; +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; +const signal = new AbortController().signal; + +async function write(rel: string, content: string, tx: Transaction): Promise { + const prepared = await rt.prepare({ id: `c${++seq}`, tool: 'write', args: { path: rel, content } } satisfies ToolCall, ctx, policy); + await rt.commit(prepared, signal, tx); +} + +const read = (rel: string): string => readFileSync(path.join(ws, rel), 'utf8'); + +const IS_WINDOWS = process.platform === 'win32'; + +/** A pid that belonged to a process that has exited. */ +function deadPid(): number { + const r = spawnSync(process.execPath, ['-e', '']); + return r.pid ?? 999_999; +} + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + stateDir = path.join(base, 'state'); + mkdirSync(ws); + mkdirSync(outside); + ctx = makeContext(ws); + rt = new NodeToolRuntime({ stateDir }); + writeFileSync(path.join(ws, 'a.txt'), 'a0\n'); + writeFileSync(path.join(ws, 'b.txt'), 'b0\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe('transactions', () => { + it('rolls back three writes (two edits and a create in a new directory)', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('a.txt', 'a2\n', tx); + await write('b.txt', 'b1\n', tx); + await write('new/dir/c.txt', 'c1\n', tx); + expect(existsSync(path.join(stateDir, 'journal'))).toBe(true); + const report = await tx.rollback(); + expect(report.skipped).toEqual([]); + expect([...report.restored].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'b.txt'), path.join(ws, 'new/dir/c.txt')].sort()); + expect(read('a.txt')).toBe('a0\n'); + expect(read('b.txt')).toBe('b0\n'); + expect(existsSync(path.join(ws, 'new'))).toBe(false); + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + }); + + it('does not clobber a file changed externally after our write, and reports it', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('b.txt', 'b1\n', tx); + writeFileSync(path.join(ws, 'a.txt'), 'edited by someone else\n'); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'b.txt')]); + expect(report.skipped).toEqual([{ path: path.join(ws, 'a.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('edited by someone else\n'); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('keeps changes and deletes the journal on dispose, and refuses writes afterwards', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await tx.dispose(); + await tx.dispose(); + expect(read('a.txt')).toBe('a1\n'); + await vi.waitFor(() => expect(readdirSync(journalRoot(stateDir))).toEqual([])); + await expect(write('b.txt', 'b1\n', tx)).rejects.toBeInstanceOf(ToolError); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('refuses a write that would push the journal past its size cap', async () => { + const big = Buffer.alloc(33 * 1024 * 1024, 0x61); + writeFileSync(path.join(ws, 'big1.txt'), big); + writeFileSync(path.join(ws, 'big2.txt'), big); + const tx = rt.beginTransaction(); + await write('big1.txt', 'small\n', tx); + const err = await write('big2.txt', 'small\n', tx).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ToolError); + expect(String(err)).toMatch(/journal is full/); + expect(readFileSync(path.join(ws, 'big2.txt')).length).toBe(big.length); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'big1.txt')]); + expect(readFileSync(path.join(ws, 'big1.txt')).equals(big)).toBe(true); + }); + + it('refuses to write again a file another writer changed since this transaction wrote it', async () => { + const mine = rt.beginTransaction(); + const other = rt.beginTransaction(); + await write('a.txt', 'mine\n', mine); + await write('a.txt', 'other\n', other); + await other.dispose(); + await expect(write('a.txt', 'mine again\n', mine)).rejects.toMatchObject({ code: 'stale' }); + await mine.rollback(); + expect(read('a.txt')).toBe('other\n'); + }); + + it('rolls back only directories its own writes created', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + const dir = path.join(ws, 'shared'); + const abs = path.join(dir, 'x.txt'); + const bytes = Buffer.from('x\n'); + const outcome = await atomicWrite(abs, bytes, { kind: 'absent' }, { + beforeWrite: async (before, dirs) => { + await tx.record(abs, ws, before, sha256(bytes), dirs); + // Another writer creates the directory between the checks and the write. + mkdirSync(dir); + }, + }); + tx.written(abs, sha256(bytes), outcome.createdDirs); + await tx.rollback(); + expect(existsSync(abs)).toBe(false); + expect(existsSync(dir)).toBe(true); + }); + + it('refuses a transaction it did not start', async () => { + const foreign: Transaction = { rollback: async () => ({ restored: [], skipped: [] }), dispose: async () => undefined }; + await expect(write('a.txt', 'a1\n', foreign)).rejects.toThrow(/not started by this tool runtime/); + expect(read('a.txt')).toBe('a0\n'); + }); +}); + +describe('crash recovery', () => { + /** Makes the journal of `tx` look like it was left by a process that died. */ + function abandon(tx: FileTransaction): string { + const dir = tx.dir; + const manifestPath = path.join(dir, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { pid: number }; + const pid = deadPid(); + manifest.pid = pid; + writeFileSync(manifestPath, JSON.stringify(manifest)); + const [stamp, , hex] = path.basename(dir).split('-'); + const moved = path.join(path.dirname(dir), `${stamp}-${pid}-${hex}`); + renameSync(dir, moved); + return moved; + } + + it('recovers a journal without write timestamps and preserves directories with unknown ownership', async () => { + const pid = deadPid(); + const dir = path.join(journalRoot(stateDir), `old-${pid}-abcd`); + const shared = path.join(ws, 'shared'); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + mkdirSync(shared); + writeFileSync(path.join(ws, 'a.txt'), 'a1\n'); + writeFileSync(path.join(dir, '0.bin'), 'a0\n'); + writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ + version: 1, pid, host: os.hostname(), startedAt: 0, roots: [ws], dirs: [shared], + entries: [{ + path: path.join(ws, 'a.txt'), existed: true, original: sha256('a0\n'), + mode: 0o644, blob: '0.bin', written: [sha256('a1\n')], + }], + })); + + const recovered = await recoverStaleJournals(stateDir, [ws], []); + + expect(recovered[0]?.report.restored).toEqual([path.join(ws, 'a.txt')]); + expect(read('a.txt')).toBe('a0\n'); + expect(existsSync(shared)).toBe(true); + }); + + it('restores a journal whose process is gone, and leaves a live one alone', async () => { + const crashed = rt.beginTransaction(); + if (!(crashed instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', crashed); + await write('new.txt', 'n1\n', crashed); + await write('b.txt', 'b1\n', crashed); + writeFileSync(path.join(ws, 'b.txt'), 'changed after the crash\n'); + const moved = abandon(crashed); + + const live = rt.beginTransaction(); + writeFileSync(path.join(ws, 'live.txt'), 'l0\n'); + await write('live.txt', 'l1\n', live); + + const recovered = await recoverStaleJournals(stateDir, [ws], []); + expect(recovered).toHaveLength(1); + const report = recovered[0]?.report; + expect([...(report?.restored ?? [])].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'new.txt')]); + expect(report?.skipped).toEqual([{ path: path.join(ws, 'b.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('a0\n'); + expect(existsSync(path.join(ws, 'new.txt'))).toBe(false); + expect(read('b.txt')).toBe('changed after the crash\n'); + expect(read('live.txt')).toBe('l1\n'); + expect(existsSync(moved)).toBe(false); + await live.dispose(); + }); + + it('ignores journals of other workspaces and never restores outside the roots', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + const moved = abandon(tx); + // Another workspace: nothing happens. + expect(await recoverStaleJournals(stateDir, [outside], [])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + + // A tampered record pointing outside the roots is not followed. + writeFileSync(path.join(outside, 'victim.txt'), 'victim\n'); + const manifestPath = path.join(moved, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { entries: { path: string }[] }; + const first = manifest.entries[0]; + if (first) first.path = path.join(outside, 'victim.txt'); + writeFileSync(manifestPath, JSON.stringify(manifest)); + const recovered = await recoverStaleJournals(stateDir, [ws], []); + expect(recovered[0]?.report.restored).toEqual([]); + expect(recovered[0]?.report.skipped[0]?.reason).toBe('error'); + expect(readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('victim\n'); + // A record with a file it could not handle is kept for a later pass. + expect(readdirSync(journalRoot(stateDir))).toHaveLength(1); + }); + + it('undoes writes newest first across journals, whatever order the runs started in', async () => { + const first = rt.beginTransaction(); + const second = rt.beginTransaction(); + if (!(first instanceof FileTransaction) || !(second instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'second\n', second); + await new Promise((r) => setTimeout(r, 5)); + await write('a.txt', 'first\n', first); + abandon(first); + abandon(second); + await recoverStaleJournals(stateDir, [ws], []); + expect(read('a.txt')).toBe('a0\n'); + }); + + it('never restores a protected path', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + abandon(tx); + const recovered = await recoverStaleJournals(stateDir, [ws], [path.join(ws, 'a.txt')]); + expect(recovered[0]?.report.skipped).toEqual([{ path: path.join(ws, 'a.txt'), reason: 'error', detail: expect.stringContaining('protected') }]); + expect(read('a.txt')).toBe('a1\n'); + }); + + it.skipIf(IS_WINDOWS)('reads and deletes nothing in a journal directory other users can write', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + abandon(tx); + mkdirSync(path.join(journalRoot(stateDir), `zz-1-abcd${COMMITTED}`)); + chmodSync(journalRoot(stateDir), 0o777); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + expect(readdirSync(journalRoot(stateDir))).toHaveLength(2); + }); + + it('deletes only finalized transaction directories', async () => { + const root = journalRoot(stateDir); + mkdirSync(root, { recursive: true, mode: 0o700 }); + mkdirSync(path.join(root, `notes${COMMITTED}`)); + mkdirSync(path.join(root, `zz-1-abcd${COMMITTED}`)); + await recoverStaleJournals(stateDir, [ws], []); + expect(readdirSync(root)).toEqual([`notes${COMMITTED}`]); + }); + + it('skips a malformed record', async () => { + mkdirSync(path.join(journalRoot(stateDir), 'zz-1-abcd'), { recursive: true }); + writeFileSync(path.join(journalRoot(stateDir), 'zz-1-abcd', 'manifest.json'), '{"version":1,"entries":"nope"}'); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); + }); +}); + +describe('finalization', () => { + /** Keeps the delete of a finalized journal pending, as if the process died right after the commit. */ + const held = (): Promise => new Promise(() => undefined); + + it('commits by renaming the journal, so recovery never undoes a finalized run', async () => { + const tx = new FileTransaction(stateDir, { syncDir: syncDirStrict, removeDir: held }); + await write('a.txt', 'a1\n', tx); + await write('new.txt', 'n1\n', tx); + await tx.dispose(); + // The delete never ran: the record is still complete, under the committed name. + expect(existsSync(tx.dir)).toBe(false); + expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); + + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + expect(read('new.txt')).toBe('n1\n'); + // Recovery deletes what a finalized run left behind. + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + }); + + it('reports a committed but not flushed journal and never rolls it back', async () => { + let failing = false; + const io: JournalIo = { + syncDir: async () => { + if (failing) throw new Error('EIO: flush failed'); + }, + removeDir: held, + }; + const tx = new FileTransaction(stateDir, io); + await write('a.txt', 'a1\n', tx); + failing = true; + const err = await tx.dispose().then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(TransactionFinalizeError); + expect(err).toMatchObject({ committed: true }); + expect(String(err)).toMatch(/durability is not guaranteed/); + // Asked again, finalization settles the same way. + await expect(tx.dispose()).rejects.toBe(err); + expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); + expect(await tx.rollback()).toEqual({ restored: [], skipped: [] }); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + }); + + it('refuses the write when its journal record cannot be flushed', async () => { + const tx = new FileTransaction(stateDir, { + syncDir: async () => { + throw new Error('EIO: flush failed'); + }, + removeDir: held, + }); + await expect(write('a.txt', 'a1\n', tx)).rejects.toThrow(/EIO/); + expect(read('a.txt')).toBe('a0\n'); + }); + + it('keeps the journal open for a rollback when the commit rename fails', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + // A non-empty directory in the way makes the rename fail. + mkdirSync(path.join(`${tx.dir}${COMMITTED}`, 'blocker'), { recursive: true }); + const err = await tx.dispose().then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(TransactionFinalizeError); + expect(err).toMatchObject({ committed: false }); + expect(existsSync(path.join(tx.dir, 'manifest.json'))).toBe(true); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'a.txt')]); + expect(read('a.txt')).toBe('a0\n'); + }); +}); diff --git a/src/tools/journal.ts b/src/tools/journal.ts new file mode 100644 index 0000000..5876aa9 --- /dev/null +++ b/src/tools/journal.ts @@ -0,0 +1,556 @@ +/* + * The journal design (original bytes written durably before the first change, + * restore only files that still hold what this process wrote, recovery of a + * record whose process is gone) follows Turnpack's src/journal.ts + * (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). + * Modified by the agent-code-mode authors: the record grows one file at a time + * across a run instead of being written once per call, and it is restored + * through the workspace jail checks of this project. + */ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { z } from 'zod'; +import { ToolError, TransactionFinalizeError, errorMessage } from '../core/errors.js'; +import type { RollbackReport, Transaction } from '../core/types.js'; +import { + type RegularFile, + assertDirUnchanged, + atomicWrite, + errnoCode, + readRegularFile, + removeEmptyDirInside, + removeRegularFile, + sha256, + syncDirStrict, + writeDurable, +} from './fs-ops.js'; +import { findMatchingPattern } from '../core/paths.js'; +import { expandTilde, isInsideDir, isInsideGitDir } from './jail.js'; + +/** Above this many bytes of originals a transaction refuses further writes. */ +export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024; +/** Slack when comparing a start time with the boot time. */ +const BOOT_SLACK_MS = 10_000; +const MANIFEST = 'manifest.json'; +const RECOVERING = '.recovering-'; +/** + * Suffix of a finalized transaction directory. Renaming `` to + * `.committed` is the commit point: recovery never undoes such a + * directory, whatever is left in it, and only deletes it. + */ +export const COMMITTED = '.committed'; + +const EntrySchema = z.object({ + path: z.string().min(1), + existed: z.boolean(), + /** SHA-256 of the original bytes ('' when absent). */ + original: z.string(), + mode: z.number().int().nullable(), + /** Blob file name holding the original bytes (null when absent). */ + blob: z.string().regex(/^[0-9]+\.bin$/).nullable(), + /** Hashes this transaction wrote (or was about to write) to the file, oldest first. */ + written: z.array(z.string()), + /** Wall-clock time (ms) of the latest write to the file; recovery undoes writes newest first across journals. */ + at: z.number().optional(), +}); + +const ManifestSchema = z.object({ + version: z.literal(1), + pid: z.number().int(), + host: z.string(), + startedAt: z.number(), + roots: z.array(z.string()), + /** Directories the transaction created, outermost first. */ + dirs: z.array(z.string()), + entries: z.array(EntrySchema), +}); + +type Manifest = z.infer; +type Entry = z.infer; + +/** Journal directory under the server state dir. */ +export function journalRoot(stateDir: string): string { + return path.join(stateDir, 'journal'); +} + +/** File system steps of finalization; replaceable in tests. */ +export interface JournalIo { + /** fsyncs a directory and rejects when that fails. */ + readonly syncDir: (dir: string) => Promise; + /** Deletes a finalized transaction directory. */ + readonly removeDir: (dir: string) => Promise; +} + +const defaultIo: JournalIo = { + syncDir: syncDirStrict, + removeDir: (dir) => fs.rm(dir, { recursive: true, force: true }), +}; + +/** Ids of transactions this process still has open; a recovery pass leaves them alone. */ +const openTransactions = new Set(); + +const TXID = /^[0-9a-z]+-\d+-[0-9a-f]+$/; + +function writeTime(): number { + return performance.timeOrigin + performance.now(); +} + +/** + * Throws unless `dir` is a real directory (not a link) that only this user + * can write: journals are restored from and deleted in it. + */ +async function assertPrivateDir(dir: string): Promise { + const st = await fs.lstat(dir); + if (st.isSymbolicLink() || !st.isDirectory()) throw new ToolError('tool-error', `journal directory ${dir} is not a real directory`); + if (process.platform === 'win32') return; + const uid = process.getuid?.(); + if ((uid !== undefined && st.uid !== uid) || (st.mode & 0o022) !== 0) { + throw new ToolError('tool-error', `journal directory ${dir} is not private to this user (owner ${st.uid}, mode ${(st.mode & 0o777).toString(8)})`); + } +} + +interface LiveEntry { + readonly entry: Entry; + /** Original bytes, kept in memory for the in-process rollback. */ + readonly bytes: Buffer | null; + /** Hash of what this transaction last wrote, or null after a failed write. */ + last: string | null; +} + +/** How finalization ended, once it did. */ +type Finalized = { readonly durable: true } | { readonly durable: false; readonly error: TransactionFinalizeError }; + +/** + * A per-run journal. The first write to a file snapshots its original bytes + * (or "absent") in memory and durably under `/journal//` + * before the file is touched. + */ +export class FileTransaction implements Transaction { + readonly id: string; + readonly dir: string; + readonly #roots: string[] = []; + readonly #startedAt = Date.now(); + readonly #entries = new Map(); + readonly #dirs: string[] = []; + /** Directories this transaction's writes really created; only those are removed by the in-process rollback. */ + readonly #ownDirs = new Set(); + #bytes = 0; + #created = false; + #closed = false; + #finalized: Finalized | undefined; + #queue: Promise = Promise.resolve(); + readonly #io: JournalIo; + + constructor(stateDir: string, io: JournalIo = defaultIo) { + this.#io = io; + this.id = `${this.#startedAt.toString(36)}-${process.pid}-${randomBytes(4).toString('hex')}`; + this.dir = path.join(journalRoot(stateDir), this.id); + openTransactions.add(this.id); + } + + /** True once rolled back or disposed. */ + get closed(): boolean { + return this.#closed; + } + + #serial(fn: () => Promise): Promise { + const next = this.#queue.then(fn, fn); + this.#queue = next.catch(() => undefined); + return next; + } + + #manifest(): Manifest { + return { + version: 1, + pid: process.pid, + host: os.hostname(), + startedAt: this.#startedAt, + roots: [...this.#roots], + dirs: [...this.#dirs], + entries: [...this.#entries.values()].map((live) => live.entry), + }; + } + + /** Writes the manifest; once it resolves, the record survives a crash (where directories can be flushed). */ + async #persist(): Promise { + if (!this.#created) { + const root = path.dirname(this.dir); + await fs.mkdir(root, { recursive: true, mode: 0o700 }); + await assertPrivateDir(root); + await this.#io.syncDir(path.dirname(root)); + await fs.mkdir(this.dir, { mode: 0o700 }); + this.#created = true; + await this.#io.syncDir(root); + } + const next = path.join(this.dir, `${MANIFEST}.next`); + await writeDurable(next, JSON.stringify(this.#manifest())); + await fs.rename(next, path.join(this.dir, MANIFEST)); + await this.#io.syncDir(this.dir); + } + + /** + * Called by a commit after the stale check and before the write. Records + * the original on the first write to `absPath` and the hash about to be + * written. Throws when the journal is full or closed. + */ + record( + absPath: string, + root: string, + before: { readonly bytes: Buffer; readonly mode: number } | null, + nextHash: string, + createdDirs: readonly string[], + ): Promise { + return this.#serial(async () => { + if (this.#closed) throw new ToolError('tool-error', 'the transaction is already finished'); + if (!this.#roots.includes(root)) this.#roots.push(root); + const existing = this.#entries.get(absPath); + if (existing) { + // Another writer changed the file since this transaction last wrote it: restoring the + // original later would discard that change, so the write is refused. + const current = before ? sha256(before.bytes) : null; + const ours = existing.last ?? (existing.entry.existed ? existing.entry.original : null); + if (current !== ours) { + throw new ToolError('stale', `${absPath} was changed by another writer since this transaction last wrote it`); + } + existing.entry.written.push(nextHash); + existing.entry.at = writeTime(); + await this.#persist(); + return; + } + const size = before?.bytes.length ?? 0; + if (this.#bytes + size > MAX_JOURNAL_BYTES) { + throw new ToolError( + 'tool-error', + `transaction journal is full: snapshotting ${absPath} (${size} bytes) would exceed ${MAX_JOURNAL_BYTES} bytes, so the write was refused to keep rollback possible`, + ); + } + let blob: string | null = null; + if (before) { + if (!this.#created) await this.#persist(); + blob = `${this.#entries.size}.bin`; + await writeDurable(path.join(this.dir, blob), before.bytes); + } + this.#bytes += size; + for (const d of createdDirs) if (!this.#dirs.includes(d)) this.#dirs.push(d); + this.#entries.set(absPath, { + entry: { + path: absPath, + existed: before !== null, + original: before ? sha256(before.bytes) : '', + mode: before?.mode ?? null, + blob, + written: [nextHash], + at: writeTime(), + }, + bytes: before?.bytes ?? null, + last: null, + }); + await this.#persist(); + }); + } + + /** Called after a successful write, with the directories it created. */ + written(absPath: string, hash: string, createdDirs: readonly string[] = []): void { + const live = this.#entries.get(absPath); + if (live) live.last = hash; + for (const d of createdDirs) this.#ownDirs.add(d); + } + + rollback(): Promise { + return this.#serial(async () => { + if (this.#closed) return { restored: [], skipped: [] }; + this.#closed = true; + openTransactions.delete(this.id); + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; + for (const live of [...this.#entries.values()].reverse()) { + const { entry } = live; + try { + const current = await currentContent(entry.path); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) continue; + if (live.last === null || currentHash !== live.last) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what this run wrote' }); + continue; + } + await restoreEntry(entry, live.bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } + } + await removeCreatedDirs( + this.#dirs.filter((d) => this.#ownDirs.has(d)), + this.#roots, + ); + // A file whose restore failed keeps the record, so a recovery pass can still restore it. + if (skipped.some((s) => s.reason === 'error')) await this.#flushRecord(); + else await this.#removeRecord(); + return { restored, skipped }; + }); + } + + /** + * Commits the journal: renames its directory to `.committed`, which + * recovery never undoes, then fsyncs the journal root so the rename is + * durable. The recursive delete of the renamed directory runs afterwards + * and is not awaited. Rejects with `TransactionFinalizeError`: not + * committed when the rename failed (the journal stays open for a + * rollback), committed when only the fsync failed. Called again, it + * settles the same way. + */ + dispose(): Promise { + return this.#serial(async () => { + if (this.#finalized) { + if (this.#finalized.durable) return; + throw this.#finalized.error; + } + if (this.#closed) return; + if (!this.#created) { + this.#closed = true; + this.#finalized = { durable: true }; + openTransactions.delete(this.id); + return; + } + const committed = `${this.dir}${COMMITTED}`; + try { + await fs.rename(this.dir, committed); + } catch (err) { + throw new TransactionFinalizeError(false, `could not finalize the transaction journal: ${errorMessage(err)}`); + } + this.#closed = true; + this.#created = false; + openTransactions.delete(this.id); + try { + await this.#io.syncDir(path.dirname(this.dir)); + } catch (err) { + // The committed record stays: recovery deletes it without undoing anything. + const error = new TransactionFinalizeError( + true, + `the transaction journal was finalized, but flushing it to disk failed (${errorMessage(err)}); the changes are on disk, but their durability is not guaranteed`, + ); + this.#finalized = { durable: false, error }; + throw error; + } + this.#finalized = { durable: true }; + void this.#io.removeDir(committed).catch(() => undefined); + }); + } + + /** Keeps the record on disk for a recovery pass and stops tracking it here. */ + async #flushRecord(): Promise { + if (!this.#created) return; + await this.#persist().catch(() => undefined); + this.#created = false; + } + + async #removeRecord(): Promise { + if (!this.#created) return; + await fs.rm(this.dir, { recursive: true, force: true }); + this.#created = false; + } +} + +/** + * Content at `abs`, read only through real directories: null when the file + * (or its directory) is gone; `stale` when its directory now resolves + * elsewhere (a link was swapped in), so nothing outside is read or touched. + */ +async function currentContent(abs: string): Promise { + const parent = await fs.lstat(path.dirname(abs)).catch(() => null); + if (!parent) return null; + await assertDirUnchanged(path.dirname(abs)); + return readRegularFile(abs); +} + +async function restoreEntry(entry: Entry, bytes: Buffer | null, currentHash: string | null): Promise { + if (isInsideGitDir(entry.path)) throw new ToolError('protected-path', 'inside a .git directory'); + if (!entry.existed) { + if (currentHash !== null) await removeRegularFile(entry.path, currentHash); + return; + } + if (bytes === null || sha256(bytes) !== entry.original) throw new ToolError('tool-error', 'the saved original is damaged'); + const expect = currentHash === null ? ({ kind: 'absent' } as const) : ({ kind: 'hash', sha256: currentHash } as const); + await atomicWrite(entry.path, bytes, expect, entry.mode !== null ? { mode: entry.mode } : {}); +} + +/** Removes created directories that are empty, real and strictly inside `roots`, deepest first. */ +async function removeCreatedDirs(dirs: readonly string[], roots: readonly string[]): Promise { + for (const d of [...dirs].sort((a, b) => b.length - a.length)) await removeEmptyDirInside(d, roots); +} + +// --------------------------------------------------------------------------- +// Crash recovery. +// --------------------------------------------------------------------------- + +function isAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return errnoCode(err) === 'EPERM'; + } +} + +/** Whether the process that wrote a record can no longer be running it. */ +function ownerGone(manifest: Manifest, openHere: ReadonlySet, id: string): boolean { + if (manifest.pid === process.pid) return !openHere.has(id); + if (!isAlive(manifest.pid)) return true; + // A pid alone does not say: the system hands a dead process's id to a new one. + const bootedAt = Date.now() - os.uptime() * 1000; + return bootedAt > manifest.startedAt + BOOT_SLACK_MS; +} + +/** What a recovery pass did for one stale journal. */ +export interface RecoveredJournal { + readonly id: string; + readonly report: RollbackReport; +} + +async function realOrSelf(p: string): Promise { + try { + return await fs.realpath(p); + } catch { + return p; + } +} + +async function readOriginal(dir: string, entry: Entry): Promise { + if (entry.blob === null) return null; + return fs.readFile(path.join(dir, entry.blob)); +} + +/** A claimed stale journal and what undoing it has done so far. */ +interface Claimed { + readonly id: string; + readonly dir: string; + readonly manifest: Manifest; + readonly restored: string[]; + readonly skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[]; +} + +async function undoEntry(record: Claimed, entry: Entry, roots: readonly string[], protectedPaths: readonly string[]): Promise { + const { manifest, dir, restored, skipped } = record; + try { + // The record is data on disk: each path is checked like a tool argument. + if (!path.isAbsolute(entry.path) || !roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the workspace roots; not touched' }); + return; + } + if (!manifest.roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); + return; + } + const hit = findMatchingPattern(entry.path, protectedPaths); + if (hit !== undefined) { + skipped.push({ path: entry.path, reason: 'error', detail: `a protected host policy path (${hit}); not touched` }); + return; + } + const current = await currentContent(entry.path); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) return; + if (currentHash === null || !entry.written.includes(currentHash)) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what the crashed run wrote' }); + return; + } + const bytes = await readOriginal(dir, entry); + await restoreEntry(entry, bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } +} + +function isCommitted(name: string): boolean { + return name.endsWith(COMMITTED); +} + +/** + * Restores every journal left by a server process that is gone and that + * touched one of `roots`. Writes are undone newest first across journals, so + * two cut-off runs that changed the same file unwind in order. Files are + * restored only when they still hold what that run wrote and are not + * protected by `protectedPaths` (host policy patterns, `~` expanded); + * anything else is reported in `skipped`. A journal with a file that could not + * be handled is kept for a later pass. Nothing is read or deleted unless the + * journal directory is private to this user. Never throws. + */ +export async function recoverStaleJournals( + stateDir: string, + roots: readonly string[], + protectedPaths: readonly string[], +): Promise { + const base = journalRoot(stateDir); + let names: string[]; + try { + await assertPrivateDir(base); + names = await fs.readdir(base); + } catch { + return []; + } + const realRoots = await Promise.all(roots.filter((r) => path.isAbsolute(r)).map(realOrSelf)); + const patterns = protectedPaths.map((p) => expandTilde(p)); + // A finalized run is never undone, whatever its directory still holds; it is only deleted. + for (const name of names.filter(isCommitted)) { + if (!TXID.test(name.slice(0, -COMMITTED.length))) continue; + const dir = path.join(base, name); + const st = await fs.lstat(dir).catch(() => null); + if (st?.isDirectory()) await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined); + } + // The id pattern below also rejects `.committed`, so a finalized run is never read as pending. + const records = names + .map((name) => ({ name, id: name.includes(RECOVERING) ? name.slice(0, name.indexOf(RECOVERING)) : name })) + .filter((r) => TXID.test(r.id)); + const claimed: Claimed[] = []; + for (const record of records) { + const dir = path.join(base, record.name); + try { + const st = await fs.lstat(dir); + if (st.isSymbolicLink() || !st.isDirectory()) continue; + const raw: unknown = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), 'utf8')); + const parsed = ManifestSchema.safeParse(raw); + if (!parsed.success) continue; + const manifest = parsed.data; + if (manifest.host !== os.hostname()) continue; + if (!manifest.roots.some((r) => realRoots.some((root) => isInsideDir(root, r) || isInsideDir(r, root)))) continue; + if (record.name.includes(RECOVERING)) { + const claimer = Number(record.name.slice(record.name.indexOf(RECOVERING) + RECOVERING.length)); + if (claimer !== process.pid && isAlive(claimer)) continue; + } else if (!ownerGone(manifest, openTransactions, record.id)) { + continue; + } + const target = path.join(base, `${record.id}${RECOVERING}${process.pid}`); + if (target !== dir) { + try { + await fs.rename(dir, target); + } catch { + continue; + } + } + claimed.push({ id: record.id, dir: target, manifest, restored: [], skipped: [] }); + } catch { + // One bad record must not stop the others. + } + } + const writes = claimed + .flatMap((record) => record.manifest.entries.map((entry) => ({ record, entry }))) + .sort((a, b) => (b.entry.at ?? b.record.manifest.startedAt) - (a.entry.at ?? a.record.manifest.startedAt)); + for (const { record, entry } of writes) await undoEntry(record, entry, realRoots, patterns); + const out: RecoveredJournal[] = []; + for (const record of claimed) { + try { + // The journal contains planned directory names and cannot establish ownership after a crash. + // A file that could not be handled keeps the record for a later pass. + if (!record.skipped.some((s) => s.reason === 'error')) await fs.rm(record.dir, { recursive: true, force: true }); + out.push({ id: record.id, report: { restored: record.restored, skipped: record.skipped } }); + } catch { + // One bad record must not stop the others. + } + } + return out; +} diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts new file mode 100644 index 0000000..877ea0e --- /dev/null +++ b/src/tools/runtime.test.ts @@ -0,0 +1,507 @@ +import { spawnSync } from 'node:child_process'; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, PreparedCall, SessionContext, ToolArgsMap, ToolCall, ToolName, ToolResult } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { windowsPathProblem } from './jail.js'; +import { NodeToolRuntime } from './runtime.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let outside: string; +let ctx: SessionContext; +let policy: PolicySnapshot; +let rt: NodeToolRuntime; +let outsideBefore: Record; +let seq = 0; + +/** Every entry under `dir` with its type and content (links are not followed). */ +function snapshot(dir: string): Record { + const out: Record = {}; + const walk = (d: string): void => { + for (const name of readdirSync(d)) { + const p = path.join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) out[p] = `link:${readlinkSync(p)}`; + else if (st.isDirectory()) { + out[p] = 'dir'; + walk(p); + } else out[p] = `file:${readFileSync(p, 'utf8')}`; + } + }; + walk(dir); + return out; +} + +function call(tool: K, args: ToolArgsMap[K]): ToolCall { + return { id: `c${++seq}`, tool, args } as ToolCall; +} + +async function prep(tool: K, args: ToolArgsMap[K]): Promise { + return rt.prepare(call(tool, args), ctx, policy); +} + +async function run(tool: K, args: ToolArgsMap[K]): Promise { + return rt.commit(await prep(tool, args), new AbortController().signal); +} + +async function code(p: Promise): Promise { + try { + await p; + } catch (err) { + if (err instanceof ToolError) return err.code; + throw err; + } + return 'resolved'; +} + +function link(target: string, at: string): void { + symlinkSync(target, at, statSync(target, { throwIfNoEntry: false })?.isDirectory() ? 'dir' : 'file'); +} + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(ws); + mkdirSync(outside); + writeFileSync(path.join(outside, 'secret.txt'), 'secret value\n'); + mkdirSync(path.join(outside, 'deep')); + writeFileSync(path.join(outside, 'deep', 'more.txt'), 'secret value too\n'); + ctx = makeContext(ws); + policy = { + host: 'generic', + bashContainment: { mode: 'none' }, + protectedPaths: [`${ws}/.claude/settings*.json`, `${ws}/.claude/hooks/**`, `${ws}/.codex/**`, `${ws}/.mcp.json`], + payload: null, + }; + rt = new NodeToolRuntime({ stateDir: path.join(base, 'state') }); + outsideBefore = snapshot(outside); +}); + +afterEach(() => { + // Every attack test also asserts that nothing outside the jail changed. + expect(snapshot(outside)).toEqual(outsideBefore); + rmSync(base, { recursive: true, force: true }); +}); + +describe('path traversal', () => { + it('refuses ../, absolute paths outside and ~', async () => { + // `..` after a missing component fails as the operating system would. + expect(await code(prep('write', { path: 'a/../../outside/new.txt', content: 'x' }))).toBe('not-found'); + for (const p of ['../outside/secret.txt', `${outside}/secret.txt`, '~/acm-must-not-exist.txt', '~']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'x' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'secret', path: '..' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '**/*', path: outside }))).toBe('outside-workspace'); + expect(await code(prep('bash', { command: 'pwd', cwd: '../outside' }))).toBe('outside-workspace'); + expect(existsSync(path.join(os.homedir(), 'acm-must-not-exist.txt'))).toBe(false); + }); + + it('refuses NUL bytes and very long paths', async () => { + expect(await code(prep('write', { path: 'a\0b', content: 'x' }))).toBe('invalid-args'); + const long = `${'a'.repeat(250)}/`.repeat(40) + 'f.txt'; + const result = await code(run('write', { path: long, content: 'x' })); + // Windows with long-path support accepts it; it must then be inside the workspace. + if (result === 'resolved') expect(readFileSync(path.join(ws, long), 'utf8')).toBe('x'); + else { + expect(['invalid-args', 'tool-error']).toContain(result); + expect(readdirSync(ws)).toEqual([]); + } + }); + + it('keeps unicode lookalikes of .. inside the workspace', async () => { + for (const p of ['\u2025/outside/x.txt', '\uff0e\uff0e/outside/x.txt', '.\u2024/outside/x.txt']) { + const prepared = await prep('write', { path: p, content: 'x' }); + expect(prepared.tool === 'write' && prepared.effect.absPath.startsWith(`${ws}${path.sep}`)).toBe(true); + } + }); + + it('flags Windows alias spellings', () => { + expect(windowsPathProblem('\\\\?\\C:\\x')).not.toBeNull(); + expect(windowsPathProblem('\\\\server\\share\\x')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.env::$DATA')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\file.txt:stream')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.git.\\config')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\src\\a.ts')).toBeNull(); + }); +}); + +describe.skipIf(IS_WINDOWS)('symlinks', () => { + beforeEach(() => { + link(outside, path.join(ws, 'link-out')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'file-link')); + symlinkSync(path.join(outside, 'not-yet.txt'), path.join(ws, 'dangling')); + writeFileSync(path.join(ws, 'inside.txt'), 'inside secret value\n'); + }); + + it('does not let read, write or edit follow a link out', async () => { + for (const p of ['file-link', 'link-out/secret.txt', 'link-out/deep/more.txt', 'dangling', 'link-out/new.txt']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'pwned' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'pwned' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'x', path: 'link-out' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '*', path: 'link-out' }))).toBe('outside-workspace'); + expect(existsSync(path.join(outside, 'not-yet.txt'))).toBe(false); + }); + + it('does not let grep or glob walk through links', async () => { + const grep = await run('grep', { pattern: 'secret' }); + expect('matches' in grep ? grep.matches.map((m) => m.file) : []).toEqual([path.join(ws, 'inside.txt')]); + const glob = await run('glob', { pattern: '**/*' }); + expect('files' in glob ? glob.files : []).toEqual([path.join(ws, 'inside.txt')]); + }); + + it('refuses a write when the file was swapped for a link after prepare', async () => { + writeFileSync(path.join(ws, 'f.txt'), 'one\n'); + const write = await prep('write', { path: 'f.txt', content: 'pwned\n' }); + const edit = await prep('edit', { path: 'f.txt', oldString: 'one', newString: 'pwned' }); + const read = await prep('read', { path: 'f.txt' }); + rmSync(path.join(ws, 'f.txt')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'f.txt')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(edit, signal))).toBe('stale'); + expect(await code(rt.commit(read, signal))).toBe('stale'); + }); + + it('refuses a create when a link appears at the name after prepare', async () => { + const write = await prep('write', { path: 'new.txt', content: 'pwned\n' }); + symlinkSync(path.join(outside, 'created-by-link.txt'), path.join(ws, 'new.txt')); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'created-by-link.txt'))).toBe(false); + }); + + it('refuses a write when a parent directory was replaced by a link after prepare', async () => { + mkdirSync(path.join(ws, 'dir')); + writeFileSync(path.join(ws, 'dir', 'secret.txt'), 'secret value\n'); + const write = await prep('write', { path: 'dir/secret.txt', content: 'pwned\n' }); + const create = await prep('write', { path: 'dir/fresh.txt', content: 'pwned\n' }); + const nested = await prep('write', { path: 'dir/a/b/c.txt', content: 'pwned\n' }); + renameSync(path.join(ws, 'dir'), path.join(ws, 'dir-moved')); + link(outside, path.join(ws, 'dir')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(create, signal))).toBe('stale'); + expect(await code(rt.commit(nested, signal))).toBe('stale'); + }); + + it('refuses writing through a link that bash created mid-run', async () => { + const pending = await prep('write', { path: 'via-later.txt', content: 'pwned\n' }); + const bash = await run('bash', { command: `ln -s ${JSON.stringify(path.join(outside, 'secret.txt'))} via.txt && ln -s ${JSON.stringify(path.join(outside, 'later.txt'))} via-later.txt` }); + expect('exitCode' in bash && bash.exitCode).toBe(0); + expect(await code(prep('write', { path: 'via.txt', content: 'pwned\n' }))).toBe('outside-workspace'); + expect(await code(rt.commit(pending, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'later.txt'))).toBe(false); + }); + + it('follows links that stay inside the workspace', async () => { + link(path.join(ws, 'inside.txt'), path.join(ws, 'alias.txt')); + const read = await run('read', { path: 'alias.txt' }); + expect('content' in read && read.path).toBe(path.join(ws, 'inside.txt')); + }); +}); + +describe('protected paths', () => { + it('refuses writes and edits to host config and .git, but allows reads', async () => { + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.git', 'config'), '[core]\n'); + mkdirSync(path.join(ws, '.claude')); + writeFileSync(path.join(ws, '.claude', 'settings.json'), '{}\n'); + for (const p of ['.claude/settings.json', '.claude/settings.local.json', '.codex/config.toml', '.git/config', '.git/hooks/pre-commit', 'sub/.git/config', '.mcp.json']) { + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('protected-path'); + } + expect(await code(prep('edit', { path: '.git/config', oldString: '[core]', newString: '[x]' }))).toBe('protected-path'); + expect(await code(prep('edit', { path: '.claude/settings.json', oldString: '{}', newString: '{"x":1}' }))).toBe('protected-path'); + const read = await run('read', { path: '.git/config' }); + expect('content' in read && read.content).toBe('[core]'); + expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); + }); + + it.skipIf(IS_WINDOWS)('matches patterns written through an alias of the workspace', async () => { + const alias = path.join(base, 'alias'); + link(ws, alias); + const aliasCtx = makeContext(alias); + const p = { ...policy, protectedPaths: [`${alias}/.claude/settings*.json`, `${alias}/.codex/**`] }; + expect(await code(rt.prepare(call('write', { path: '.claude/settings.json', content: '{}' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: '.codex/config.toml', content: '' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: 'ok.txt', content: '' }), aliasCtx, p))).toBe('resolved'); + }); + + it('expands ~ in protected patterns', async () => { + const home = path.join(ws, 'home'); + mkdirSync(home); + const homeCtx = makeContext(ws); + const p = { ...policy, protectedPaths: [`~/.claude/**`] }; + const prevHome = process.env['HOME']; + process.env['HOME'] = home; + try { + if (os.homedir() !== home) return; // os.homedir ignores HOME on this platform + expect(await code(rt.prepare(call('write', { path: 'home/.claude/x.json', content: '1' }), homeCtx, p))).toBe('protected-path'); + } finally { + process.env['HOME'] = prevHome; + } + }); +}); + +describe('write and edit', () => { + it('refuses an ambiguous edit without writing', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\ny = 2\nx = 1\n'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 3' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'nothing like it', newString: 'z' }))).toBe('not-found'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1\ny = 2\nx = 1\n'); + }); + + it('refuses a commit when the file changed after prepare', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\n'); + const edit = await prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 2' }); + const write = await prep('write', { path: 'a.ts', content: 'overwritten\n' }); + writeFileSync(path.join(ws, 'a.ts'), 'x = 1 // changed\n'); + expect(await code(rt.commit(edit, new AbortController().signal))).toBe('stale'); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1 // changed\n'); + + const create = await prep('write', { path: 'b.ts', content: 'mine\n' }); + writeFileSync(path.join(ws, 'b.ts'), 'theirs\n'); + expect(await code(rt.commit(create, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'b.ts'), 'utf8')).toBe('theirs\n'); + }); + + it('applies a tolerant edit and carries the exact matched text and diff', async () => { + writeFileSync(path.join(ws, 'f.js'), 'function f() {\n if (x) {\n return 1;\n }\n}\n'); + const prepared = await prep('edit', { path: 'f.js', oldString: 'if (x) {\n return 1;\n}', newString: 'if (x) {\n return 2;\n}' }); + if (prepared.tool !== 'edit') throw new Error('unreachable'); + expect(prepared.effect.matchStrategy).toBe('indentation-flexible'); + expect(prepared.effect.matchedOldString).toBe(' if (x) {\n return 1;\n }'); + expect(prepared.effect.diff).toContain('--- a/f.js\n+++ b/f.js\n'); + expect(prepared.effect.diff).toContain('- return 1;\n+ return 2;\n'); + const result = await rt.commit(prepared, new AbortController().signal); + expect('replacements' in result && result.replacements).toBe(1); + expect(readFileSync(path.join(ws, 'f.js'), 'utf8')).toBe(prepared.effect.afterContent); + }); + + it.skipIf(IS_WINDOWS)('writes atomically, keeps the mode and creates parents', async () => { + writeFileSync(path.join(ws, 'run.sh'), '#!/bin/sh\necho 1\n'); + chmodSync(path.join(ws, 'run.sh'), 0o751); + const result = await run('write', { path: 'run.sh', content: '#!/bin/sh\necho 2\n' }); + expect('created' in result && result.created).toBe(false); + expect(statSync(path.join(ws, 'run.sh')).mode & 0o777).toBe(0o751); + const created = await run('write', { path: 'new/deep/file.txt', content: 'hi' }); + expect('created' in created && created.created).toBe(true); + expect(readFileSync(path.join(ws, 'new/deep/file.txt'), 'utf8')).toBe('hi'); + expect(readdirSync(path.join(ws, 'new/deep'))).toEqual(['file.txt']); + }); + + it('refuses edits of binary files and directories', async () => { + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0, 1, 2, 3])); + mkdirSync(path.join(ws, 'd')); + expect(await code(prep('edit', { path: 'b.bin', oldString: 'a', newString: 'b' }))).toBe('tool-error'); + expect(await code(prep('write', { path: 'd', content: 'x' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'missing.txt', oldString: 'a', newString: 'b' }))).toBe('not-found'); + }); +}); + +describe('read', () => { + it('returns a window of lines and the total', async () => { + writeFileSync(path.join(ws, 'r.txt'), 'l1\nl2\nl3\nl4\n'); + const all = await run('read', { path: 'r.txt' }); + expect(all).toEqual({ path: path.join(ws, 'r.txt'), content: 'l1\nl2\nl3\nl4', startLine: 1, totalLines: 4, truncated: false }); + const part = await run('read', { path: 'r.txt', offset: 2, limit: 2 }); + expect(part).toEqual({ path: path.join(ws, 'r.txt'), content: 'l2\nl3', startLine: 2, totalLines: 4, truncated: true }); + }); + + it('caps the bytes returned and refuses binary files', async () => { + writeFileSync(path.join(ws, 'big.txt'), `${'x'.repeat(1000)}\n`.repeat(1000)); + const big = await run('read', { path: 'big.txt' }); + expect('content' in big && big.truncated).toBe(true); + expect('content' in big && Buffer.byteLength(big.content)).toBeLessThanOrEqual(256 * 1024); + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0x89, 0x50, 0, 0, 1])); + expect(await code(run('read', { path: 'b.bin' }))).toBe('tool-error'); + expect(await code(prep('read', { path: 'missing' }))).toBe('not-found'); + }); +}); + +describe('grep and glob', () => { + beforeEach(() => { + mkdirSync(path.join(ws, 'src')); + mkdirSync(path.join(ws, 'node_modules', 'dep'), { recursive: true }); + mkdirSync(path.join(ws, 'build')); + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.gitignore'), 'build/\n*.log\n!keep.log\n'); + writeFileSync(path.join(ws, 'src', 'a.ts'), 'const needle = 1;\nother\n'); + writeFileSync(path.join(ws, 'src', 'b.js'), 'needle again\n'); + writeFileSync(path.join(ws, 'src', 'nested.ts'), 'NEEDLE upper\n'); + writeFileSync(path.join(ws, 'node_modules', 'dep', 'i.js'), 'needle in deps\n'); + writeFileSync(path.join(ws, 'build', 'out.js'), 'needle built\n'); + writeFileSync(path.join(ws, 'debug.log'), 'needle log\n'); + writeFileSync(path.join(ws, 'keep.log'), 'needle kept\n'); + writeFileSync(path.join(ws, '.git', 'HEAD'), 'needle git\n'); + }); + + it('grep skips .git, node_modules and gitignored files', async () => { + const r = await run('grep', { pattern: 'needle' }); + if (!('matches' in r)) throw new Error('unreachable'); + expect(r.matches.map((m) => path.relative(ws, m.file)).sort()).toEqual(['keep.log', path.join('src', 'a.ts'), path.join('src', 'b.js')]); + const ci = await run('grep', { pattern: 'needle', ignoreCase: true, glob: '*.ts' }); + if (!('matches' in ci)) throw new Error('unreachable'); + expect(ci.matches.map((m) => [path.basename(m.file), m.line, m.text])).toEqual([ + ['a.ts', 1, 'const needle = 1;'], + ['nested.ts', 1, 'NEEDLE upper'], + ]); + const capped = await run('grep', { pattern: 'needle', maxResults: 1 }); + expect('matches' in capped && [capped.matches.length, capped.truncated]).toEqual([1, true]); + expect(await code(prep('grep', { pattern: '(' }))).toBe('invalid-args'); + }); + + it('glob lists sorted files with the same ignores', async () => { + const r = await run('glob', { pattern: '**/*.{ts,js}' }); + expect('files' in r && r.files).toEqual([path.join(ws, 'src', 'a.ts'), path.join(ws, 'src', 'b.js'), path.join(ws, 'src', 'nested.ts')]); + const capped = await run('glob', { pattern: '**/*', maxResults: 2 }); + expect('files' in capped && [capped.files.length, capped.truncated]).toEqual([2, true]); + expect(await code(prep('glob', { pattern: `${outside}/*` }))).toBe('invalid-args'); + }); +}); + +describe.skipIf(IS_WINDOWS)('bash cwd', () => { + it('moves a non-default cwd into the command and keeps the effect cwd at the session cwd', async () => { + mkdirSync(path.join(ws, "it's here")); + const prepared = await prep('bash', { command: 'pwd', cwd: "it's here" }); + if (prepared.tool !== 'bash') throw new Error('unreachable'); + expect(prepared.effect.cwd).toBe(ws); + expect(prepared.effect.command).toBe(`cd -- '${ws}/it'\\''s here' || exit 1\npwd`); + expect(prepared.args.command).toBe(prepared.effect.command); + expect(prepared.effect.timeoutMs).toBe(120_000); + const result = await rt.commit(prepared, new AbortController().signal); + expect('stdout' in result && result.stdout.trim()).toBe(path.join(ws, "it's here")); + const same = await prep('bash', { command: 'pwd', cwd: '.' }); + expect(same.tool === 'bash' && same.effect.command).toBe('pwd'); + }); + + it('runs nothing of the command when its cwd is gone at commit', async () => { + mkdirSync(path.join(ws, 'gone')); + const prepared = await prep('bash', { command: 'echo first; echo second', cwd: 'gone' }); + rmSync(path.join(ws, 'gone'), { recursive: true }); + const result = await rt.commit(prepared, new AbortController().signal); + expect('exitCode' in result && [result.exitCode, result.stdout]).toEqual([1, '']); + }); +}); + +describe('protected paths and policy metadata', () => { + it('refuses a write that would create a protected directory', async () => { + policy = { ...policy, protectedPaths: [path.join(ws, 'locked')] }; + expect(await code(prep('write', { path: 'locked/inner/x.txt', content: 'x' }))).toBe('protected-path'); + expect(existsSync(path.join(ws, 'locked'))).toBe(false); + }); + + it.skipIf(IS_WINDOWS)('protects the target of a protected literal path that is a link', async () => { + writeFileSync(path.join(ws, 'real.json'), '{}'); + link(path.join(ws, 'real.json'), path.join(ws, 'config.json')); + policy = { ...policy, protectedPaths: [path.join(ws, 'config.json')] }; + expect(await code(prep('write', { path: 'real.json', content: 'x' }))).toBe('protected-path'); + }); + + it('refuses to commit a call it did not prepare', async () => { + const prepared = await prep('grep', { pattern: 'x' }); + await rt.commit(prepared, new AbortController().signal); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('tool-error'); + }); + + it('refuses a sandboxed bash when a protected pattern has no directory the sandbox can deny', async () => { + policy = { + ...policy, + protectedPaths: ['**/.env'], + bashContainment: { mode: 'sandbox', readOnly: false, writableRoots: [ws], network: false }, + }; + await expect(prep('bash', { command: 'true' })).rejects.toMatchObject({ code: 'containment-unavailable', message: expect.stringContaining('**/.env') }); + }); +}); + +describe('file names', () => { + it('keeps leading spaces as part of the name', async () => { + await run('write', { path: ' spaced.txt', content: 'x' }); + expect(readFileSync(path.join(ws, ' spaced.txt'), 'utf8')).toBe('x'); + expect(existsSync(path.join(ws, 'spaced.txt'))).toBe(false); + }); + + it.skipIf(IS_WINDOWS)('writes a file whose name is close to the length limit', async () => { + const name = `${'n'.repeat(250)}.txt`; + await run('write', { path: name, content: 'x' }); + expect(readFileSync(path.join(ws, name), 'utf8')).toBe('x'); + }); + + it.skipIf(IS_WINDOWS)('refuses to search through a link given as the search path', async () => { + mkdirSync(path.join(ws, 'dir')); + link(path.join(ws, 'dir'), path.join(ws, 'alias')); + expect(await code(prep('grep', { pattern: 'x', path: 'alias' }))).toBe('invalid-args'); + expect(await code(prep('glob', { pattern: '*', path: 'alias' }))).toBe('invalid-args'); + }); + + it('shows none of the file when an edit does not match', async () => { + writeFileSync(path.join(ws, 'code.ts'), 'const token = "abc123";\nexport default token;\n'); + const err = await prep('edit', { path: 'code.ts', oldString: 'const token = "abc124";', newString: 'x' }).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toMatchObject({ code: 'not-found' }); + expect(String(err)).not.toContain('abc123'); + }); +}); + +describe('search filters', () => { + const grepFiles = async (args: ToolArgsMap['grep']): Promise => { + const r = await run('grep', args); + return 'matches' in r ? r.matches.map((m) => path.relative(ws, m.file)) : []; + }; + + it('applies gitignore rules to names that begin with two dots', async () => { + writeFileSync(path.join(ws, '.gitignore'), '..cache\n'); + writeFileSync(path.join(ws, '..cache'), 'hit\n'); + writeFileSync(path.join(ws, 'kept.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['kept.txt']); + }); + + it('keeps ignoring files a directory negation does not re-include', async () => { + mkdirSync(path.join(ws, 'logs')); + writeFileSync(path.join(ws, 'logs', '.gitignore'), '*.log\n!sub/\n'); + mkdirSync(path.join(ws, 'logs', 'sub')); + writeFileSync(path.join(ws, 'logs', 'sub', 'x.log'), 'hit\n'); + writeFileSync(path.join(ws, 'logs', 'sub', 'x.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual([path.join('logs', 'sub', 'x.txt')]); + }); + + it('skips a .git file of a worktree', async () => { + writeFileSync(path.join(ws, '.git'), 'gitdir: hit\n'); + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['a.txt']); + const r = await run('glob', { pattern: '*' }); + expect('files' in r && r.files).toEqual([path.join(ws, 'a.txt')]); + }); + + it('applies the glob filter to a file given as the path', async () => { + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit', path: 'a.txt', glob: '*.ts' })).toEqual([]); + expect(await grepFiles({ pattern: 'hit', path: 'a.txt', glob: '*.txt' })).toEqual(['a.txt']); + }); + + it('skips files that are not valid UTF-8', async () => { + writeFileSync(path.join(ws, 'latin1.txt'), Buffer.from([0x68, 0x69, 0x74, 0x0a, 0xe9, 0xff, 0x0a])); + writeFileSync(path.join(ws, 'utf8.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['utf8.txt']); + }); + + it.skipIf(IS_WINDOWS || spawnSync('mkfifo', ['--help']).error !== undefined)('does not wait on a FIFO named .gitignore or written to', async () => { + spawnSync('mkfifo', [path.join(ws, '.gitignore')]); + spawnSync('mkfifo', [path.join(ws, 'pipe')]); + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['a.txt']); + expect(await code(prep('write', { path: 'pipe', content: 'x' }))).toBe('invalid-args'); + }); +}); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts new file mode 100644 index 0000000..670e22d --- /dev/null +++ b/src/tools/runtime.ts @@ -0,0 +1,429 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError, errorMessage } from '../core/errors.js'; +import type { + BashContainment, + MatchStrategy, + PolicySnapshot, + PreparedCall, + PreparedCallOf, + ReadResult, + SessionContext, + ToolCall, + ToolResult, + ToolRuntime, + Transaction, +} from '../core/types.js'; +import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, runBash, shellQuote } from './bash.js'; +import { binaryDiff, unifiedDiff } from './diff.js'; +import { applySearchReplace, type MatchHow } from './edit-match.js'; +import { type PathIdentity, type RegularFile, assertDirUnchanged, atomicWrite, captureIdentity, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; +import { FileTransaction } from './journal.js'; +import { Jail } from './jail.js'; +import { DEFAULT_GLOB_MAX_RESULTS, DEFAULT_GREP_MAX_RESULTS, compileGrep, normalizeGlob, runGlob, runGrep } from './search.js'; + +/** Default number of lines `read` returns. */ +export const DEFAULT_READ_LIMIT = 2000; +/** Most bytes of content one `read` returns. */ +export const READ_CAP_BYTES = 256 * 1024; +/** Largest file `read`, `write` (existing content) and `edit` load. */ +export const MAX_FILE_BYTES = 64 * 1024 * 1024; + +/** + * How each Turnpack rung is reported in the frozen `MatchStrategy` type, + * which has fewer names than the ladder has rungs. + */ +const STRATEGY: Record = { + exact: 'exact', + 'line-endings': 'whitespace-normalized', + 'line-numbers': 'line-trimmed', + 'trailing-whitespace': 'line-trimmed', + indentation: 'indentation-flexible', + punctuation: 'whitespace-normalized', +}; + +export interface NodeToolRuntimeOptions { + /** Server state directory; transaction journals live under `/journal/`. */ + readonly stateDir: string; + /** Extra absolute directories the tools may touch besides the session cwd and MCP roots. */ + readonly additionalRoots?: readonly string[]; + /** Bytes kept of each of bash stdout and stderr. */ + readonly bashOutputCapBytes?: number; + /** Time the grep regular expression may run on one file before grep fails. */ + readonly grepFileBudgetMs?: number; +} + +/** What `commit` needs to know about a call besides its frozen effect. */ +interface CallMeta { + /** Workspace root that contains the call's path. */ + readonly root: string; + /** Path shown in diffs. */ + readonly display: string; + /** Paths a sandboxed bash may never write. */ + readonly denyWrite: readonly string[]; + /** For write and edit: identity of the file and its directories at prepare. */ + readonly identity?: PathIdentity; +} + +/** Most prepared calls whose metadata is kept while they wait for commit. */ +const MAX_PENDING_META = 4096; + +function metaKey(prepared: PreparedCall): string { + return sha256(JSON.stringify([prepared.id, prepared.tool, prepared.effect])); +} + +class MetaStore { + readonly #map = new Map(); + + put(prepared: PreparedCall, meta: CallMeta): void { + const key = metaKey(prepared); + this.#map.delete(key); + this.#map.set(key, meta); + while (this.#map.size > MAX_PENDING_META) { + const oldest = this.#map.keys().next(); + if (oldest.done === true) break; + this.#map.delete(oldest.value); + } + } + + take(prepared: PreparedCall): CallMeta | undefined { + const key = metaKey(prepared); + const meta = this.#map.get(key); + this.#map.delete(key); + return meta; + } +} + +/** + * Paths the OS sandbox denies writing, covering every protected pattern: + * a literal pattern as itself, `dir/**` as `dir`, and any other wildcard + * pattern as the directory its literal prefix names (more than the pattern + * protects, never less). Throws `containment-unavailable` for a pattern with + * no absolute directory prefix, rather than running a command that could + * write what the pattern protects. + */ +function sandboxDenyWrite(patterns: readonly string[]): string[] { + const out: string[] = []; + for (const p of patterns) { + const base = p.endsWith('/**') ? p.slice(0, -3) : p; + const wild = base.search(/[*?[]/); + const literal = wild === -1 ? base : base.slice(0, base.lastIndexOf('/', wild)); + if (!path.isAbsolute(literal) || path.dirname(literal) === literal) { + throw new ToolError('containment-unavailable', `the bash sandbox cannot enforce the protected path pattern ${p}`); + } + if (!out.includes(literal)) out.push(literal); + } + return out; +} + +/** Any failure of the runtime reaches the dispatcher as a `ToolError`. */ +function asToolError(err: unknown): ToolError { + if (err instanceof ToolError) return err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') return new ToolError('invalid-args', `path is too long: ${errorMessage(err)}`); + if (code === 'ENOENT') return new ToolError('not-found', errorMessage(err)); + return new ToolError('tool-error', errorMessage(err)); +} + +function assertContainmentShape(c: BashContainment): void { + if (c.mode === 'sandbox' && c.writableRoots.some((r) => !path.isAbsolute(r))) { + throw new ToolError('containment-unavailable', 'bash containment has a writable root that is not absolute'); + } +} + +/** + * The real `ToolRuntime`: workspace jail, tolerant edit, atomic writes with + * stale checks, transactional rollback, and contained `bash`. + */ +export class NodeToolRuntime implements ToolRuntime { + readonly #opts: NodeToolRuntimeOptions; + /** + * What prepare learned about each call, keyed by a digest of the prepared + * call's content: the dispatcher hands commit a frozen copy, not the object + * prepare returned. Taken out at commit; bounded so calls that never commit + * (denied ones) do not accumulate. + */ + readonly #meta = new MetaStore(); + + constructor(opts: NodeToolRuntimeOptions) { + this.#opts = opts; + } + + async prepare(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + try { + return await this.#prepareInJail(call, ctx, policy); + } catch (err) { + throw asToolError(err); + } + } + + async #prepareInJail(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + const jail = await Jail.create({ + cwd: ctx.cwd, + roots: [...ctx.roots, ...(this.#opts.additionalRoots ?? [])], + protectedPaths: policy.protectedPaths, + }); + const meta = (abs: string, denyWrite: readonly string[] = []): CallMeta => ({ + root: jail.rootOf(abs) ?? jail.cwd, + display: jail.displayPath(abs), + denyWrite, + }); + return this.#prepare(call, jail, policy, meta); + } + + async #prepare( + call: ToolCall, + jail: Jail, + policy: PolicySnapshot, + meta: (abs: string, denyWrite?: readonly string[]) => CallMeta, + ): Promise { + switch (call.tool) { + case 'bash': { + let cwd = jail.cwd; + if (call.args.cwd !== undefined) { + cwd = await jail.resolve(call.args.cwd); + const st = await fs.stat(cwd).catch(() => null); + if (!st) throw new ToolError('not-found', `bash cwd ${call.args.cwd} does not exist`); + if (!st.isDirectory()) throw new ToolError('invalid-args', `bash cwd ${call.args.cwd} is not a directory`); + } + // What hooks see is exactly what runs: another cwd becomes part of the command. + // A cd that fails ends the whole command, whatever operators the command uses. + const command = cwd === jail.cwd ? call.args.command : `cd -- ${shellQuote(cwd)} || exit 1\n${call.args.command}`; + const timeoutMs = Math.min(call.args.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS); + const containment = policy.bashContainment; + assertContainmentShape(containment); + const denyWrite = containment.mode === 'sandbox' && !containment.readOnly ? sandboxDenyWrite(jail.protectedPaths) : []; + const prepared: PreparedCallOf<'bash'> = { + id: call.id, + tool: 'bash', + args: { command, timeoutMs }, + effect: { command, cwd: jail.cwd, timeoutMs, containment }, + }; + this.#meta.put(prepared, meta(jail.cwd, denyWrite)); + return prepared; + } + case 'read': { + const absPath = await jail.resolve(call.args.path); + await this.#assertFile(absPath, call.args.path); + const offset = call.args.offset ?? 1; + const limit = call.args.limit ?? DEFAULT_READ_LIMIT; + const prepared: PreparedCallOf<'read'> = { + id: call.id, + tool: 'read', + args: { path: absPath, offset, limit }, + effect: { absPath, offset, limit }, + }; + this.#meta.put(prepared, meta(absPath)); + return prepared; + } + case 'write': { + const absPath = await jail.resolveForWrite(call.args.path); + const m = { ...meta(absPath), identity: await captureIdentity(absPath, jail.rootOf(absPath) ?? jail.cwd) }; + const current = await this.#readExisting(absPath); + const diff = + current !== null && isBinary(current.bytes) + ? binaryDiff(m.display, true) + : unifiedDiff(m.display, current === null ? null : current.bytes.toString('utf8'), call.args.content); + const prepared: PreparedCallOf<'write'> = { + id: call.id, + tool: 'write', + args: { path: absPath, content: call.args.content }, + effect: { + absPath, + beforeHash: current === null ? null : sha256(current.bytes), + afterContent: call.args.content, + diff, + }, + }; + this.#meta.put(prepared, m); + return prepared; + } + case 'edit': { + const absPath = await jail.resolveForWrite(call.args.path); + const m = { ...meta(absPath), identity: await captureIdentity(absPath, jail.rootOf(absPath) ?? jail.cwd) }; + const current = await this.#readExisting(absPath); + if (current === null) throw new ToolError('not-found', `${m.display} does not exist`); + const text = decodeText(m.display, current.bytes); + if (call.args.oldString === call.args.newString) { + throw new ToolError('invalid-args', 'oldString and newString are the same; the edit would change nothing'); + } + const outcome = applySearchReplace(text, call.args.oldString, call.args.newString, call.args.replaceAll === true, MAX_FILE_BYTES); + if (!outcome.ok) { + // Nothing of the file's content is shown: the call is not authorized yet. + if (outcome.kind === 'not-found') { + throw new ToolError('not-found', `${m.display}: search text not found; read the file and write oldString from what is there`); + } + throw new ToolError(outcome.kind === 'too-large' ? 'tool-error' : 'invalid-args', `${m.display}: ${outcome.message}`); + } + const prepared: PreparedCallOf<'edit'> = { + id: call.id, + tool: 'edit', + args: { ...call.args, path: absPath }, + effect: { + absPath, + beforeHash: sha256(current.bytes), + afterContent: outcome.text, + diff: unifiedDiff(m.display, text, outcome.text), + matchedOldString: outcome.matched, + matchStrategy: STRATEGY[outcome.how], + replacements: outcome.count, + }, + }; + this.#meta.put(prepared, m); + return prepared; + } + case 'grep': { + const absRoot = await jail.resolveSearchRoot(call.args.path ?? '.'); + await this.#assertExists(absRoot, call.args.path ?? '.'); + const ignoreCase = call.args.ignoreCase ?? false; + compileGrep(call.args.pattern, ignoreCase); + const effect = { + absRoot, + pattern: call.args.pattern, + glob: call.args.glob ?? null, + ignoreCase, + maxResults: call.args.maxResults ?? DEFAULT_GREP_MAX_RESULTS, + }; + const prepared: PreparedCallOf<'grep'> = { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; + this.#meta.put(prepared, meta(absRoot)); + return prepared; + } + case 'glob': { + const absRoot = await jail.resolveSearchRoot(call.args.path ?? '.'); + const st = await this.#assertExists(absRoot, call.args.path ?? '.'); + if (!st.isDirectory()) throw new ToolError('invalid-args', `glob path ${call.args.path ?? '.'} is not a directory`); + normalizeGlob(call.args.pattern, absRoot); + const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? DEFAULT_GLOB_MAX_RESULTS }; + const prepared: PreparedCallOf<'glob'> = { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; + this.#meta.put(prepared, meta(absRoot)); + return prepared; + } + } + } + + async #assertExists(abs: string, shown: string): Promise { + const st = await fs.lstat(abs).catch((err: unknown) => { + if (errnoCode(err) === 'ENOENT' || errnoCode(err) === 'ENOTDIR') return null; + throw new ToolError('tool-error', `cannot stat ${shown}: ${errnoCode(err) ?? String(err)}`); + }); + if (!st) throw new ToolError('not-found', `${shown} does not exist`); + return st; + } + + async #assertFile(abs: string, shown: string): Promise { + const st = await this.#assertExists(abs, shown); + if (st.isDirectory()) throw new ToolError('invalid-args', `${shown} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${shown} is not a regular file`); + } + + async #readExisting(abs: string): Promise<{ bytes: Buffer; mode: number } | null> { + const st = await fs.lstat(abs).catch(() => null); + if (st?.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + return readRegularFile(abs, MAX_FILE_BYTES); + } + + /** What prepare recorded for the call; a call this runtime did not prepare (or already committed) is refused. */ + #metaOf(prepared: PreparedCall): CallMeta { + const meta = this.#meta.take(prepared); + if (meta === undefined) { + throw new ToolError('tool-error', `this ${prepared.tool} call was not prepared by this tool runtime (or was already committed); prepare it again`); + } + return meta; + } + + async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + try { + return await this.#commit(prepared, signal, tx); + } catch (err) { + throw asToolError(err); + } + } + + async #commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before commit'); + switch (prepared.tool) { + case 'bash': { + const m = this.#metaOf(prepared); + return runBash(prepared.effect, signal, { + ...(this.#opts.bashOutputCapBytes !== undefined ? { outputCapBytes: this.#opts.bashOutputCapBytes } : {}), + denyWrite: m.denyWrite, + }); + } + case 'read': + this.#metaOf(prepared); + return this.#commitRead(prepared); + case 'write': + case 'edit': + return this.#commitWrite(prepared, signal, tx); + case 'grep': { + const { root } = this.#metaOf(prepared); + await assertDirUnchanged(prepared.effect.absRoot); + return runGrep(prepared.effect, root, signal, this.#opts.grepFileBudgetMs); + } + case 'glob': { + const { root } = this.#metaOf(prepared); + await assertDirUnchanged(prepared.effect.absRoot); + return runGlob(prepared.effect, root, signal); + } + } + } + + async #commitRead(prepared: PreparedCallOf<'read'>): Promise { + const { absPath, offset, limit } = prepared.effect; + await assertDirUnchanged(path.dirname(absPath)); + const file = await readRegularFile(absPath, MAX_FILE_BYTES); + if (file === null) throw new ToolError('not-found', `${absPath} does not exist`); + const text = decodeText(absPath, file.bytes); + const lines = text === '' ? [] : text.split('\n'); + if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop(); + const window: string[] = []; + let bytes = 0; + let truncated = false; + for (let i = offset - 1; i < lines.length && window.length < limit; i++) { + const line = lines[i] ?? ''; + const size = Buffer.byteLength(line, 'utf8') + 1; + if (bytes + size > READ_CAP_BYTES) { + truncated = true; + break; + } + window.push(line); + bytes += size; + } + if (offset - 1 + window.length < lines.length) truncated = true; + return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated }; + } + + async #commitWrite( + prepared: PreparedCallOf<'write'> | PreparedCallOf<'edit'>, + signal: AbortSignal, + tx: Transaction | undefined, + ): Promise { + if (tx !== undefined && !(tx instanceof FileTransaction)) { + throw new ToolError('tool-error', 'the transaction was not started by this tool runtime; refusing to write without a journal'); + } + const { absPath, beforeHash, afterContent } = prepared.effect; + const m = this.#meta.take(prepared); + if (m?.identity === undefined) { + throw new ToolError('tool-error', 'this write was not prepared by this tool runtime (or was already committed); prepare it again'); + } + const bytes = Buffer.from(afterContent, 'utf8'); + const nextHash = sha256(bytes); + const outcome = await atomicWrite(absPath, bytes, beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, { + signal, + identity: m.identity, + ...(tx ? { beforeWrite: (before: RegularFile | null, createdDirs: readonly string[]) => tx.record(absPath, m.root, before, nextHash, createdDirs) } : {}), + }); + tx?.written(absPath, nextHash, outcome.createdDirs); + if (prepared.tool === 'write') return { path: absPath, created: outcome.before === null, diff: prepared.effect.diff }; + return { + path: absPath, + replacements: prepared.effect.replacements, + matchStrategy: prepared.effect.matchStrategy, + diff: prepared.effect.diff, + }; + } + + beginTransaction(): Transaction { + return new FileTransaction(this.#opts.stateDir); + } +} diff --git a/src/tools/sandbox.ts b/src/tools/sandbox.ts new file mode 100644 index 0000000..72a1b20 --- /dev/null +++ b/src/tools/sandbox.ts @@ -0,0 +1,169 @@ +import { ToolError, errorMessage } from '../core/errors.js'; +import type { BashContainment } from '../core/types.js'; +import { bootstrapEnv, spawnAndWait } from './bash.js'; + +/** + * OS containment for `bash` through `@anthropic-ai/sandbox-runtime` + * (bubblewrap on Linux, Seatbelt on macOS). The library keeps one global + * configuration and one network proxy per process, so this module owns it: + * it is initialized once, lazily, with no network allowed, and each command + * passes its own filesystem rules. + * + * Network: the library routes all traffic through its proxy and refuses an + * allow-everything domain list, so "network on" is implemented with the + * library's ask callback, which allows a host only while a network-enabled + * command holds the sandbox. Sandboxed commands are therefore serialized in + * this process, so a network-off command never runs while the gate is open. + * On Linux the command has no network namespace of its own either way: with + * network on, only clients that honor the proxy variables the library sets + * (curl, git, npm, ...) reach the network; raw sockets never do. + */ + +type SandboxModule = typeof import('@anthropic-ai/sandbox-runtime'); +type Manager = SandboxModule['SandboxManager']; + +let loading: Promise | undefined; +let networkOpen = false; +let tail: Promise = Promise.resolve(); +let probed = false; + +/** Why containment is unavailable on this machine, or null when it is available. */ +let availability: Promise | undefined; + +async function loadManager(): Promise { + const mod: SandboxModule = await import('@anthropic-ai/sandbox-runtime'); + return mod.SandboxManager; +} + +/** Checks and caches the platform and dependencies before a sandboxed commit can run. */ +export function containmentUnavailableReason(): Promise { + availability ??= (async () => { + if (process.platform !== 'linux' && process.platform !== 'darwin') { + return `bash containment is not supported on ${process.platform}`; + } + try { + const manager = await loadManager(); + if (!manager.isSupportedPlatform()) return 'the sandbox runtime does not support this platform'; + const check = manager.checkDependencies(); + if (check.errors.length > 0) return `sandbox dependencies missing: ${check.errors.join('; ')}`; + return null; + } catch (err) { + return `sandbox runtime failed to load: ${errorMessage(err)}`; + } + })(); + return availability; +} + +/** Most time the probe command may take. */ +const PROBE_TIMEOUT_MS = 15_000; + +/** + * Runs `true` in the sandbox once: present dependencies do not prove the + * sandbox can start here (user namespaces may be disabled), and a sandbox + * that cannot start would otherwise look like the command's own exit. + */ +async function probe(m: Manager, shell: string, signal: AbortSignal): Promise { + try { + const wrapped = await m.wrapWithSandboxArgv('true', shell, { filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } }); + const env = bootstrapEnv({ ...process.env, ...wrapped.env }); + const r = await spawnAndWait(wrapped.argv, env, process.cwd(), PROBE_TIMEOUT_MS, signal, 4096); + if (r.exitCode === 0) return; + const how = r.timedOut ? `no exit within ${PROBE_TIMEOUT_MS} ms` : `exit ${r.exitCode ?? r.signal}`; + const first = r.stderr.trim().split('\n')[0] ?? ''; + throw new Error(`the sandbox could not start a command (${how}${first ? `: ${first}` : ''})`); + } finally { + try { + m.cleanupAfterCommand(); + } catch { + // Cleanup is best effort. + } + } +} + +async function manager(): Promise { + loading ??= (async () => { + const m = await loadManager(); + await m.initialize( + { network: { allowedDomains: [], deniedDomains: [] }, filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } }, + async () => networkOpen, + ); + return m; + })(); + try { + return await loading; + } catch (err) { + loading = undefined; + throw err; + } +} + +/** A command wrapped for the sandbox. */ +export interface WrappedCommand { + readonly argv: readonly string[]; + readonly env: NodeJS.ProcessEnv; +} + +/** + * Runs `fn` with `command` wrapped for `containment`. Sandboxed commands are + * serialized in this process (see the module comment). `denyWrite` adds + * paths the command may never write even inside a writable root. + */ +export function withSandbox( + command: string, + shell: string, + cwd: string, + containment: Extract, + denyWrite: readonly string[], + signal: AbortSignal, + fn: (wrapped: WrappedCommand) => Promise, +): Promise { + const run = async (): Promise => { + const reason = await containmentUnavailableReason(); + if (reason !== null) throw new ToolError('containment-unavailable', reason); + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + let m: Manager; + try { + m = await manager(); + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + if (!probed) { + await probe(m, shell, signal); + probed = true; + } + } catch (err) { + if (err instanceof ToolError && err.code === 'cancelled') throw err; + throw new ToolError('containment-unavailable', `sandbox runtime failed to start: ${errorMessage(err)}`); + } + let wrapped: WrappedCommand; + try { + wrapped = await m.wrapWithSandboxArgv( + command, + shell, + { + filesystem: { + denyRead: [], + allowWrite: containment.readOnly ? [] : [...containment.writableRoots], + denyWrite: [...denyWrite], + }, + }, + undefined, + cwd, + ); + } catch (err) { + throw new ToolError('containment-unavailable', `sandbox runtime could not wrap the command: ${errorMessage(err)}`); + } + networkOpen = containment.network; + try { + return await fn(wrapped); + } finally { + networkOpen = false; + try { + m.cleanupAfterCommand(); + } catch { + // Cleanup is best effort. + } + } + }; + const next = tail.then(run, run); + tail = next.catch(() => undefined); + return next; +} diff --git a/src/tools/search.ts b/src/tools/search.ts new file mode 100644 index 0000000..1aecee5 --- /dev/null +++ b/src/tools/search.ts @@ -0,0 +1,438 @@ +import { constants as FS } from 'node:fs'; +import { Worker } from 'node:worker_threads'; +import { z } from 'zod'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, matchesPathPattern } from '../core/paths.js'; +import { isBinary, readFileInside } from './fs-ops.js'; +import type { GlobEffect, GlobResult, GrepEffect, GrepMatch, GrepResult } from '../core/types.js'; + +/** Default `grep` result count. */ +export const DEFAULT_GREP_MAX_RESULTS = 500; +/** Default `glob` result count. */ +export const DEFAULT_GLOB_MAX_RESULTS = 1000; +/** Longest matching line returned by `grep`. */ +const MAX_LINE_CHARS = 2000; +/** Files larger than this are not searched by `grep`. */ +const MAX_GREP_FILE_BYTES = 16 * 1024 * 1024; +/** Upper bound of directory entries visited by one call. */ +const MAX_VISITED = 500_000; + +const ALWAYS_IGNORED = new Set(['.git', 'node_modules']); + +// --------------------------------------------------------------------------- +// gitignore +// --------------------------------------------------------------------------- + +interface IgnoreRule { + readonly re: RegExp; + readonly negate: boolean; + readonly dirOnly: boolean; +} + +function globToRegExpSource(glob: string): string { + let src = ''; + for (let i = 0; i < glob.length; i++) { + const ch = glob[i] ?? ''; + if (ch === '\\' && i + 1 < glob.length) { + src += (glob[++i] ?? '').replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } else if (ch === '*') { + if (glob[i + 1] === '*') { + const prevSlash = i === 0 || glob[i - 1] === '/'; + const nextSlash = glob[i + 2] === '/' || i + 2 === glob.length; + if (prevSlash && nextSlash) { + if (i + 2 === glob.length) src += '.*'; + else { + src += '(?:.*/)?'; + i++; + } + i++; + continue; + } + i++; + } + src += '[^/]*'; + } else if (ch === '?') { + src += '[^/]'; + } else if (ch === '[') { + const close = glob.indexOf(']', i + 1); + if (close === -1) src += '\\['; + else { + let body = glob.slice(i + 1, close); + if (body.startsWith('!')) body = `^${body.slice(1)}`; + src += `[${body.replace(/\\/g, '\\\\')}]`; + i = close; + } + } else { + src += ch.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } + } + return src; +} + +/** Parses a `.gitignore` file. Patterns are relative to the directory holding it. */ +export function parseGitignore(text: string): IgnoreRule[] { + const rules: IgnoreRule[] = []; + for (const rawLine of text.split(/\r?\n/)) { + let line = rawLine.replace(/(? 0 && !matchedParent; i--) { + if (rule.re.test(parts.slice(0, i).join('/'))) matchedParent = true; + } + if (matchedParent) parentIgnored = !rule.negate; + continue; + } + if (rule.re.test(rel)) ignored = !rule.negate; + } + } + return ignored || parentIgnored; +} + +async function loadIgnore(dir: string): Promise { + try { + // Non-blocking, so a FIFO named .gitignore cannot stall the open before the type check. + const handle = await fs.open(path.join(dir, '.gitignore'), FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0) | (FS.O_NONBLOCK ?? 0)); + try { + const st = await handle.stat(); + if (!st.isFile() || st.size > 1024 * 1024) return null; + return { base: dir, rules: parseGitignore(await handle.readFile('utf8')) }; + } finally { + await handle.close(); + } + } catch { + return null; + } +} + +/** `.gitignore` layers of the directories from `top` down to `dir` (inclusive). */ +async function ancestorLayers(top: string, dir: string): Promise { + const chain: string[] = []; + let cursor = dir; + for (;;) { + chain.push(cursor); + if (cursor === top) break; + const parent = path.dirname(cursor); + if (parent === cursor || path.relative(top, parent).startsWith('..')) break; + cursor = parent; + } + const layers: IgnoreLayer[] = []; + for (const d of chain.reverse()) { + const layer = await loadIgnore(d); + if (layer) layers.push(layer); + } + return layers; +} + +// --------------------------------------------------------------------------- +// Walking +// --------------------------------------------------------------------------- + +async function isRealDir(dir: string): Promise { + const st = await fs.lstat(dir).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return false; + const real = await fs.realpath(dir).catch(() => null); + return real !== null && (process.platform === 'win32' ? real.toLowerCase() === dir.toLowerCase() : real === dir); +} + +/** + * Lists regular files below `absRoot` (real path, inside the jail), sorted, + * skipping `.git`, `node_modules` and gitignored entries. Symbolic links are + * never followed, whether they point inside or outside the workspace. + * `jailRoot` is the workspace root above it whose `.gitignore` files apply. + */ +async function* walkFiles(absRoot: string, jailRoot: string, signal: AbortSignal): AsyncGenerator { + const rootStat = await fs.lstat(absRoot); + if (rootStat.isFile()) { + yield absRoot; + return; + } + if (!rootStat.isDirectory()) return; + const startLayers = await ancestorLayers(jailRoot, absRoot); + let visited = 0; + const stack: { dir: string; layers: IgnoreLayer[] }[] = [{ dir: absRoot, layers: startLayers }]; + while (stack.length > 0) { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped'); + const { dir, layers } = stack.pop() as { dir: string; layers: IgnoreLayer[] }; + let entries: import('node:fs').Dirent[]; + try { + entries = await fs.readdir(dir, { withFileTypes: true }); + } catch { + continue; + } + // A directory swapped for a link while it was listed is skipped whole: + // its names may come from outside the workspace. + if (!(await isRealDir(dir))) continue; + const own = dir === absRoot ? null : await loadIgnore(dir); + const here = own ? [...layers, own] : layers; + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const subdirs: string[] = []; + for (const entry of entries) { + if (++visited > MAX_VISITED) throw new ToolError('tool-error', `too many files under ${absRoot} (more than ${MAX_VISITED}); narrow the path`); + const abs = path.join(dir, entry.name); + if (entry.isSymbolicLink()) continue; + // `.git` is also a file, in worktrees and submodules. + if (ALWAYS_IGNORED.has(entry.name)) continue; + if (entry.isDirectory()) { + if (isIgnored(here, abs, true)) continue; + subdirs.push(abs); + } else if (entry.isFile()) { + if (isIgnored(here, abs, false)) continue; + yield abs; + } + } + // Depth first, in name order: push in reverse so the first name pops first. + // Files of a directory come before its subdirectories' files. + for (const sub of subdirs.reverse()) stack.push({ dir: sub, layers: here }); + } +} + +// --------------------------------------------------------------------------- +// Patterns +// --------------------------------------------------------------------------- + +/** Expands `{a,b}` alternations (nested allowed, at most 256 results). */ +export function expandBraces(pattern: string): string[] { + const open = pattern.indexOf('{'); + if (open === -1) return [pattern]; + let depth = 0; + let close = -1; + const commas: number[] = []; + for (let i = open; i < pattern.length; i++) { + const ch = pattern[i]; + if (ch === '{') depth++; + else if (ch === '}') { + depth--; + if (depth === 0) { + close = i; + break; + } + } else if (ch === ',' && depth === 1) commas.push(i); + } + if (close === -1 || commas.length === 0) return [pattern]; + const head = pattern.slice(0, open); + const tail = pattern.slice(close + 1); + const cuts = [open, ...commas, close]; + const out: string[] = []; + for (let i = 0; i + 1 < cuts.length; i++) { + const alt = pattern.slice((cuts[i] ?? 0) + 1, cuts[i + 1]); + for (const expanded of expandBraces(head + alt + tail)) { + out.push(expanded); + if (out.length >= 256) return out; + } + } + return out; +} + +/** Normalizes a glob pattern given relative to `absRoot`; refuses patterns that leave it. */ +export function normalizeGlob(pattern: string, absRoot: string): string { + let p = pattern.replace(/\\/g, '/'); + const rootFwd = absRoot.replace(/\\/g, '/'); + if (p.startsWith(`${rootFwd}/`)) p = p.slice(rootFwd.length + 1); + else if (p.startsWith('/') || /^[A-Za-z]:\//.test(p)) { + throw new ToolError('invalid-args', `glob pattern ${pattern} is absolute and not under ${absRoot}; pass the directory as path and a relative pattern`); + } + if (p.startsWith('./')) p = p.slice(2); + if (p.split('/').includes('..')) throw new ToolError('invalid-args', `glob pattern ${pattern} must not contain ..`); + return p; +} + +function toRel(absRoot: string, abs: string): string { + return path.relative(absRoot, abs).split(path.sep).join('/'); +} + +// --------------------------------------------------------------------------- +// grep and glob +// --------------------------------------------------------------------------- + +/** Compiles a grep pattern (JavaScript RegExp syntax). */ +export function compileGrep(pattern: string, ignoreCase: boolean): RegExp { + try { + return new RegExp(pattern, ignoreCase ? 'i' : ''); + } catch (err) { + throw new ToolError('invalid-args', `invalid regular expression ${JSON.stringify(pattern)}: ${err instanceof Error ? err.message : String(err)}`); + } +} + +function matchesFileGlob(rel: string, globs: readonly string[]): boolean { + const base = rel.slice(rel.lastIndexOf('/') + 1); + return globs.some((g) => (g.includes('/') ? matchesPathPattern(rel, g) : matchesPathPattern(base, g))); +} + +/** + * Matches lines in a worker thread, so a pathological pattern (catastrophic + * backtracking) can be stopped: each file gets a time budget, and an abort + * terminates the worker at once. + */ +const MATCH_WORKER_SOURCE = ` +const { parentPort, workerData } = require('node:worker_threads'); +const re = new RegExp(workerData.pattern, workerData.flags); +parentPort.on('message', (m) => { + const lines = m.text.split('\\n'); + const hits = []; + let more = false; + for (let i = 0; i < lines.length; i++) { + let t = lines[i]; + if (t.endsWith('\\r')) t = t.slice(0, -1); + if (i === lines.length - 1 && t === '') break; + if (!re.test(t)) continue; + if (hits.length >= m.room) { more = true; break; } + hits.push([i + 1, t.length > m.lineMax ? t.slice(0, m.lineMax) + '\\u2026' : t]); + } + parentPort.postMessage({ hits, more }); +}); +`; + +const HitsSchema = z.object({ hits: z.array(z.tuple([z.number().int(), z.string()])), more: z.boolean() }); +type Hits = z.infer; + +class MatchWorker { + readonly #worker: Worker; + #dead = false; + + constructor(pattern: string, flags: string) { + this.#worker = new Worker(MATCH_WORKER_SOURCE, { + eval: true, + workerData: { pattern, flags }, + resourceLimits: { maxOldGenerationSizeMb: 256 }, + }); + this.#worker.once('exit', () => (this.#dead = true)); + } + + match(file: string, text: string, room: number, budgetMs: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (this.#dead) return reject(new ToolError('tool-error', 'grep worker stopped')); + const done = (): void => { + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + this.#worker.off('message', onMessage); + this.#worker.off('error', onError); + }; + const onMessage = (msg: unknown): void => { + done(); + const parsed = HitsSchema.safeParse(msg); + if (parsed.success) resolve(parsed.data); + else reject(new ToolError('tool-error', 'grep worker returned an invalid reply')); + }; + const onError = (err: Error): void => { + done(); + reject(new ToolError('tool-error', `grep failed on ${file}: ${err.message}`)); + }; + const onAbort = (): void => { + done(); + this.close(); + reject(new ToolError('cancelled', 'grep was stopped because the run stopped')); + }; + const timer = setTimeout(() => { + done(); + this.close(); + reject( + new ToolError( + 'tool-error', + `grep pattern ran for more than ${budgetMs} ms on ${file} and was stopped; the regular expression is too expensive (catastrophic backtracking?)`, + ), + ); + }, budgetMs); + if (signal.aborted) return onAbort(); + signal.addEventListener('abort', onAbort, { once: true }); + this.#worker.on('message', onMessage); + this.#worker.once('error', onError); + this.#worker.postMessage({ text, room, lineMax: MAX_LINE_CHARS }); + }); + } + + close(): void { + this.#dead = true; + void this.#worker.terminate(); + } +} + +/** Default time budget of the regex on one file. */ +export const DEFAULT_GREP_FILE_BUDGET_MS = 10_000; + +export async function runGrep( + effect: GrepEffect, + jailRoot: string, + signal: AbortSignal, + fileBudgetMs: number = DEFAULT_GREP_FILE_BUDGET_MS, +): Promise { + compileGrep(effect.pattern, effect.ignoreCase); + const globs = effect.glob === null ? null : expandBraces(effect.glob.replace(/\\/g, '/')); + const matches: GrepMatch[] = []; + const worker = new MatchWorker(effect.pattern, effect.ignoreCase ? 'i' : ''); + try { + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + const rel = file === effect.absRoot ? path.basename(file) : toRel(effect.absRoot, file); + if (globs && !matchesFileGlob(rel, globs)) continue; + // Opened without following links and checked to be the file at this path, + // so a directory swapped for a link mid-walk cannot lead outside. + const bytes = await readFileInside(file, MAX_GREP_FILE_BYTES); + if (bytes === null || isBinary(bytes)) continue; + const room = effect.maxResults - matches.length; + const found = await worker.match(file, bytes.toString('utf8'), room, fileBudgetMs, signal); + for (const [line, text] of found.hits) matches.push({ file, line, text }); + if (found.more) return { matches, truncated: true }; + } + } finally { + worker.close(); + } + return { matches, truncated: false }; +} + +export async function runGlob(effect: GlobEffect, jailRoot: string, signal: AbortSignal): Promise { + const patterns = expandBraces(normalizeGlob(effect.pattern, effect.absRoot)); + const all: string[] = []; + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (file === effect.absRoot) continue; + const rel = toRel(effect.absRoot, file); + if (patterns.some((p) => matchesPathPattern(rel, p))) all.push(file); + } + all.sort(); + return { files: all.slice(0, effect.maxResults), truncated: all.length > effect.maxResults }; +}