diff --git a/apps/docs/src/content/guide/terminal.mdx b/apps/docs/src/content/guide/terminal.mdx index 0fb3cd01..78b0293c 100644 --- a/apps/docs/src/content/guide/terminal.mdx +++ b/apps/docs/src/content/guide/terminal.mdx @@ -421,7 +421,47 @@ commands for builds, tests and Git. Each command shows its full text and absolut directory for confirmation, including when `--yes` skips file-write prompts. Without `--shell`, only the existing emulated file commands are available. +The coding agent calls `local_info` to check which client and workspace it is using. +The terminal reports whether native shell execution is enabled; the browser reports +emulated commands and whether files live in a mounted directory or its virtual workspace. +This check reads no project files and runs no command. Older clients can continue using +the file tools, but do not support this capability check. + +Before editing a target file, `code` can use `local_instructions` to read the `AGENTS.md` +and `CLAUDE.md` files in its parent directories, starting at the workspace root. This +also works for new files. Results include truncation offsets when instructions exceed +the response budget; the agent must finish those reads before editing. Both tools +are available in plan mode. + +`local_edit` rechecks the original contents after terminal confirmation and before +committing a browser write. If the file changed, it reports a conflict and preserves +the newer work so the agent can reread and reconcile it. This does not lock the file +against other programs. + +Delete and rename also recheck the source after terminal confirmation. Terminal +rename creates the destination exclusively before removing the source, so it cannot +replace a file created during approval. It requires a filesystem that supports hard +links and refuses moves across filesystems. If a move fails after creating the +destination, inspect both paths: the source is retained when its removal is uncertain. +Browser rename copies before deleting and retains a source changed during that copy. + Commands start inside the project, but **are not sandboxed**: an approved command has your account's filesystem and network access. stdin is closed; interactive programs are unsupported. Output is capped at 200 kB and commands time out after four minutes. Stop cancels the process group. `local_open` displays text files through `$PAGER`; web URLs appear as links to open manually. + + +After a `code` turn finishes, **Workspace results** summarizes observed file operations, +completed commands, issues, unconfirmed operations, and unfinished plan steps. It uses +recorded tool results, not the agent's prose. A completed command is not a claim that tests +passed. Failed attempts remain visible even after a successful retry; partial or missing +results are marked unconfirmed. Each group shows up to six entries, with the rest available +in the tool results above. + +Use `/work` to open a coding report for the loaded thread history in `$PAGER`. It +combines operations and command attempts across turns and uses the latest recorded +state of each plan. Failed attempts remain visible after successful retries; only the +latest unfinished plan steps are listed. The report makes no model call, runs no +command against the project, and changes no project file. The pager uses a private +temporary report file. It reports loaded history rather +than fetching a fresh Git diff or checking the current workspace. diff --git a/apps/tui/src/app.tsx b/apps/tui/src/app.tsx index 47e82a11..e4ebb6a9 100644 --- a/apps/tui/src/app.tsx +++ b/apps/tui/src/app.tsx @@ -899,6 +899,7 @@ export function App({ = [ ['agent', '/manifest [name] /start '], ['history', '/rewind [n] /version /search /open '], ['$PAGER', '/artifact [file] · /skills /skill (read-only)'], + ['coding', '/work · recorded operations and latest plan (read-only)'], ['client', '/refresh the thread list · /quit'], ]; @@ -163,6 +165,13 @@ export function runCommand(ctx: CommandContext, line: string): void { const [name, ...rest] = line.slice(1).split(/\s+/); const arg = rest.join(' ').trim(); switch (name) { + case 'work': + if (arg) { + setNotice('usage: /work'); + return; + } + ctx.show(workReport(engine.state.turns, threadIdRef.current), 'Coding work'); + return; case 'new': newThread(); return; diff --git a/apps/tui/src/ui/transcript.tsx b/apps/tui/src/ui/transcript.tsx index 628a0e15..fff1bc86 100644 --- a/apps/tui/src/ui/transcript.tsx +++ b/apps/tui/src/ui/transcript.tsx @@ -52,6 +52,7 @@ import { handlesByTool, type Spill, sizeLabel } from '../artifacts.js'; import { syntaxStyle } from '../syntax.js'; import { oneLine } from '../text.js'; import { DIM, DIM_ITALIC, type Theme } from '../theme.js'; +import { WorkspaceResults } from './workspace-summary.js'; /** * Fenced code, in a frame with its language on it. @@ -529,12 +530,14 @@ function AssistantTurn({ live, theme, handles, + workspaceResults, }: { turn: Turn; live: boolean; theme: Theme; /** Handle numbers are assigned across the whole transcript, not per turn. */ handles: Map; + workspaceResults: boolean; }) { const segments = interleaveTurn(turn.content, turn.tools, turn.reasoning as ReasoningBlock[]); // Only the tail of a live turn is still being written. An earlier segment was @@ -589,6 +592,9 @@ function AssistantTurn({ pending ) : null} + {workspaceResults && !live && !turn.runStatus ? ( + + ) : null} {turn.usage ? ( {' '} @@ -649,6 +655,7 @@ function UserTurn({ turn, theme, branch }: { turn: Turn; theme: Theme; branch?: export function Transcript({ turns, streaming = false, + showWorkspaceResults = false, scrollRef, theme, greeting, @@ -656,6 +663,7 @@ export function Transcript({ }: { turns: Turn[]; streaming?: boolean; + showWorkspaceResults?: boolean; /** * Handed to `App` so the page keys can drive the box without taking focus * from the composer. The alternative — focusing the scrollbox so its own @@ -722,6 +730,7 @@ export function Transcript({ live={streaming && turn.id === turns[turns.length - 1]?.id} theme={theme} handles={handles} + workspaceResults={showWorkspaceResults} /> ), )} diff --git a/apps/tui/src/ui/workspace-summary.tsx b/apps/tui/src/ui/workspace-summary.tsx new file mode 100644 index 00000000..dc57950d --- /dev/null +++ b/apps/tui/src/ui/workspace-summary.tsx @@ -0,0 +1,53 @@ +import type { Turn } from '@felix/client'; +import { useMemo } from 'react'; +import { oneLine } from '../text.js'; +import { BOLD, DIM, type Theme } from '../theme.js'; +import { summarizeWorkspace } from '../workspace-summary.js'; + +export function WorkspaceResults({ turn, theme }: { turn: Turn; theme: Theme }) { + const summary = useMemo(() => summarizeWorkspace(turn), [turn]); + if (!summary) return null; + const groups = [ + ['File operations', summary.files, theme.ready], + ['Commands completed', summary.commands, theme.ready], + ['Issues', summary.issues, theme.failed], + ['Unconfirmed operations', summary.unconfirmed, theme.blocked], + ['Plan steps remaining', summary.remaining, theme.blocked], + ] as const; + const outcome = summary.issues.length + ? theme.failed + : summary.unconfirmed.length || summary.remaining.length + ? theme.blocked + : theme.ready; + return ( + + + Workspace results + + {groups.map(([label, entries, color]) => + entries.length ? ( + + {`${label}: ${entries.length}`} + + {entries + .slice(0, 6) + .map((entry) => ` ${oneLine(entry, 160)}`) + .join('\n')} + + {entries.length > 6 ? ( + {` … ${entries.length - 6} more; see tool results above`} + ) : null} + + ) : null, + )} + + ); +} diff --git a/apps/tui/src/work-report.ts b/apps/tui/src/work-report.ts new file mode 100644 index 00000000..2a43d1e3 --- /dev/null +++ b/apps/tui/src/work-report.ts @@ -0,0 +1,58 @@ +import { type PlanState, plansInTurn, type Turn } from '@felix/client'; +import { oneLine } from './text.js'; +import { summarizeWorkspace } from './workspace-summary.js'; + +const MAX_ROWS = 200; + +/** A local report from loaded history; no model, repository command, or file write. */ +export function workReport(turns: readonly Turn[], threadId: string): string { + const files: string[] = []; + const commands: string[] = []; + const issues: string[] = []; + const unconfirmed: string[] = []; + const plans = new Map(); + for (const turn of turns) { + if (turn.role !== 'assistant') continue; + const summary = summarizeWorkspace(turn); + if (summary) { + files.push(...summary.files); + commands.push(...summary.commands); + issues.push(...summary.issues); + unconfirmed.push(...summary.unconfirmed); + } + for (const [id, plan] of plansInTurn(turn.tools).latest) plans.set(id, plan); + } + // Tool arguments and instruction-derived titles are data, including control bytes. + // biome-ignore lint/suspicious/noControlCharactersInRegex: Strip terminal control bytes from tool-derived labels. + const line = (text: string) => oneLine(text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' '), 400); + const lines = [ + 'Coding work · loaded thread history', + `Thread: ${line(threadId)}`, + '', + 'Recorded operations, not a live Git diff. Completed commands do not establish that tests passed.', + 'Failed or refused attempts remain in history even when a later retry succeeds.', + ]; + const section = (title: string, entries: string[]) => { + lines.push('', `${title} (${entries.length})`); + lines.push(...entries.slice(0, MAX_ROWS).map((entry) => ` ${line(entry)}`)); + if (!entries.length) lines.push(' None recorded.'); + if (entries.length > MAX_ROWS) + lines.push(` … ${entries.length - MAX_ROWS} more; see the transcript.`); + }; + section('File operations', files); + section('Commands completed', commands); + section('Failed or refused attempts', issues); + section('Unconfirmed operations', unconfirmed); + const remaining: string[] = []; + for (const plan of plans.values()) { + for (const step of plan.steps) { + if (step.state !== 'done') + remaining.push( + `${plan.title}: ${step.title} [${step.status}]${step.note ? ` · ${step.note}` : ''}`, + ); + } + } + section('Unfinished steps in latest recorded plans', remaining); + if (!plans.size) lines.push(' No saved plan was observed in loaded history.'); + return lines.join('\n'); +} diff --git a/apps/tui/src/workspace-summary.ts b/apps/tui/src/workspace-summary.ts new file mode 100644 index 00000000..d5db1e07 --- /dev/null +++ b/apps/tui/src/workspace-summary.ts @@ -0,0 +1,59 @@ +import { classifyToolResult, fileToolOp, plansInTurn, type Turn } from '@felix/client'; + +export interface WorkspaceSummary { + files: string[]; + commands: string[]; + issues: string[]; + unconfirmed: string[]; + remaining: string[]; +} + +/** Observed tool outcomes only: prose is never evidence that a check passed. */ +export function summarizeWorkspace(turn: Turn): WorkspaceSummary | null { + const summary: WorkspaceSummary = { + files: [], + commands: [], + issues: [], + unconfirmed: [], + remaining: [], + }; + let relevant = false; + for (const tool of turn.tools ?? []) { + const name = tool.name.replace(/^client · /, ''); + const op = fileToolOp(name); + const mutation = op === 'write' || op === 'edit' || op === 'delete' || op === 'rename'; + if (!mutation && name !== 'local_shell') continue; + relevant = true; + const args = + tool.input && typeof tool.input === 'object' ? (tool.input as Record) : {}; + const path = typeof args.path === 'string' ? args.path : '(path unavailable)'; + const command = typeof args.command === 'string' ? args.command : '(command unavailable)'; + const label = mutation + ? `${op} ${path}${op === 'rename' ? ` → ${typeof args.to_path === 'string' ? args.to_path : '(destination unavailable)'}` : ''}` + : command; + if ( + !tool.done || + typeof tool.output !== 'string' || + !tool.output.trim() || + tool.output.startsWith('[approval required]') + ) { + summary.unconfirmed.push(label); + continue; + } + // Local tools historically returned plain error text. Treat it conservatively + // even for shell calls; current clients additionally emit typed error markers. + const issue = + classifyToolResult(name, tool.output) ?? classifyToolResult('local_read', tool.output); + if (issue) summary.issues.push(`${label}: ${issue.label}`); + else if (mutation) summary.files.push(label); + else summary.commands.push(label); + } + if (!relevant) return null; + for (const plan of plansInTurn(turn.tools).latest.values()) { + for (const step of plan.steps) { + if (step.state !== 'done') + summary.remaining.push(`${step.title}${step.note ? ` · ${step.note}` : ''}`); + } + } + return summary; +} diff --git a/apps/tui/src/workspace.ts b/apps/tui/src/workspace.ts index 452bf7ca..f8b5f794 100644 --- a/apps/tui/src/workspace.ts +++ b/apps/tui/src/workspace.ts @@ -29,16 +29,16 @@ * confirmed real command. Only its initial cwd is contained; this is not an OS sandbox. */ -import { constants } from 'node:fs'; +import { constants, type Stats } from 'node:fs'; import { access, appendFile, + link, lstat, mkdir, readdir, readFile, realpath, - rename, stat, unlink, writeFile, @@ -310,6 +310,27 @@ async function refuseLink(realRoot: string, path: string): Promise { throw new Error(`${path} is a symbolic link; links are not followed here`); } +async function assertUnchanged( + root: string, + path: string, + target: string, + before: Stats, +): Promise { + await refuseLink(root, path); + if ((await resolveWithin(root, path)) !== target) + throw new Error(`${path} changed location while awaiting approval; inspect it again`); + const now = await lstat(target); + if ( + !now.isFile() || + now.dev !== before.dev || + now.ino !== before.ino || + now.size !== before.size || + now.mtimeMs !== before.mtimeMs + ) + throw new Error(`${path} changed while awaiting approval; inspect it again`); + await assertWritable(root, target); +} + /** * The working directory as the `local_*` file tools see it, under the same three rules as the * shell verbs above: every path through `resolveWithin`, every write through `assertWritable` @@ -338,11 +359,18 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { } return await readFile(target, 'utf8'); }, - write: async (path, content, { append, summary }) => { + write: async (path, content, { append, summary, expected }) => { const root = await realRoot(); const target = await resolveWithin(root, path); await assertWritable(root, target); if (!(await opts.confirm(`${summary} ${target}`))) throw new Error('refused by the user'); + // Approval may take minutes. Revalidate both the destination and the + // content used to construct an edit before replacing the file. + if ((await resolveWithin(root, path)) !== target) + throw new Error(`${path} changed location; read it again before editing`); + await assertWritable(root, target); + if (expected !== undefined && (await readFile(target, 'utf8')) !== expected) + throw new Error(`${path} changed since it was read; read it again before editing`); await mkdir(dirname(target), { recursive: true }); opts.signal?.throwIfAborted(); if (append) await appendFile(target, content, 'utf8'); @@ -358,6 +386,7 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { if (!info.isFile()) throw new Error(`${path} is not a file; only files are deleted`); await assertWritable(root, target); if (!(await opts.confirm(`${summary} ${target}`))) throw new Error('refused by the user'); + await assertUnchanged(root, path, target, info); opts.signal?.throwIfAborted(); await unlink(target); }, @@ -381,15 +410,45 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { } if (!(await opts.confirm(`${summary} ${from} → ${to}`))) throw new Error('refused by the user'); + await assertUnchanged(root, path, from, info); + await refuseLink(root, toPath); + if ((await resolveWithin(root, toPath)) !== to) + throw new Error(`${toPath} changed location while awaiting approval; inspect it again`); + await assertWritable(root, to); await mkdir(dirname(to), { recursive: true }); opts.signal?.throwIfAborted(); - await rename(from, to); + // link is exclusive: a destination created after the checks is never + // replaced. Unlink only after the new name exists and source is rechecked. + // Cross-filesystem links fail safely, leaving the source in place. + await link(from, to); + try { + await assertUnchanged(root, path, from, info); + opts.signal?.throwIfAborted(); + await unlink(from); + } catch (error) { + // Do not remove either name during uncertain concurrent changes. + throw new Error(`rename created ${toPath} but kept ${path}: ${String(error)}`); + } }, }; } async function run(req: ClientToolRequest, opts: WorkspaceOptions): Promise { try { + if (req.name === 'local_info') { + return { + content: JSON.stringify({ + client: 'terminal', + workspace: { kind: 'directory', root: await realpath(opts.root) }, + shell: { + mode: opts.shell ? 'native' : 'emulated', + ...(opts.shell + ? { interpreter: '/bin/sh', confirmation: 'always', sandboxed: false } + : { commands: ['pwd', 'ls', 'cat', 'echo', 'mkdir', 'touch', 'tree', 'help'] }), + }, + }), + }; + } if (isLocalFileTool(req.name)) return await runLocalFileTool(req, workingDirFs(opts)); if (req.name === 'local_shell') { const command = typeof req.args.command === 'string' ? req.args.command : ''; diff --git a/apps/tui/tests/skill-commands.test.ts b/apps/tui/tests/skill-commands.test.ts index cef35511..d3bd7a64 100644 --- a/apps/tui/tests/skill-commands.test.ts +++ b/apps/tui/tests/skill-commands.test.ts @@ -85,6 +85,26 @@ function context(client: Partial, spills: Spill[] = []) { const settle = () => new Promise((r) => setTimeout(r, 0)); +describe('/work', () => { + it('opens a local report without contacting the harness or writing a project file', () => { + const { ctx, shown, written } = context({}); + Object.assign(ctx.engine, { state: { turns: [] } }); + runCommand(ctx, '/work'); + expect(shown).toHaveLength(1); + expect(shown[0]?.name).toBe('Coding work'); + expect(shown[0]?.body).toContain('Thread: t1'); + expect(written.size).toBe(0); + }); + + it('rejects arguments instead of treating them as an export path', () => { + const { ctx, shown, notices, written } = context({}); + runCommand(ctx, '/work output.txt'); + expect(notices).toContain('usage: /work'); + expect(shown).toEqual([]); + expect(written.size).toBe(0); + }); +}); + describe('/skills', () => { it('pages the review queue and the skills in use', async () => { const t = context({ diff --git a/apps/tui/tests/transcript.test.ts b/apps/tui/tests/transcript.test.ts index 6901dcca..3d0e1845 100644 --- a/apps/tui/tests/transcript.test.ts +++ b/apps/tui/tests/transcript.test.ts @@ -3,6 +3,7 @@ import type { Turn } from '@felix/client'; import { createTextAttributes, type ScrollBoxRenderable } from '@opentui/core'; import { createElement } from 'react'; import { spinnerTicking, Transcript } from '../src/ui/transcript'; +import { WorkspaceResults } from '../src/ui/workspace-summary'; import { hasAttribute, lines, mount, shows, styleOf, testTheme } from './render'; /** @@ -33,6 +34,78 @@ const user = (content: string): Turn => ({ content, }); +describe('workspace result summary', () => { + it('integrates the summary for a completed coding turn', async () => { + const turn: Turn = { + id: 'work', + role: 'assistant', + content: '', + tools: [{ name: 'local_edit', input: { path: 'a.ts' }, output: 'edited', done: true }], + }; + const ui = await mount( + createElement(Transcript, { turns: [turn], showWorkspaceResults: true, theme: testTheme }), + { width: 60, height: 16 }, + ); + try { + expect(shows(ui.frame(), 'Workspace results')).toBe(true); + } finally { + ui.stop(); + } + }); + + it('shows observed operations and failures in a narrow terminal', async () => { + const turn: Turn = { + id: 'work', + role: 'assistant', + content: '', + tools: [ + { name: 'local_edit', input: { path: 'src/api.ts' }, output: 'edited', done: true }, + { + name: 'local_shell', + input: { command: 'npm test' }, + output: '[tool error/provider_error] exit 1', + done: true, + }, + ], + }; + const ui = await mount(createElement(WorkspaceResults, { turn, theme: testTheme }), { + width: 38, + height: 14, + }); + try { + expect(shows(ui.frame(), 'Workspace results')).toBe(true); + expect(shows(ui.frame(), 'File operations: 1')).toBe(true); + expect(shows(ui.frame(), 'Issues: 1')).toBe(true); + expect(ui.frame()).not.toContain('Commands completed'); + } finally { + ui.stop(); + } + }); + + it('waits until streaming finishes before displaying a summary', async () => { + const turn: Turn = { + id: 'work', + role: 'assistant', + content: '', + tools: [{ name: 'local_edit', input: { path: 'a.ts' }, output: 'edited', done: true }], + }; + const ui = await mount( + createElement(Transcript, { + turns: [turn], + streaming: true, + showWorkspaceResults: true, + theme: testTheme, + }), + { width: 60, height: 12 }, + ); + try { + expect(ui.frame()).not.toContain('Workspace results'); + } finally { + ui.stop(); + } + }); +}); + describe('the greeting', () => { const greeting = createElement('text', null, 'GREETING MARKER'); diff --git a/apps/tui/tests/work-report.test.ts b/apps/tui/tests/work-report.test.ts new file mode 100644 index 00000000..1320e84c --- /dev/null +++ b/apps/tui/tests/work-report.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'bun:test'; +import type { ToolCall, Turn } from '@felix/client'; +import { workReport } from '../src/work-report'; + +const turn = (...tools: ToolCall[]): Turn => ({ + id: crypto.randomUUID(), + role: 'assistant', + content: 'Tests passed!', + tools, +}); +const tool = (name: string, output: unknown, input: unknown = {}): ToolCall => ({ + name, + output, + input, + done: true, +}); +const plan = (status: string) => + tool( + 'plan_get', + JSON.stringify({ + id: 'build', + plan: { + title: 'Ship fix', + steps: [ + { id: '1', title: 'Implement', status }, + { id: '2', title: 'Verify', status: 'blocked', note: 'missing dependency' }, + ], + }, + }), + ); + +describe('work report', () => { + it('combines tool history and the latest plan across continuation turns', () => { + const report = workReport( + [ + turn(plan('pending'), tool('local_edit', 'edited', { path: 'src/a.ts' })), + turn(tool('local_shell', '[tool error/provider_error] exit 1', { command: 'npm test' })), + turn(plan('done'), tool('local_shell', 'passed', { command: 'npm test' })), + ], + 'coding-thread', + ); + expect(report).toContain('File operations (1)'); + expect(report).toContain('Commands completed (1)'); + expect(report).toContain('Failed or refused attempts (1)'); + expect(report).toContain('Unfinished steps in latest recorded plans (1)'); + expect(report).toContain('Ship fix: Verify [blocked] · missing dependency'); + expect(report).not.toContain('Ship fix: Implement'); + }); + + it('does not infer checks from prose, user content or absent results', () => { + const report = workReport( + [ + { id: 'u', role: 'user', content: 'run tests' }, + turn(), + turn(tool('local_shell', undefined, { command: 'npm test' })), + ], + 't', + ); + expect(report).toContain('Commands completed (0)'); + expect(report).toContain('Unconfirmed operations (1)'); + expect(report).toContain('No saved plan was observed'); + }); + + it('bounds large histories and neutralizes terminal control characters', () => { + const tools = Array.from({ length: 205 }, (_, i) => + tool('local_write', 'wrote', { path: `file-${i}.ts` }), + ); + const report = workReport([turn(...tools)], 't\u001b[31m'); + expect(report).toContain('File operations (205)'); + expect(report).toContain('5 more; see the transcript'); + expect(report).not.toContain('\u001b'); + expect(report).not.toContain('file-204.ts'); + }); +}); diff --git a/apps/tui/tests/workspace-summary.test.ts b/apps/tui/tests/workspace-summary.test.ts new file mode 100644 index 00000000..b222dc91 --- /dev/null +++ b/apps/tui/tests/workspace-summary.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'bun:test'; +import type { ToolCall, Turn } from '@felix/client'; +import { summarizeWorkspace } from '../src/workspace-summary'; + +const turn = (...tools: ToolCall[]): Turn => ({ + id: 'summary', + role: 'assistant', + content: 'All tests passed!', + tools, +}); +const call = (name: string, output: unknown, input: unknown = {}): ToolCall => ({ + name, + output, + input, + done: true, +}); + +describe('workspace results', () => { + it('does not count a pending approval as a completed write', () => { + const summary = summarizeWorkspace( + turn(call('local_write', '[approval required] request pending', { path: 'a.ts' })), + ); + expect(summary?.files).toEqual([]); + expect(summary?.unconfirmed).toEqual(['write a.ts']); + }); + + it('does not derive successful checks from model prose or read-only tools', () => { + expect(summarizeWorkspace(turn())).toBeNull(); + expect(summarizeWorkspace(turn(call('local_read', 'content', { path: 'file.ts' })))).toBeNull(); + }); + + it('separates observed mutations from commands, and includes rename destinations', () => { + const summary = summarizeWorkspace( + turn( + call('client · local_edit', '{"replacements":1}', { path: 'src/a.ts' }), + call('local_rename', '{"path":"a","to_path":"b"}', { path: 'a', to_path: 'b' }), + call('local_shell', '12 tests passed', { command: 'npm test' }), + ), + ); + expect(summary?.files).toEqual(['edit src/a.ts', 'rename a → b']); + expect(summary?.commands).toEqual(['npm test']); + }); + + it('never counts failures, denied calls or missing results as completed operations', () => { + const summary = summarizeWorkspace( + turn( + call('local_edit', 'error: file changed', { path: 'a.ts' }), + call('local_shell', '[tool error/provider_error] command exited with code 1', { + command: 'npm test', + }), + call('local_write', '[plan mode] local_write can change things', { path: 'b.ts' }), + call('local_shell', undefined, { command: 'npm run build' }), + { ...call('local_delete', undefined, { path: 'old.ts' }), done: false }, + ), + ); + expect(summary?.files).toEqual([]); + expect(summary?.commands).toEqual([]); + expect(summary?.issues).toHaveLength(3); + expect(summary?.unconfirmed).toEqual(['npm run build', 'delete old.ts']); + }); + + it('keeps failed attempts visible when a later retry succeeds', () => { + const summary = summarizeWorkspace( + turn( + call('local_shell', 'error: unsupported command', { command: 'npm test' }), + call('local_shell', 'passed', { command: 'npm test' }), + ), + ); + expect(summary?.commands).toEqual(['npm test']); + expect(summary?.issues).toHaveLength(1); + }); + + it('uses the latest observed plan state and retains blocked steps', () => { + const plan = (status: string) => + JSON.stringify({ + id: 'p', + plan: { + title: 'Build', + steps: [ + { id: '1', title: 'Implement', status }, + { id: '2', title: 'Verify', status: 'blocked', note: 'missing credentials' }, + ], + }, + }); + const summary = summarizeWorkspace( + turn( + call('plan_create', plan('pending')), + call('local_edit', 'edited', { path: 'a.ts' }), + call('plan_update_step', plan('done')), + ), + ); + expect(summary?.remaining).toEqual(['Verify · missing credentials']); + }); +}); diff --git a/apps/tui/tests/workspace.test.ts b/apps/tui/tests/workspace.test.ts index 6548d871..2fdbfc18 100644 --- a/apps/tui/tests/workspace.test.ts +++ b/apps/tui/tests/workspace.test.ts @@ -8,6 +8,7 @@ import { realpathSync, statSync, symlinkSync, + unlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -50,6 +51,96 @@ const allow = async () => true; /** A workspace that would say yes — so a refusal in a test is never the prompt's. */ const permissive = () => createWorkspace({ root, confirm: allow }); +describe('local_info', () => { + it.each([false, true])('reports native execution only with shell=%s', async (shell) => { + const confirm = vi.fn(async () => true); + const workspace = createWorkspace({ root, shell, confirm }); + const result = await workspace.execute(call('local_info', {})); + expect(result.error).not.toBe(true); + const info = JSON.parse(result.content); + expect(info.client).toBe('terminal'); + expect(info.workspace).toEqual({ kind: 'directory', root }); + expect(info.shell.mode).toBe(shell ? 'native' : 'emulated'); + if (shell) { + expect(info.shell.confirmation).toBe('always'); + expect(info.shell.sandboxed).toBe(false); + expect(info.shell.interpreter).toBe('/bin/sh'); + } else { + expect(info.shell.commands).not.toContain('git'); + expect(info.shell.commands).toContain('cat'); + } + expect(confirm).not.toHaveBeenCalled(); + }); +}); + +describe('edits while confirmation is pending', () => { + it('preserves a newer edit and permits a fresh retry', async () => { + const file = join(root, 'src', 'api.ts'); + let changed = false; + const workspace = createWorkspace({ + root, + confirm: async () => { + if (!changed) { + writeFileSync(file, 'export const x = 3;\n'); + changed = true; + } + return true; + }, + }); + const stale = await workspace.execute( + call('local_edit', { path: 'src/api.ts', old_string: '1', new_string: '2' }), + ); + expect(stale.error).toBe(true); + expect(stale.content).toContain('changed since it was read'); + expect(readFileSync(file, 'utf8')).toBe('export const x = 3;\n'); + const retry = await workspace.execute( + call('local_edit', { path: 'src/api.ts', old_string: '3', new_string: '4' }), + ); + expect(retry.error).not.toBe(true); + expect(readFileSync(file, 'utf8')).toBe('export const x = 4;\n'); + }); + + it('does not recreate a file deleted while confirmation was pending', async () => { + const file = join(root, 'src', 'api.ts'); + const workspace = createWorkspace({ + root, + confirm: async () => { + await import('node:fs/promises').then((fs) => fs.unlink(file)); + return true; + }, + }); + const result = await workspace.execute( + call('local_edit', { path: 'src/api.ts', old_string: '1', new_string: '2' }), + ); + expect(result.error).toBe(true); + expect(existsSync(file)).toBe(false); + }); +}); + +describe('local_instructions', () => { + it('reads applicable instructions from the real project without confirmation', async () => { + writeFileSync(join(root, 'AGENTS.md'), 'root instructions'); + writeFileSync(join(root, 'src', 'CLAUDE.md'), 'source instructions'); + const confirm = vi.fn(async () => true); + const result = await createWorkspace({ root, confirm }).execute( + call('local_instructions', { path: 'src/new.ts' }), + ); + expect(result.error).not.toBe(true); + expect( + JSON.parse(result.content).instructions.map((file: { content: string }) => file.content), + ).toEqual(['root instructions', 'source instructions']); + expect(confirm).not.toHaveBeenCalled(); + }); + + it('refuses an instruction file symlink outside the workspace', async () => { + writeFileSync(join(outside, 'instructions.md'), 'outside instructions'); + symlinkSync(join(outside, 'instructions.md'), join(root, 'AGENTS.md')); + const result = await permissive().execute(call('local_instructions', {})); + expect(result.error).toBe(true); + expect(result.content).not.toContain('outside instructions'); + }); +}); + describe('resolveWithin', () => { it('resolves a relative path under the root', async () => { await expect(resolveWithin(root, 'src/api.ts')).resolves.toBe(join(root, 'src', 'api.ts')); @@ -326,6 +417,58 @@ describe('the local_* file tools', () => { }); describe('local_delete and local_rename on the working directory', () => { + it('never overwrites a destination created during rename confirmation', async () => { + const workspace = createWorkspace({ + root, + confirm: async () => { + writeFileSync(join(root, 'new.ts'), 'newer destination'); + return true; + }, + }); + const result = await workspace.execute( + call('local_rename', { path: 'src/api.ts', to_path: 'new.ts' }), + ); + expect(result.error).toBe(true); + expect(readFileSync(join(root, 'new.ts'), 'utf8')).toBe('newer destination'); + expect(readFileSync(join(root, 'src', 'api.ts'), 'utf8')).toBe('export const x = 1;\n'); + }); + + it.each([ + 'local_delete', + 'local_rename', + ])('preserves a changed source during %s confirmation', async (name) => { + const file = join(root, 'src', 'api.ts'); + const workspace = createWorkspace({ + root, + confirm: async () => { + writeFileSync(file, 'newer user work'); + return true; + }, + }); + const result = await workspace.execute(call(name, { path: 'src/api.ts', to_path: 'new.ts' })); + expect(result.error).toBe(true); + expect(result.content).toContain('changed while awaiting approval'); + expect(readFileSync(file, 'utf8')).toBe('newer user work'); + expect(existsSync(join(root, 'new.ts'))).toBe(false); + }); + + it('refuses a source replaced by a symlink during delete confirmation', async () => { + const file = join(root, 'src', 'api.ts'); + writeFileSync(join(outside, 'secret.ts'), 'outside'); + const workspace = createWorkspace({ + root, + confirm: async () => { + unlinkSync(file); + symlinkSync(join(outside, 'secret.ts'), file); + return true; + }, + }); + const result = await workspace.execute(call('local_delete', { path: 'src/api.ts' })); + expect(result.error).toBe(true); + expect(readFileSync(file, 'utf8')).toBe('outside'); + expect(readFileSync(join(outside, 'secret.ts'), 'utf8')).toBe('outside'); + }); + it('delete removes a file after a yes that names it absolutely, and nothing without one', async () => { writeFileSync(join(root, 'gone.md'), 'x'); const asked: string[] = []; diff --git a/apps/web/tests/github-login.test.tsx b/apps/web/tests/github-login.test.tsx index 46e342c8..c3863d91 100644 --- a/apps/web/tests/github-login.test.tsx +++ b/apps/web/tests/github-login.test.tsx @@ -431,7 +431,13 @@ describe('the device flow, off the happy path', () => { it('selects the code for the keyboard when the clipboard refuses', async () => { routes['/api/auth/github/token'] = () => json({ error: 'authorization_pending', message: 'pending', interval: 5 }, 428); - const writeText = vi.fn().mockRejectedValue(new Error('denied')); + let refuseCopy!: (reason: Error) => void; + const writeText = vi.fn( + () => + new Promise((_resolve, reject) => { + refuseCopy = reject; + }), + ); vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText }, @@ -443,7 +449,11 @@ describe('the device flow, off the happy path', () => { fireEvent.click(screen.getByRole('button', { name: 'Copy code' })); }); expect(writeText).toHaveBeenCalledWith('WDJB-MJHT'); - expect(await screen.findByRole('button', { name: /could not copy/i })).toBeTruthy(); + // Settle the asynchronous clipboard result before inspecting its React update. + await act(async () => { + refuseCopy(new Error('denied')); + }); + expect(screen.getByRole('button', { name: /could not copy/i })).toBeTruthy(); expect(window.getSelection()?.toString()).toBe('WDJB-MJHT'); }); diff --git a/packages/cowork-client/src/client-tools.ts b/packages/cowork-client/src/client-tools.ts index 34212727..6577174a 100644 --- a/packages/cowork-client/src/client-tools.ts +++ b/packages/cowork-client/src/client-tools.ts @@ -126,10 +126,14 @@ export function workspaceFs(vfs: VirtualFs, check: () => void = () => {}): Local list: async (path) => checked(() => (hasMount() ? mountList(path || '.') : vfs.list(path || '.'))), read: async (path) => checked(() => (hasMount() ? mountRead(path) : vfs.read(path))), - write: async (path, content, { append }) => { + write: async (path, content, { append, expected }) => { check(); - if (hasMount()) await mountWrite(path, content, append, check); - else vfs.write(path, content, append); + if (hasMount()) await mountWrite(path, content, append, check, expected); + else { + if (expected !== undefined && vfs.read(path) !== expected) + throw new Error(`${path} changed since it was read; read it again before editing`); + vfs.write(path, content, append); + } }, // Files only, never overwriting — the same rules the operator's pane // follows, through the same helpers, gated by the same approval rule. @@ -206,6 +210,20 @@ async function runClientTool( ): Promise { try { check(); + if (req.name === 'local_info') { + return { + content: JSON.stringify({ + client: 'browser', + workspace: hasMount() + ? { kind: 'directory', label: getMountLabel() } + : { kind: 'virtual' }, + shell: { + mode: 'emulated', + commands: ['pwd', 'ls', 'cat', 'echo', 'mkdir', 'touch', 'tree', 'help'], + }, + }), + }; + } if (isLocalFileTool(req.name)) return await runLocalFileTool(req, workspaceFs(vfs, check)); if (req.name === 'local_shell') { const command = asString(req.args.command); diff --git a/packages/cowork-client/src/fs-mount.ts b/packages/cowork-client/src/fs-mount.ts index ad339814..0b23cf02 100644 --- a/packages/cowork-client/src/fs-mount.ts +++ b/packages/cowork-client/src/fs-mount.ts @@ -23,10 +23,12 @@ async function writeAndCommit( writable: FileSystemWritableFileStream, data: string | Uint8Array, check: MutationCheck, + beforeCommit?: () => Promise, ): Promise { try { check(); await writable.write(data); + await beforeCommit?.(); check(); await writable.close(); } catch (error) { @@ -224,11 +226,12 @@ export async function mountWrite( content: string, append = false, check: MutationCheck = unchecked, + expected?: string, ): Promise { - const { parent, name } = await resolve(path, { create: true, check }); + const { parent, name } = await resolve(path, { create: expected === undefined, check }); check(); if (!name) throw new Error('not a file'); - const fileHandle = await parent.getFileHandle(name, { create: true }); + const fileHandle = await parent.getFileHandle(name, { create: expected === undefined }); check(); let next = content; if (append) { @@ -241,8 +244,14 @@ export async function mountWrite( } } check(); + const verify = async () => { + if (expected !== undefined && (await (await fileHandle.getFile()).text()) !== expected) + throw new Error(`${path} changed since it was read; read it again before editing`); + check(); + }; + await verify(); const writable = await fileHandle.createWritable(); - await writeAndCommit(writable, next, check); + await writeAndCommit(writable, next, check, verify); } export async function mountMkdir(path: string, check: MutationCheck = unchecked): Promise { @@ -388,6 +397,12 @@ export async function mountRename( const writable = await out.createWritable(); await writeAndCommit(writable, bytes, check); check(); + const latest = new Uint8Array( + await (await (await src.parent.getFileHandle(src.name)).getFile()).arrayBuffer(), + ); + check(); + if (latest.length !== bytes.length || latest.some((byte, index) => byte !== bytes[index])) + throw new Error(`rename created ${to} but kept ${from}: source changed during the move`); await src.parent.removeEntry(src.name); } diff --git a/packages/cowork-client/tests/client-tools.test.ts b/packages/cowork-client/tests/client-tools.test.ts index d786f279..befe396d 100644 --- a/packages/cowork-client/tests/client-tools.test.ts +++ b/packages/cowork-client/tests/client-tools.test.ts @@ -10,6 +10,23 @@ beforeEach(() => { }); describe('executeClientTool', () => { + it('reports virtual files and emulation without opening or reading files', async () => { + const read = vi.spyOn(vfs, 'read'); + try { + const result = await executeClientTool({ id: 'info', name: 'local_info', args: {} }, vfs); + expect(result.error).not.toBe(true); + const info = JSON.parse(result.content); + expect(info.client).toBe('browser'); + expect(info.workspace).toEqual({ kind: 'virtual' }); + expect(info.shell.mode).toBe('emulated'); + expect(info.shell.commands).toContain('cat'); + expect(info.shell.commands).not.toContain('npm'); + expect(read).not.toHaveBeenCalled(); + } finally { + read.mockRestore(); + } + }); + it('runs a shell command against the tab VFS', async () => { vfs.write('notes/todo.md', 'one\n'); const result = await executeClientTool( diff --git a/packages/cowork-client/tests/fs-mount.test.ts b/packages/cowork-client/tests/fs-mount.test.ts index ec0b8554..b16666b6 100644 --- a/packages/cowork-client/tests/fs-mount.test.ts +++ b/packages/cowork-client/tests/fs-mount.test.ts @@ -52,11 +52,15 @@ class MockFileHandle { } async createWritable() { + let staged = this.content; return { write: async (data: string) => { - this.content = data; + staged = data; }, - close: async () => {}, + close: async () => { + this.content = staged; + }, + abort: async () => {}, }; } } @@ -126,6 +130,17 @@ afterEach(() => { }); describe('mount lifecycle', () => { + it('reports mount changes without claiming native shell access', async () => { + const request = { id: 'info', name: 'local_info', args: {} }; + const vfs = getVfs('mount-info'); + const mounted = JSON.parse((await executeClientTool(request, vfs)).content); + expect(mounted.workspace).toEqual({ kind: 'directory', label: 'project' }); + expect(mounted.shell.mode).toBe('emulated'); + clearMount(); + const cleared = JSON.parse((await executeClientTool(request, vfs)).content); + expect(cleared.workspace).toEqual({ kind: 'virtual' }); + }); + it('reports the picked folder', () => { expect(hasMount()).toBe(true); expect(getMountLabel()).toBe('project'); @@ -420,6 +435,53 @@ describe('folders in the mount', () => { }); }); +it('keeps a rename source edited while the destination is being written', async () => { + const source = await root.getFileHandle('source.ts', { create: true }); + source.content = 'original'; + const getFile = root.getFileHandle.bind(root); + vi.spyOn(root, 'getFileHandle').mockImplementation(async (name, opts) => { + const file = await getFile(name, opts); + if (name === 'destination.ts' && opts?.create) { + const create = file.createWritable.bind(file); + vi.spyOn(file, 'createWritable').mockImplementation(async () => { + const stream = await create(); + source.content = 'newer source work'; + return stream; + }); + } + return file; + }); + await expect(mountRename('source.ts', 'destination.ts')).rejects.toThrow(/source changed/); + expect(await mountRead('source.ts')).toBe('newer source work'); + expect(await mountRead('destination.ts')).toBe('original'); +}); + +it('preserves a concurrent edit instead of committing a stale replacement', async () => { + const file = await root.getFileHandle('code.ts', { create: true }); + file.content = 'before'; + const original = file.createWritable.bind(file); + vi.spyOn(file, 'createWritable').mockImplementation(async () => { + const stream = await original(); + file.content = 'newer user edit'; + return stream; + }); + await expect(mountWrite('code.ts', 'replacement', false, () => {}, 'before')).rejects.toThrow( + /changed since it was read/, + ); + expect(file.content).toBe('newer user edit'); +}); + +it('refuses a stale edit before opening a writable stream', async () => { + const file = await root.getFileHandle('code.ts', { create: true }); + file.content = 'newer user edit'; + const open = vi.spyOn(file, 'createWritable'); + await expect(mountWrite('code.ts', 'replacement', false, () => {}, 'before')).rejects.toThrow( + /changed since it was read/, + ); + expect(open).not.toHaveBeenCalled(); + expect(file.content).toBe('newer user edit'); +}); + it('aborts an uncommitted write when the request is stopped', async () => { const file = await root.getFileHandle('code.ts', { create: true }); file.content = 'before'; diff --git a/packages/felix-client/src/local-files.ts b/packages/felix-client/src/local-files.ts index 29e2cbe3..6c9ab743 100644 --- a/packages/felix-client/src/local-files.ts +++ b/packages/felix-client/src/local-files.ts @@ -46,7 +46,7 @@ export function fileToolOp(toolName: string): FileToolOp | null { /** True for a client tool this module answers. */ export function isLocalFileTool(name: string): boolean { - return name.startsWith('local_') && name in OPS; + return name === 'local_instructions' || (name.startsWith('local_') && name in OPS); } export interface LocalEntry { @@ -63,8 +63,16 @@ export interface LocalFs { /** Direct entries of a directory (`''` or `.` is the root). */ list(path: string): Promise; read(path: string): Promise; - /** Create or replace a file, creating parent directories. May throw a refusal. */ - write(path: string, content: string, opts: { append: boolean; summary: string }): Promise; + /** + * Create or replace a file, creating parent directories. May throw a refusal. + * When expected is supplied, refuse if the current contents differ before + * writing (after any confirmation) or committing a staged browser write. + */ + write( + path: string, + content: string, + opts: { append: boolean; summary: string; expected?: string }, + ): Promise; /** * Delete one file — never a directory. May throw a refusal. Absent from a * filesystem that cannot, which `local_delete` then reports as an error. @@ -158,6 +166,57 @@ async function read(fs: LocalFs, args: Record): Promise return `${slice}\n[… characters ${offset}–${end} of ${text.length}; pass offset=${end} to read on]`; } +/** Read only instruction files governing a target, never unrelated subtrees. */ +async function instructions(fs: LocalFs, args: Record): Promise { + const raw = str(args.path) ?? ''; + const normalized = raw.replace(/\\/g, '/'); + if (normalized.startsWith('/') || /^[a-z]:/i.test(normalized) || normalized.includes('\0')) + throw new Error('path must be a file relative to the workspace root'); + const parts = normalized.split('/').filter((part) => part && part !== '.'); + if (parts.includes('..')) throw new Error('instruction paths cannot contain ..'); + if (parts.length > 33) throw new Error('instruction path exceeds 32 directories'); + // An omitted path asks for root instructions; otherwise path names a target file. + const parents = parts.slice(0, -1); + const found: Array<{ path: string; content: string; truncated: boolean; next_offset: number }> = + []; + let remaining = 48_000; + let directory = ''; + let entries = await fs.list(directory); + for (let depth = 0; depth <= parents.length; depth++) { + for (const name of ['AGENTS.md', 'CLAUDE.md']) { + const path = directory ? `${directory}/${name}` : name; + if (!entries.some((entry) => entry.path === path && entry.type === 'file')) continue; + // A listed but unreadable instruction is an error, not an absent instruction. + const text = await fs.read(path); + if (text.includes('\0')) throw new Error(`${path} is not a text instruction file`); + const content = text.slice(0, Math.min(16_000, remaining)); + remaining -= content.length; + found.push({ + path, + content, + truncated: content.length < text.length, + next_offset: content.length, + }); + } + const next = parents[depth]; + if (next === undefined) break; + const path = directory ? `${directory}/${next}` : next; + const entry = entries.find((candidate) => candidate.path === path); + // A new directory has no nested instructions yet; its existing ancestors still apply. + if (!entry) break; + if (entry.type !== 'dir') throw new Error(`${path} is not a directory`); + directory = path; + entries = await fs.list(directory); + } + return JSON.stringify({ + target: parts.join('/'), + instructions: found, + complete: found.every((file) => !file.truncated), + guidance: + 'Read in order. Deeper instructions govern their subtree. Use local_read with offset=next_offset for truncated files before editing.', + }); +} + /** A regular expression the model wrote, or a literal match; never throws. */ function matcher(query: string, regex: boolean): ((line: string) => boolean) | string { if (!regex) return (line) => line.includes(query); @@ -242,6 +301,7 @@ async function edit(fs: LocalFs, args: Record): Promise : text.replace(oldString, () => newString); await fs.write(path, next, { append: false, + expected: text, summary: `edit (${found} replacement${found === 1 ? '' : 's'})`, }); return JSON.stringify({ path, replacements: all ? found : 1 }); @@ -280,6 +340,7 @@ export async function runLocalFileTool( ): Promise { const args = req.args ?? {}; try { + if (req.name === 'local_instructions') return { content: await instructions(fs, args) }; let content: string; switch (fileToolOp(req.name)) { case 'list': diff --git a/packages/felix-client/tests/local-files.test.ts b/packages/felix-client/tests/local-files.test.ts index 311e3874..cbc9d06f 100644 --- a/packages/felix-client/tests/local-files.test.ts +++ b/packages/felix-client/tests/local-files.test.ts @@ -62,6 +62,98 @@ describe('fileToolOp', () => { }); }); +describe('local_instructions', () => { + it('reads root and applicable nested instructions in order without changing files', async () => { + const { fs, writes } = memoryFs({ + 'AGENTS.md': 'root', + 'CLAUDE.md': 'root commands', + 'src/AGENTS.md': 'source', + 'src/lib/AGENTS.md': 'library', + 'other/AGENTS.md': 'unrelated', + 'src/lib/code.ts': 'code', + }); + expect(isLocalFileTool('local_instructions')).toBe(true); + const result = await run(fs, 'local_instructions', { path: 'src/lib/code.ts' }); + expect(result.error).not.toBe(true); + const out = JSON.parse(result.content); + expect(out.instructions.map((file: { path: string }) => file.path)).toEqual([ + 'AGENTS.md', + 'CLAUDE.md', + 'src/AGENTS.md', + 'src/lib/AGENTS.md', + ]); + expect(out.complete).toBe(true); + expect(writes).toEqual([]); + }); + + it('finds instructions for a file in directories that do not exist yet', async () => { + const { fs } = memoryFs({ 'AGENTS.md': 'root', 'src/AGENTS.md': 'source' }); + const out = JSON.parse( + (await run(fs, 'local_instructions', { path: 'src/new/deep/file.ts' })).content, + ); + expect(out.instructions.map((file: { content: string }) => file.content)).toEqual([ + 'root', + 'source', + ]); + }); + + it('asks only for root instructions when no target is given', async () => { + const { fs } = memoryFs({ 'AGENTS.md': 'root', 'src/AGENTS.md': 'nested' }); + const out = JSON.parse((await run(fs, 'local_instructions', {})).content); + expect(out.instructions).toHaveLength(1); + expect(out.instructions[0].path).toBe('AGENTS.md'); + }); + + it('reports an empty instruction set explicitly', async () => { + const { fs } = memoryFs({ 'README.md': 'project' }); + const out = JSON.parse((await run(fs, 'local_instructions', {})).content); + expect(out.instructions).toEqual([]); + expect(out.complete).toBe(true); + }); + + it.each([ + '../secret.ts', + '/etc/file', + 'C:\\secret.ts', + 'src/../../file', + 'src\\..\\file', + `${'a/'.repeat(34)}file`, + ])('refuses unsafe or excessive paths: %s', async (path) => { + const { fs } = memoryFs({ 'AGENTS.md': 'root' }); + expect((await run(fs, 'local_instructions', { path })).error).toBe(true); + }); + + it('does not silently ignore an unreadable instruction', async () => { + const { fs } = memoryFs({ 'AGENTS.md': 'root' }); + fs.read = async () => { + throw new Error('permission denied'); + }; + const result = await run(fs, 'local_instructions', {}); + expect(result.error).toBe(true); + expect(result.content).toContain('permission denied'); + }); + + it('bounds the combined text and tells the caller where to continue every truncated file', async () => { + const { fs } = memoryFs({ + 'AGENTS.md': 'a'.repeat(20_000), + 'CLAUDE.md': 'b'.repeat(20_000), + 'src/AGENTS.md': 'c'.repeat(20_000), + 'src/CLAUDE.md': 'd'.repeat(20_000), + }); + const out = JSON.parse((await run(fs, 'local_instructions', { path: 'src/code.ts' })).content); + expect(out.complete).toBe(false); + expect(out.instructions.map((file: { next_offset: number }) => file.next_offset)).toEqual([ + 16_000, 16_000, 16_000, 0, + ]); + expect(out.instructions.every((file: { truncated: boolean }) => file.truncated)).toBe(true); + const more = await run(fs, 'local_read', { + path: out.instructions[0].path, + offset: out.instructions[0].next_offset, + }); + expect(more.content).toContain('a'.repeat(4_000)); + }); +}); + describe('local_list', () => { it('lists direct entries, directories ending in a slash', async () => { const { fs } = memoryFs({ 'README.md': '', '.github/ci.yml': '', 'src/a.ts': '' });