Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): fs_edit reports the diff it applied and can preview without writing (#178)
Abdurrahman Fakhrulae3cbbd8a8d1
diff --git a/docs/AGENT-CODING-PLAN.md b/docs/AGENT-CODING-PLAN.mdindex 6ad45ecb..f06614cc 100644--- a/docs/AGENT-CODING-PLAN.md+++ b/docs/AGENT-CODING-PLAN.md@@ -50,6 +50,9 @@ an interactive process cannot be driven.`/diff` renders the server's historical artifact diff. There is no preview of a pending edit.+**Closed.** `fs_edit` now returns the diff it applied and accepts `dry_run: true`, and the TUI+renders that diff under the `fs_edit` row. See `docs/AGENT-EDIT-PREVIEW.md`.+## What I will build, in this order| # | Item | Seam it uses | Why this order |@@ -59,7 +62,8 @@ an interactive process cannot be driven.| 3 | `fs_glob` tool: path glob (`**/*.ts`) bounded by root | same leaf | cheap once grep exists || 4 | `todo_write` tool: session-scoped checklist the TUI renders | session store | keeps long tasks honest || 5 | Background subagent: `agent_subagent_start` + `agent_subagent_status` | existing subagent runner + `exec_job_*` lifecycle pattern | enables parallelism |-| 6 | TUI: render todo list, and `fs_edit` preview | `mso-agent-layout.mjs` section helpers | visibility |+| 6 | TUI: render the `fs_edit` diff, and `dry_run` on `fs_edit` itself | returned tool result, no extra round trip | visibility |+| 7 | TUI: render the `todo_write` list | session state on the status row | not started |## Non-negotiable constraintsdiff --git a/docs/AGENT-EDIT-PREVIEW.md b/docs/AGENT-EDIT-PREVIEW.mdnew file mode 100644index 00000000..9fd8555d--- /dev/null+++ b/docs/AGENT-EDIT-PREVIEW.md@@ -0,0 +1,74 @@+# Pending-edit preview: design note++Item 6 in `docs/AGENT-CODING-PLAN.md`: "the TUI cannot show a diff before writing. `/diff`+renders the server's historical artifact diff. There is no preview of a pending edit."++## What is actually missing++Two different things, and only the first one is a coding gap:++1. **The agent cannot preview its own edit.** `fs_edit` writes immediately. An agent that+ wants to check "does this old_string match exactly once, and what exactly changes" has to+ write and then read back, which is a write it cannot undo.+2. **The owner cannot see what changed.** The TUI prints `[write] fs_edit` and then+ `✓ fs_edit`. The change itself is invisible. That is the reason `/diff` exists as a+ separate command, and why it only ever shows historical artifact diffs.++Claude Code and opencode both answer these with the same shape: the edit tool returns the+diff it applied, and the UI renders that diff inline.++## Design++### A pure diff function, not a diff library++`lib/host/fs-edit-diff.ts` exports `editDiff(before, after, { context, maxLines })`.++No diff algorithm. `fs_edit` derives `after` from `before` by one substitution, so the+change region is exactly the common prefix and the common suffix around it. That is cheap,+exact, and cannot misattribute a change the way a heuristic line matcher can. The output is+unified-diff shaped so it renders with the colours `/diff` already uses:++```+@@ -12,6 +12,7 @@+ context+-removed++added+ context+```++`maxLines` defaults to 40. When the changed region is longer, the hunk is cut and a+`… N more lines` line is appended, with `truncated: true` so the caller knows the diff is+not the whole story. A silently short diff would be worse than no diff.++### `fs_edit` returns the diff it applied, and can dry-run++- Always: `diff`, `diffTruncated` on the result, so the caller sees what happened without a+ follow-up read.+- New `dry_run: true`: compute and validate everything (empty search, uniqueness, size caps,+ CAS hash), return the diff and the projected `sha256`, and **write nothing**.+ `written: false` is in the result so a caller cannot mistake a preview for a commit.++The projected hash in a dry run is deliberately the future hash, not the current one. If a+caller wrongly passes it as `expected_sha256`, the real edit fails as stale, which is a safe+failure. The reverse (returning the current hash) would silently allow a stale write.++### The TUI renders the returned diff++`scripts/mso-agent-edit-diff.mjs` holds the rendering, so `scripts/mso-agent-turn.mjs` grows+by a handful of lines rather than becoming the next file over the 220 ratchet. It renders+under the `✓ fs_edit` row, dim context, green additions, red removals, using the same width+discipline as the rest of the transcript so a long line does not wrap into a wall.++## Bounds++- Diff text is capped per edit (`maxLines`), and the tool result already has a byte cap.+- `dry_run` performs no write, so it cannot be used to probe write access differently than a+ real edit: it runs the same guards before returning.++## Explicitly not in scope++- An interactive approve/reject prompt for each edit. Approval already exists at the tool+ level (`requestExactToolApproval` with a digest); adding a second gate inside the edit+ would mean two places decide the same thing.+- Replacing `/diff`. That command answers "what did this session change to artifacts over+ time", which is a different question from "what did this one call change".diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 180eabfe..3b0969f5 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Added**+- `agent` fs_edit reports the diff it applied and can preview without writing- `agent` a bounded pty_session tool, so an agent can drive an interactive process (#176)- `agent` background subagents, so a parent can keep working in parallel (#175)- `agent` surgical edit, content search, glob and a todo list (#173)diff --git a/docs/README.md b/docs/README.mdindex 356b81fa..2652d5a6 100644--- a/docs/README.md+++ b/docs/README.md@@ -33,6 +33,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`AGENT-BOOTSTRAP.md`](./AGENT-BOOTSTRAP.md) | Canonical first-call sequence and capability-parity matrix across CLI, MCP, and Alfa || [`AGENT-CODING-PLAN.md`](./AGENT-CODING-PLAN.md) | Audited coding-capability gaps in the MCP catalog, the four tools added to close them, and what stays out of scope || [`AGENT-PTY-DESIGN.md`](./AGENT-PTY-DESIGN.md) | Why an agent-driven PTY is the highest-blast-radius tool in the catalog, and the bounds that keep it equal to exec_run |+| [`AGENT-EDIT-PREVIEW.md`](./AGENT-EDIT-PREVIEW.md) | Why fs_edit returns the diff it applied, what a dry run promises, and how the TUI renders it || [`RASMIC.md`](./RASMIC.md) | Risk-aware orchestration, repo-local memory/evidence, collision detection and recipe/script promotion || [`MEMORY-GRAPH.md`](./MEMORY-GRAPH.md) | Owner Memory app: vault notes, project knowledge, agent memory, layouts and limits || [`AGENT-VAULT.md`](./AGENT-VAULT.md) | Separate private repository agent-progress vaults, source/data boundaries and Obsidian use |diff --git a/lib/host/fs-edit-diff.test.ts b/lib/host/fs-edit-diff.test.tsnew file mode 100644index 00000000..c2a22df4--- /dev/null+++ b/lib/host/fs-edit-diff.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import { editDiff } from "./fs-edit-diff";++const lines = (text: string) => text.split("\n");++describe("editDiff", () => {+ it("reports a single-line substitution with its context", () => {+ const before = "const x = 1;\nexport const y = 2;\n";+ const after = "const x = 42;\nexport const y = 2;\n";++ const result = editDiff(before, after);++ expect(result.removed).toBe(1);+ expect(result.added).toBe(1);+ expect(result.truncated).toBe(false);+ expect(lines(result.diff)).toEqual([+ "@@ -1,2 +1,2 @@",+ "-const x = 1;",+ "+const x = 42;",+ " export const y = 2;",+ ]);+ });++ it("keeps three context lines on each side and nothing more", () => {+ const before = "a\nb\nc\nd\ne\nf\ng\nh\ni\n";+ const after = "a\nb\nc\nD\ne\nf\ng\nh\ni\n";++ const body = lines(editDiff(before, after).diff);++ expect(body[0]).toBe("@@ -1,7 +1,7 @@");+ expect(body.filter((line) => line.startsWith(" "))).toHaveLength(6);+ expect(body).toContain("-d");+ expect(body).toContain("+D");+ expect(body).not.toContain(" i");+ });++ it("hunk header names the real line number of the change", () => {+ const before = Array.from({ length: 60 }, (_, i) => `line ${i}`).join("\n");+ const after = before.replace("line 30", "LINE 30");++ const body = lines(editDiff(before, after).diff);++ // line 30 is the 31st line; three lines of context start at line 28.+ expect(body[0]).toBe("@@ -28,7 +28,7 @@");+ expect(body).toContain("-line 30");+ expect(body).toContain("+LINE 30");+ });++ it("drops context entirely when context is 0", () => {+ const body = lines(editDiff("a\nb\nc\n", "a\nB\nc\n", { context: 0 }).diff);+ expect(body).toEqual(["@@ -2,1 +2,1 @@", "-b", "+B"]);+ });++ it("handles an insertion at end of file with no trailing newline", () => {+ const result = editDiff("a\nb", "a\nb\nc");+ expect(result.added).toBe(1);+ expect(lines(result.diff)).toEqual(["@@ -1,2 +1,3 @@", " a", " b", "+c"]);+ });++ it("handles a deletion", () => {+ const result = editDiff("a\nb\nc\n", "a\nc\n");+ expect(result.removed).toBe(1);+ expect(result.added).toBe(0);+ expect(lines(result.diff)).toContain("-b");+ });++ it("reports every replaced region of a replace-all as one hunk", () => {+ const result = editDiff("x\nx\nx\n", "y\ny\ny\n");+ expect(result.removed).toBe(3);+ expect(result.added).toBe(3);+ expect(lines(result.diff).filter((line) => line === "-x")).toHaveLength(3);+ expect(lines(result.diff).filter((line) => line === "+y")).toHaveLength(3);+ });++ it("returns nothing when the text is unchanged", () => {+ expect(editDiff("same\n", "same\n")).toEqual({ diff: "", truncated: false, removed: 0, added: 0 });+ });++ it("truncates at maxLines and says how much it withheld, without losing the counts", () => {+ const before = Array.from({ length: 80 }, (_, i) => `line ${i}`).join("\n");+ const after = Array.from({ length: 80 }, (_, i) => `changed ${i}`).join("\n");++ const result = editDiff(before, after, { maxLines: 12 });+ const body = lines(result.diff);++ expect(result.truncated).toBe(true);+ expect(body.length).toBe(12);+ expect(body[body.length - 1]).toMatch(/^… \d+ more lines$/);+ // The counts describe the real change, not the truncated rendering.+ expect(result.removed).toBe(80);+ expect(result.added).toBe(80);+ });++ it("keeps CRLF content byte-faithful instead of normalising it", () => {+ const result = editDiff("a\r\nb\r\n", "a\r\nB\r\n");+ expect(lines(result.diff)).toContain("-b\r");+ expect(lines(result.diff)).toContain("+B\r");+ });+});diff --git a/lib/host/fs-edit-diff.ts b/lib/host/fs-edit-diff.tsnew file mode 100644index 00000000..509fefaf--- /dev/null+++ b/lib/host/fs-edit-diff.ts@@ -0,0 +1,82 @@+// Unified-diff shape for a surgical edit, without a diff library.+//+// `fs_edit` replaces one exact substring, so the changed block is the run of lines between+// the common line prefix and the common line suffix. Working in lines rather than characters+// is what keeps an insertion at a line boundary from being reported as a rewrite of the line+// before it, and it is the same granularity `git diff` reports.+//+// The output is deliberately the shape `mso-agent-diff.mjs` already colours, so one renderer+// serves both the historical artifact diff and a live edit.++const DEFAULT_CONTEXT = 3;+const DEFAULT_MAX_LINES = 40;++export interface EditDiffOptions {+ /** Unchanged lines shown on each side of the change. */+ context?: number;+ /** Hard cap on rendered lines, header included. A silently short diff is worse than none. */+ maxLines?: number;+}++export interface EditDiffResult {+ diff: string;+ truncated: boolean;+ removed: number;+ added: number;+}++/** A trailing newline terminates the last line, it does not add an empty one. */+const splitLines = (text: string): string[] => {+ if (!text) return [];+ const all = text.split("\n");+ if (all[all.length - 1] === "") all.pop();+ return all;+};++export function editDiff(before: string, after: string, options: EditDiffOptions = {}): EditDiffResult {+ if (before === after) return { diff: "", truncated: false, removed: 0, added: 0 };++ const context = Math.max(0, Math.trunc(options.context ?? DEFAULT_CONTEXT));+ const maxLines = Math.max(3, Math.trunc(options.maxLines ?? DEFAULT_MAX_LINES));++ const beforeLines = splitLines(before);+ const afterLines = splitLines(after);++ let start = 0;+ while (start < beforeLines.length && start < afterLines.length && beforeLines[start] === afterLines[start]) start += 1;++ let endBefore = beforeLines.length;+ let endAfter = afterLines.length;+ while (endBefore > start && endAfter > start && beforeLines[endBefore - 1] === afterLines[endAfter - 1]) {+ endBefore -= 1;+ endAfter -= 1;+ }++ const removed = beforeLines.slice(start, endBefore);+ const added = afterLines.slice(start, endAfter);+ const lead = beforeLines.slice(Math.max(0, start - context), start);+ const trail = beforeLines.slice(endBefore, endBefore + context);+ const hunkStart = Math.max(0, start - context) + 1;+ const header = `@@ -${hunkStart},${lead.length + removed.length + trail.length} +${hunkStart},${lead.length + added.length + trail.length} @@`;++ const body = [+ ...lead.map((line) => ` ${line}`),+ ...removed.map((line) => `-${line}`),+ ...added.map((line) => `+${line}`),+ ...trail.map((line) => ` ${line}`),+ ];++ const budget = maxLines - 1;+ if (body.length <= budget) {+ return { diff: [header, ...body].join("\n"), truncated: false, removed: removed.length, added: added.length };+ }++ const kept = body.slice(0, Math.max(0, budget - 1));+ const withheld = body.length - kept.length;+ return {+ diff: [header, ...kept, `… ${withheld} more lines`].join("\n"),+ truncated: true,+ removed: removed.length,+ added: added.length,+ };+}diff --git a/lib/host/fs-edit.ts b/lib/host/fs-edit.tsindex 51902259..f0fcfdd9 100644--- a/lib/host/fs-edit.ts+++ b/lib/host/fs-edit.ts@@ -1,7 +1,8 @@import { HostError } from "./host-error";import { readFile, statReadableMeta } from "./fs";import { writeFileGuarded } from "./guarded-write";-import { utf8Bytes } from "./hash";+import { sha256Text, utf8Bytes } from "./hash";+import { editDiff } from "./fs-edit-diff";const MAX_READ_BYTES = 2 * 1024 * 1024; // 2 MiBconst MAX_WRITE_BYTES = 8 * 1024 * 1024; // 8 MiB@@ -12,6 +13,7 @@ export interface EditFileInput {newString: string;replaceAll?: boolean;expectedSha256?: string;+ dryRun?: boolean;}export interface EditFileResult {@@ -20,6 +22,11 @@ export interface EditFileResult {replacements: number;bytes: number;sha256: string;+ written: boolean;+ diff: string;+ diffTruncated: boolean;+ removedLines: number;+ addedLines: number;previousSha256?: string;}@@ -33,8 +40,20 @@ function countOccurrences(content: string, search: string): number {return count;}+function checkExpectedSha(expectedSha256: string | undefined, currentContent: string): string | undefined {+ if (!expectedSha256) return undefined;+ if (!/^[a-f0-9]{64}$/i.test(expectedSha256)) {+ throw new HostError("expected_sha256 must be a 64-character SHA-256 hex digest from fs_read");+ }+ const currentSha = sha256Text(currentContent);+ if (currentSha.toLowerCase() !== expectedSha256.toLowerCase()) {+ throw new HostError("File changed since fs_read; inspect it again before overwriting");+ }+ return currentSha;+}+export async function editFileGuarded(input: EditFileInput): Promise<EditFileResult> {- const { path, oldString, newString, replaceAll = false, expectedSha256 } = input;+ const { path, oldString, newString, replaceAll = false, expectedSha256, dryRun = false } = input;if (oldString === "") {throw new HostError("old_string must not be empty");@@ -74,6 +93,26 @@ export async function editFileGuarded(input: EditFileInput): Promise<EditFileResthrow new HostError(`Replacement would push file over limit (max ${MAX_WRITE_BYTES} bytes, resulting file is ${nextBytes} bytes)`);}+ const previousSha256 = checkExpectedSha(expectedSha256, currentContent);++ const diffResult = editDiff(currentContent, nextContent);++ if (dryRun) {+ return {+ ok: true,+ path,+ replacements: occurrences,+ bytes: nextBytes,+ sha256: sha256Text(nextContent),+ written: false,+ diff: diffResult.diff,+ diffTruncated: diffResult.truncated,+ removedLines: diffResult.removed,+ addedLines: diffResult.added,+ ...(previousSha256 ? { previousSha256 } : {}),+ };+ }+const writeResult = await writeFileGuarded({path,content: nextContent,@@ -86,6 +125,11 @@ export async function editFileGuarded(input: EditFileInput): Promise<EditFileResreplacements: occurrences,bytes: writeResult.bytes,sha256: writeResult.sha256,+ written: true,+ diff: diffResult.diff,+ diffTruncated: diffResult.truncated,+ removedLines: diffResult.removed,+ addedLines: diffResult.added,...(writeResult.previousSha256 ? { previousSha256: writeResult.previousSha256 } : {}),};}diff --git a/lib/mcp/fs-edit.test.ts b/lib/mcp/fs-edit.test.tsindex 8498f3e8..01a34317 100644--- a/lib/mcp/fs-edit.test.ts+++ b/lib/mcp/fs-edit.test.ts@@ -9,17 +9,14 @@ import { READ_TOOLS } from "./tools-read";import { sha256Text } from "@/lib/host/fs-api";vi.mock("server-only", () => ({}));-vi.mock("@/lib/host/audit-api", async (original) => {- const actual = (await original()) as typeof import("@/lib/host/audit-api");- return { ...actual, audit: vi.fn(async () => {}) };-});-vi.mock("@/lib/agent/session-store", async (original) => {- const actual = (await original()) as typeof import("@/lib/agent/session-store");- return { ...actual, maybeAutoTitleAgentSession: vi.fn(async () => {}), appendAgentSessionEvent: vi.fn(async () => {}) };-});+vi.mock("@/lib/host/audit-api", async (orig) => ({ ...((await orig()) as object), audit: vi.fn(async () => {}) }));+vi.mock("@/lib/agent/session-store", async (orig) => ({+ ...((await orig()) as object),+ maybeAutoTitleAgentSession: vi.fn(async () => {}),+ appendAgentSessionEvent: vi.fn(async () => {}),+}));const { executeCapabilityCall } = await import("@/lib/capabilities/execute");-const edit = EDIT_TOOLS.find((tool) => tool.name === "fs_edit")!;const read = READ_TOOLS.find((tool) => tool.name === "fs_read")!;const actor = "mcp:fs-edit-test";@@ -49,20 +46,11 @@ describe("fs_edit tool", () => {it("1. unique match replaces exactly once and returns the new sha256 that fs_read would compute", async () => {const original = "Hello World\nLine 2\nLine 3\n";await fs.writeFile(filePath, original, "utf8");-const res = await call(edit, { path: filePath, old_string: "World", new_string: "MSO" });- expect(res).toMatchObject({- kind: "success",- result: { ok: true, path: filePath, replacements: 1 },- });-+ expect(res).toMatchObject({ kind: "success", result: { ok: true, path: filePath, replacements: 1 } });const expectedContent = "Hello MSO\nLine 2\nLine 3\n";const readResult = await call(read, { path: filePath }, "read");- expect(readResult).toMatchObject({- kind: "success",- result: { content: expectedContent, sha256: sha256Text(expectedContent) },- });-+ expect(readResult).toMatchObject({ kind: "success", result: { content: expectedContent, sha256: sha256Text(expectedContent) } });const editOutput = (res as { result: { sha256: string; bytes: number } }).result;expect(editOutput.sha256).toBe(sha256Text(expectedContent));expect(editOutput.bytes).toBe(Buffer.byteLength(expectedContent, "utf8"));@@ -71,121 +59,120 @@ describe("fs_edit tool", () => {it("2. two matches without replace_all FAILS and leaves the file byte-identical", async () => {const original = "foo bar foo baz\n";await fs.writeFile(filePath, original, "utf8");-const res = await call(edit, { path: filePath, old_string: "foo", new_string: "qux" });expect(res).toMatchObject({kind: "error",message: expect.stringMatching(/Found 2 occurrences of old_string.*Pass more surrounding context or set replace_all/i),});-- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(original);+ expect(await fs.readFile(filePath, "utf8")).toBe(original);});it("3. two matches with replace_all: true replaces both", async () => {const original = "apple orange apple pear\n";await fs.writeFile(filePath, original, "utf8");-- const res = await call(edit, {- path: filePath,- old_string: "apple",- new_string: "grape",- replace_all: true,- });-+ const res = await call(edit, { path: filePath, old_string: "apple", new_string: "grape", replace_all: true });const expected = "grape orange grape pear\n";- expect(res).toMatchObject({- kind: "success",- result: { ok: true, path: filePath, replacements: 2, sha256: sha256Text(expected) },- });-- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(expected);+ expect(res).toMatchObject({ kind: "success", result: { ok: true, path: filePath, replacements: 2, sha256: sha256Text(expected) } });+ expect(await fs.readFile(filePath, "utf8")).toBe(expected);});it("4. zero matches FAILS, file unchanged", async () => {const original = "first line\nsecond line\n";await fs.writeFile(filePath, original, "utf8");-const res = await call(edit, { path: filePath, old_string: "third line", new_string: "replacement" });- expect(res).toMatchObject({- kind: "error",- message: expect.stringMatching(/old_string not found/i),- });-- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(original);+ expect(res).toMatchObject({ kind: "error", message: expect.stringMatching(/old_string not found/i) });+ expect(await fs.readFile(filePath, "utf8")).toBe(original);});it("5. empty old_string FAILS", async () => {const original = "hello world\n";await fs.writeFile(filePath, original, "utf8");-const res = await call(edit, { path: filePath, old_string: "", new_string: "something" });- expect(res).toMatchObject({- kind: "error",- message: expect.stringMatching(/must be a non-empty string|old_string must not be empty/i),- });-- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(original);+ expect(res).toMatchObject({ kind: "error", message: expect.stringMatching(/must be a non-empty string|old_string must not be empty/i) });+ expect(await fs.readFile(filePath, "utf8")).toBe(original);});it("6. stale expected_sha256 FAILS and does not write", async () => {const original = "current file contents\n";await fs.writeFile(filePath, original, "utf8");-- const staleHash = "0000000000000000000000000000000000000000000000000000000000000000";- const res = await call(edit, {- path: filePath,- old_string: "current",- new_string: "modified",- expected_sha256: staleHash,- });-- expect(res).toMatchObject({- kind: "error",- message: expect.stringMatching(/File changed since fs_read/i),- });-- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(original);+ const res = await call(edit, { path: filePath, old_string: "current", new_string: "modified", expected_sha256: "0".repeat(64) });+ expect(res).toMatchObject({ kind: "error", message: expect.stringMatching(/File changed since fs_read/i) });+ expect(await fs.readFile(filePath, "utf8")).toBe(original);});it("7. correct expected_sha256 succeeds", async () => {const original = "version 1.0\nstable\n";await fs.writeFile(filePath, original, "utf8");const currentHash = sha256Text(original);+ const res = await call(edit, { path: filePath, old_string: "version 1.0", new_string: "version 2.0", expected_sha256: currentHash });+ const expected = "version 2.0\nstable\n";+ expect(res).toMatchObject({ kind: "success", result: { ok: true, path: filePath, replacements: 1, sha256: sha256Text(expected), previousSha256: currentHash } });+ expect(await fs.readFile(filePath, "utf8")).toBe(expected);+ });- const res = await call(edit, {- path: filePath,- old_string: "version 1.0",- new_string: "version 2.0",- expected_sha256: currentHash,- });+ it("8. a path outside the write roots is refused (whatever refusal the existing guard produces)", async () => {+ const res = await call(edit, { path: "/etc/hosts", old_string: "localhost", new_string: "remotehost" });+ expect(res).toMatchObject({ kind: "error", message: expect.stringMatching(/outside writable roots|outside readable roots/i) });+ });- const expected = "version 2.0\nstable\n";- expect(res).toMatchObject({- kind: "success",- result: {- ok: true,- path: filePath,- replacements: 1,- sha256: sha256Text(expected),- previousSha256: currentHash,- },- });+ it("9. real edit returns a diff containing -<old line> and +<new line> and leaves rest of file unchanged", async () => {+ const original = "prefix line\nhello world\nsecond line\nsuffix line\n";+ await fs.writeFile(filePath, original, "utf8");+ const res = await call(edit, { path: filePath, old_string: "hello world\nsecond line", new_string: "hello MSO\nsecond line modified" });+ expect(res).toMatchObject({ kind: "success", result: { ok: true, written: true, diffTruncated: false } });+ const diff = (res as { result: { diff: string } }).result.diff;+ expect(diff).toContain("-hello world");+ expect(diff).toContain("+hello MSO");+ expect(await fs.readFile(filePath, "utf8")).toBe("prefix line\nhello MSO\nsecond line modified\nsuffix line\n");+ });- const onDisk = await fs.readFile(filePath, "utf8");- expect(onDisk).toBe(expected);+ it("10. dry_run: true writes nothing and returns written: false plus a diff", async () => {+ const original = "line one\nline two\nline three\nsuffix line\n";+ await fs.writeFile(filePath, original, "utf8");+ const res = await call(edit, { path: filePath, old_string: "line two\nline three", new_string: "line modified\nline three modified", dry_run: true });+ expect(res).toMatchObject({ kind: "success", result: { ok: true, written: false, replacements: 1, diffTruncated: false } });+ const diff = (res as { result: { diff: string } }).result.diff;+ expect(diff).toContain("-line two");+ expect(diff).toContain("+line modified");+ expect(await fs.readFile(filePath, "utf8")).toBe(original);});- it("8. a path outside the write roots is refused (whatever refusal the existing guard produces)", async () => {- const outsidePath = "/etc/hosts";- const res = await call(edit, { path: outsidePath, old_string: "localhost", new_string: "remotehost" });- expect(res).toMatchObject({- kind: "error",- message: expect.stringMatching(/outside writable roots|outside readable roots/i),- });+ it("11. dry_run: true with a stale expected_sha256 fails and leaves file untouched", async () => {+ const original = "original text\n";+ await fs.writeFile(filePath, original, "utf8");+ const res = await call(edit, { path: filePath, old_string: "original", new_string: "modified", expected_sha256: "0".repeat(64), dry_run: true });+ expect(res).toMatchObject({ kind: "error", message: expect.stringMatching(/File changed since fs_read/i) });+ expect(await fs.readFile(filePath, "utf8")).toBe(original);+ });++ it("12. dry_run: true on duplicate match fails with same message as real edit", async () => {+ const original = "dup test dup\n";+ await fs.writeFile(filePath, original, "utf8");+ const realRes = await call(edit, { path: filePath, old_string: "dup", new_string: "rep" });+ const dryRes = await call(edit, { path: filePath, old_string: "dup", new_string: "rep", dry_run: true });+ expect(dryRes).toMatchObject({ kind: "error", message: (realRes as { message: string }).message });+ expect(await fs.readFile(filePath, "utf8")).toBe(original);+ });++ it("13. dry_run then the same call for real on same content produces identical sha256", async () => {+ const original = "alpha beta gamma\n";+ await fs.writeFile(filePath, original, "utf8");+ const dryRes = await call(edit, { path: filePath, old_string: "beta", new_string: "delta", dry_run: true });+ expect(dryRes).toMatchObject({ kind: "success" });+ const drySha = (dryRes as { result: { sha256: string } }).result.sha256;+ const realRes = await call(edit, { path: filePath, old_string: "beta", new_string: "delta" });+ expect(realRes).toMatchObject({ kind: "success" });+ const realSha = (realRes as { result: { sha256: string } }).result.sha256;+ expect(drySha).toBe(realSha);+ expect(sha256Text(await fs.readFile(filePath, "utf8"))).toBe(drySha);+ });++ it("14. diffTruncated is true when changed block causes diff to exceed 40 lines", async () => {+ const beforeLines = Array.from({ length: 50 }, (_, i) => `old line ${i + 1}`).join("\n");+ const afterLines = Array.from({ length: 50 }, (_, i) => `new line ${i + 1}`).join("\n");+ await fs.writeFile(filePath, beforeLines, "utf8");+ const res = await call(edit, { path: filePath, old_string: beforeLines, new_string: afterLines });+ expect(res).toMatchObject({ kind: "success", result: { ok: true, diffTruncated: true } });+ expect((res as { result: { diff: string } }).result.diff).toContain("more lines");});});diff --git a/lib/mcp/tools-edit.ts b/lib/mcp/tools-edit.tsindex b28adec4..71dea3ea 100644--- a/lib/mcp/tools-edit.ts+++ b/lib/mcp/tools-edit.ts@@ -12,7 +12,7 @@ export const EDIT_TOOLS: McpTool[] = [name: "fs_edit",limit: { key: "fs.edit", max: 120, windowMs: 60_000 },audit: { action: "fs.write" as const, targetArg: "path" },- description: "Edit a file by replacing exact old_string occurrences with new_string. Fails on zero matches or on multiple matches unless replace_all is true. Read first, pass its SHA-256 as expected_sha256 to refuse stale edits. Bounded to OS_FS_WRITE_ROOTS.",+ description: "Edit a file by replacing exact old_string occurrences with new_string. Always returns a diff; dry_run previews without writing. Fails on zero matches or on multiple matches unless replace_all is true. Read first, pass its SHA-256 as expected_sha256 to refuse stale edits. Bounded to OS_FS_WRITE_ROOTS.",scope: "write",annotations: { idempotentHint: true },actionContract: { phase: "mutate", target: "filesystem-text", sourceOfTruth: "live", discover: ["fs_read"], validators: ["path-policy", "sha256-cas"], verify: ["fs_read"], confirmation: "contextual", concurrency: "hash", presentation: "structured" },@@ -22,6 +22,7 @@ export const EDIT_TOOLS: McpTool[] = [new_string: { type: "string", description: "Replacement text." },replace_all: { type: "boolean", description: "Replace all occurrences when true. Default false requires exactly one match." },expected_sha256: { type: "string", description: "Optional SHA-256 returned by fs_read; refuse if the current file no longer matches." },+ dry_run: { type: "boolean", description: "Preview only: run every check and return the diff and projected sha256 without writing." },}, ["path", "old_string", "new_string"]),run: async (a, context) => {const target = str(a, "path");@@ -33,6 +34,7 @@ export const EDIT_TOOLS: McpTool[] = [newString: typeof a.new_string === "string" ? a.new_string : "",replaceAll: a.replace_all === true,expectedSha256: opt(a, "expected_sha256"),+ dryRun: a.dry_run === true,});},},diff --git a/scripts/mso-agent-edit-diff.mjs b/scripts/mso-agent-edit-diff.mjsnew file mode 100644index 00000000..aabf894c--- /dev/null+++ b/scripts/mso-agent-edit-diff.mjs@@ -0,0 +1,127 @@+import { colorizeDiffLine, diffLineCap } from "./mso-agent-diff.mjs";++/**+ * Parse fs_edit result JSON string or object.+ * Returns the parsed object if valid and contains a diff string, else null.+ * Never throws.+ */+export function parseEditResult(result) {+ if (result == null) return null;+ let parsed = result;+ if (typeof result === "string") {+ try {+ parsed = JSON.parse(result);+ } catch {+ return null;+ }+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return null;+ }+ if (typeof parsed.diff !== "string") {+ return null;+ }+ return parsed;+}++export const parseEditDiff = parseEditResult;++function colorizeLine(line, colors = {}) {+ if (!colors) return line;+ const colored = colorizeDiffLine(line, colors);+ if (colored === line && colors.dim) {+ return `${colors.dim}${line}${colors.reset || ""}`;+ }+ return colored;+}++/**+ * @typedef {Object} EditDiffPalette+ * @property {string} [dim]+ * @property {string} [reset]+ * @property {string} [c]+ * @property {string} [cyan]+ * @property {string} [err]+ * @property {string} [blue]+ */++/**+ * @typedef {Object} FormatEditDiffOptions+ * @property {EditDiffPalette} [colors]+ * @property {number} [cap]+ */++/**+ * Format the diff returned by fs_edit into an indented, colored block.+ * Returns empty string when diff is empty or invalid.+ * @param {any} parsed+ * @param {FormatEditDiffOptions} [options]+ * @returns {string}+ */+export function formatEditDiff(parsed, { colors = {}, cap } = {}) {+ if (!parsed || typeof parsed.diff !== "string") return "";+ const raw = parsed.diff.replace(/\r/g, "");+ const trimmed = raw.endsWith("\n") ? raw.slice(0, -1) : raw;+ const diffLines = trimmed ? trimmed.split("\n") : [];+ if (!diffLines.length || (diffLines.length === 1 && !diffLines[0])) return "";++ const effectiveCap = Number.isInteger(cap) ? cap : diffLineCap();+ const isTruncated = diffLines.length > effectiveCap;+ const targetLines = isTruncated ? diffLines.slice(0, effectiveCap) : diffLines;++ const rawPath = typeof parsed.path === "string" ? parsed.path.trim() : "";+ const baseName = (rawPath ? rawPath.split(/[/\\]/).filter(Boolean).pop() : null) || "file";++ const label = parsed.written === false+ ? `edit ${baseName} (preview, not written)`+ : `edit ${baseName}`;++ const indent = " ";+ const lines = [+ `${indent}${label}`,+ ...targetLines.map((line) => `${indent}${colorizeLine(line, colors)}`),+ ];++ if (isTruncated) {+ const withheld = diffLines.length - effectiveCap;+ const withheldText = `… ${withheld} more lines`;+ const dimmed = colors?.dim ? `${colors.dim}${withheldText}${colors.reset || ""}` : withheldText;+ lines.push(`${indent}${dimmed}`);+ }++ if (parsed.diffTruncated) {+ const cutText = "… diff truncated by server";+ const dimmed = colors?.dim ? `${colors.dim}${cutText}${colors.reset || ""}` : cutText;+ lines.push(`${indent}${dimmed}`);+ }++ return lines.join("\n");+}++/**+ * @typedef {Object} PrintEditDiffOptions+ * @property {EditDiffPalette} [colors]+ * @property {number} [cap]+ * @property {(text: string) => void} [print]+ * @property {{ live?: boolean, clear?: () => void }} [activity]+ */++/**+ * Write the formatted edit diff through print (default console.log).+ * Returns true if something was printed, false otherwise.+ * @param {any} parsed+ * @param {PrintEditDiffOptions} [options]+ * @returns {boolean}+ */+export function printEditDiff(parsed, { colors, cap, print = console.log, activity } = {}) {+ const formatted = formatEditDiff(parsed, { colors, cap });+ if (!formatted) return false;+ if (activity?.live) {+ activity.clear();+ const tone = colors?.c || colors?.cyan || "";+ const reset = colors?.reset || "";+ print(`${tone} ✓ fs_edit${reset}`);+ }+ print(formatted);+ return true;+}diff --git a/scripts/mso-agent-edit-diff.test.ts b/scripts/mso-agent-edit-diff.test.tsnew file mode 100644index 00000000..a35f919a--- /dev/null+++ b/scripts/mso-agent-edit-diff.test.ts@@ -0,0 +1,200 @@+import { describe, expect, it, vi } from "vitest";+import { formatEditDiff, parseEditDiff, parseEditResult, printEditDiff } from "./mso-agent-edit-diff.mjs";++describe("MSO Agent edit diff preview", () => {+ it("1. a real edit result prints a label with the basename and contains the -old and +new lines", () => {+ const raw = JSON.stringify({+ ok: true,+ path: "src/utils/calculator.ts",+ written: true,+ diff: [+ "@@ -1,4 +1,4 @@",+ " context line before",+ "-old line content",+ "+new line content",+ " context line after",+ ].join("\n"),+ });++ const parsed = parseEditResult(raw);+ expect(parsed).not.toBeNull();++ const printed: string[] = [];+ const sink = (line: string) => { printed.push(line); };++ const handled = printEditDiff(parsed, { print: sink });+ expect(handled).toBe(true);+ expect(printed).toHaveLength(1);++ const output = printed[0];+ expect(output).toContain("edit calculator.ts");+ expect(output).toContain("-old line content");+ expect(output).toContain("+new line content");+ expect(output).toContain("context line before");+ expect(output).toContain("context line after");++ // Every line is prefixed with two spaces of indent+ const lines = output.split("\n");+ expect(lines.length).toBeGreaterThan(1);+ for (const line of lines) {+ expect(line.startsWith(" ")).toBe(true);+ }+ });++ it("2. a dry run (written: false) label says it was a preview", () => {+ const raw = JSON.stringify({+ ok: true,+ path: "/home/user/workspace/config.json",+ written: false,+ diff: [+ "@@ -1,2 +1,2 @@",+ "-old config",+ "+new config",+ ].join("\n"),+ });++ const parsed = parseEditResult(raw);+ expect(parsed).not.toBeNull();++ const output = formatEditDiff(parsed);+ expect(output).toContain("edit config.json (preview, not written)");+ expect(output).toMatch(/preview/);+ });++ it("3. an empty diff prints nothing and printEditDiff returns false", () => {+ const parsed = {+ path: "empty.txt",+ written: true,+ diff: "",+ };++ const print = vi.fn();+ const result = printEditDiff(parsed, { print });++ expect(result).toBe(false);+ expect(print).not.toHaveBeenCalled();+ expect(formatEditDiff(parsed)).toBe("");+ });++ it("4. an unparseable result and a JSON non-object both return null from parseEditDiff and print nothing", () => {+ expect(parseEditDiff("not json at all {")).toBeNull();+ expect(parseEditDiff("42")).toBeNull();+ expect(parseEditDiff('"just a string"')).toBeNull();+ expect(parseEditDiff("[1, 2, 3]")).toBeNull();+ expect(parseEditDiff("null")).toBeNull();+ expect(parseEditDiff(null)).toBeNull();+ expect(parseEditDiff(undefined)).toBeNull();+ expect(parseEditDiff(JSON.stringify({ path: "no-diff.ts" }))).toBeNull();++ const print = vi.fn();+ expect(printEditDiff(parseEditDiff("not json at all {"), { print })).toBe(false);+ expect(printEditDiff(parseEditDiff("42"), { print })).toBe(false);+ expect(printEditDiff(parseEditDiff(null), { print })).toBe(false);+ expect(print).not.toHaveBeenCalled();+ });++ it("5. cap is respected and the withheld count is reported", () => {+ const diffLines = [+ "@@ -1,10 +1,10 @@",+ "-line 1",+ "+line 1",+ "-line 2",+ "+line 2",+ "-line 3",+ "+line 3",+ "-line 4",+ "+line 4",+ ];+ const parsed = {+ path: "cap-test.txt",+ written: true,+ diff: diffLines.join("\n"),+ };++ const output = formatEditDiff(parsed, { cap: 3 });+ expect(output).toContain("… 6 more lines");+ expect(output).toContain("-line 1");+ expect(output).not.toContain("-line 3");+ });++ it("6. diffTruncated: true adds the server-truncation note", () => {+ const parsed = {+ path: "truncated.txt",+ written: true,+ diff: [+ "@@ -1,2 +1,2 @@",+ "-old line",+ "+new line",+ ].join("\n"),+ diffTruncated: true,+ };++ const output = formatEditDiff(parsed);+ expect(output).toContain("diff truncated by server");+ });++ it("7. colours are applied only when a palette is passed (no ANSI codes in the output when colors is empty/undefined)", () => {+ const parsed = {+ path: "colors-test.txt",+ written: true,+ diff: [+ "@@ -1,3 +1,3 @@",+ " context line",+ "-old line",+ "+new line",+ ].join("\n"),+ };++ const noPalette = formatEditDiff(parsed);+ expect(noPalette).not.toContain("\x1b[");++ const emptyPalette = formatEditDiff(parsed, { colors: {} });+ expect(emptyPalette).not.toContain("\x1b[");++ const monoPalette = formatEditDiff(parsed, {+ colors: { blue: "", cyan: "", err: "", dim: "", reset: "" },+ });+ expect(monoPalette).not.toContain("\x1b[");++ const fullPalette = {+ blue: "\x1b[34m",+ cyan: "\x1b[36m",+ err: "\x1b[31m",+ dim: "\x1b[2m",+ reset: "\x1b[0m",+ };+ const colored = formatEditDiff(parsed, { colors: fullPalette });+ expect(colored).toContain("\x1b[34m@@ -1,3 +1,3 @@\x1b[0m");+ expect(colored).toContain("\x1b[31m-old line\x1b[0m");+ expect(colored).toContain("\x1b[36m+new line\x1b[0m");+ expect(colored).toContain("\x1b[2m context line\x1b[0m");+ });++ it("clears live activity and prints checkmark before diff in live mode", () => {+ const parsed = {+ path: "live.ts",+ written: true,+ diff: [+ "@@ -1,2 +1,2 @@",+ "-a",+ "+b",+ ].join("\n"),+ };+ const printed: string[] = [];+ const cleared: string[] = [];+ const mockActivity = {+ live: true,+ clear: () => { cleared.push("cleared"); },+ };+ const colors = { c: "\x1b[36m", reset: "\x1b[0m" };+ const handled = printEditDiff(parsed, {+ colors,+ print: (line: string) => { printed.push(line); },+ activity: mockActivity as any,+ });+ expect(handled).toBe(true);+ expect(cleared).toHaveLength(1);+ expect(printed[0]).toContain("✓ fs_edit");+ expect(printed[1]).toContain("edit live.ts");+ });+});diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjsindex a555b294..cf94d09b 100644--- a/scripts/mso-agent-turn.mjs+++ b/scripts/mso-agent-turn.mjs@@ -14,6 +14,7 @@ import { persistSession } from "./mso-agent-session-ui.mjs";import { addUsage } from "./mso-agent-status.mjs";import { oneShotApproves } from "./mso-agent-oneshot.mjs";import { reasoningLine } from "./mso-agent-reasoning.mjs";+import { parseEditResult, printEditDiff } from "./mso-agent-edit-diff.mjs";function lazyAssistantOutput(session, options = {}) {if (options.quiet) return null;@@ -90,6 +91,7 @@ export async function executeTool(rl, tool, call, agentSession, permission = "asif (!options.quiet) {if (options.activity) options.activity.toolEnd(tool, true);else process.stdout.write(`\r${C.c} ✓ ${tool.name}${C.reset}\n`);+ if (tool.name === "fs_edit") printEditDiff(parseEditResult(out.result), { colors: C, activity: options.activity });}if (!out.ok) return { ok: false, result: out.result || "tool failed" };return { ok: true, result: String(out.result ?? "ok") };