Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(core): follow symlinks in edit_file and write_file (#414)

Myriad-Dreaminc984e794b75d
diff --git a/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.md b/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.md
new file mode 100644
index 00000000..413f8b67
--- /dev/null
+++ b/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.md
@@ -0,0 +1,32 @@
+# edit_file and write_file follow a symlink instead of replacing it
+
+- **Date:** 2026-08-23
+- **Type:** fix
+- **Scope:** `core`, `docs`
+- **PR:** [#414](https://github.com/Prism-Shadow/penguin-harness/pull/414)
+
+[中文版](2026-08-23-file-tools-follow-symlinks.zh.md)
+
+Editing or writing a symlinked path replaced the link with a regular file and left the
+file it pointed at untouched — while reporting success, complete with a diff of a change
+that never reached the real file. `stat` and `readFile` dereference, so the tools read the
+target's content and permission bits correctly; only the final `rename` of the atomic
+write acted on the link itself. Both tools now resolve the link chain first and write to
+the file at its end, so the link survives and the content lands where it points.
+
+## Details
+
+- `resolveWriteTarget` walks the chain with `readlink` (bounded at 40 hops, the kernel's
+ own `ELOOP` budget) and returns the first path that is not a readable link. A cycle
+ fails with "Too many levels of symbolic links" instead of hanging.
+- Resolution is leaf-only rather than a `realpath`: a link whose target does not exist yet
+ still resolves, so `write_file` creates that file — and its parent directory — the way a
+ shell redirect through a dangling link would. Directory symlinks along the path are left
+ alone; the temp file only needs to share a directory with the final name for the rename
+ to stay atomic.
+- The temp file is now created beside the resolved target, keeping the rename within one
+ filesystem when the link crosses mount points.
+- Preserving the overwritten file's permission bits becomes meaningful with this: the bits
+ come from the dereferenced `stat`, and are now restored onto that same inode.
+- A chain that leaves the Workspace is followed like any other path — these tools already
+ accept absolute paths anywhere, on the same footing as the shell tool.
diff --git a/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.zh.md b/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.zh.md
new file mode 100644
index 00000000..2b7b0414
--- /dev/null
+++ b/changelog/unreleased/2026-08-23-file-tools-follow-symlinks.zh.md
@@ -0,0 +1,26 @@
+# edit_file 与 write_file 沿软链接写入,而不是替换掉链接
+
+- **Date:** 2026-08-23
+- **Type:** fix
+- **Scope:** `core`, `docs`
+- **PR:** [#414](https://github.com/Prism-Shadow/penguin-harness/pull/414)
+
+[English](2026-08-23-file-tools-follow-symlinks.md)
+
+编辑或写入一个软链接路径时,链接会被替换成普通文件,而它指向的文件原封不动——工具却报告成功,
+还附上了一份从未落到真实文件上的 diff。`stat` 和 `readFile` 本身就会解引用,因此两个工具读到的
+内容和权限位都是目标文件的;唯独原子写最后那一步 `rename` 作用在链接自身上。现在两者都会先解析
+整条链接链、写入链尾的文件,链接得以保留,内容也落在它指向的地方。
+
+## 细节
+
+- `resolveWriteTarget` 用 `readlink` 逐跳解析(上限 40 跳,与内核自身的 `ELOOP` 预算一致),
+ 返回第一个不是可读链接的路径。成环时报 "Too many levels of symbolic links" 而不是卡住。
+- 解析只针对末段,而非走 `realpath`:目标尚不存在的链接同样能解析出来,`write_file` 会像 Shell
+ 重定向穿过悬空链接那样创建该文件及其父目录。路径中间的目录软链接不做处理——临时文件只需要与
+ 最终文件名同处一个目录,rename 就仍是原子的。
+- 临时文件现在创建在解析后的目标旁边,链接跨越挂载点时 rename 也不会跨文件系统。
+- 保留被覆盖文件权限位的行为至此才真正成立:这些位取自解引用后的 `stat`,现在被还原到同一个
+ inode 上。
+- 指向 Workspace 之外的链接与其他路径一视同仁地跟随——这两个工具本就接受任意绝对路径,与
+ Shell 工具同等对待。
diff --git a/packages/core/src/environment/tools/edit-file.ts b/packages/core/src/environment/tools/edit-file.ts
index 81c74144..cb8ddeeb 100644
--- a/packages/core/src/environment/tools/edit-file.ts
+++ b/packages/core/src/environment/tools/edit-file.ts
@@ -9,9 +9,10 @@
* per replacement site, nearby sites merged; capped for replace_all storms), so both the
* model and the user can verify exactly what changed without re-reading the file. The
* write is atomic (temp file + rename, preserving the original permission bits), so a
- * crash mid-write cannot leave the file half-edited. Relative paths resolve against the
- * Workspace; absolute paths are allowed (tools run with the user's full permissions, same
- * as the shell tool).
+ * crash mid-write cannot leave the file half-edited; a symlinked path is followed to the
+ * file it names, the same way the read that produced the diff was. Relative paths resolve
+ * against the Workspace; absolute paths are allowed (tools run with the user's full
+ * permissions, same as the shell tool).
*
* Division of responsibility with Environment (see environment.ts): non-streaming — yields
* one final text delta; failures are explanatory text finalized as `failed`; anything
diff --git a/packages/core/src/environment/tools/file-utils.ts b/packages/core/src/environment/tools/file-utils.ts
index 00341197..a38b34f7 100644
--- a/packages/core/src/environment/tools/file-utils.ts
+++ b/packages/core/src/environment/tools/file-utils.ts
@@ -2,22 +2,67 @@
* Shared helpers for the file tools (edit_file / write_file).
*/
import path from "node:path";
-import { rename, rm, writeFile } from "node:fs/promises";
+import { readlink, rename, rm, writeFile } from "node:fs/promises";
+
+/**
+ * Cap on symlink hops when resolving a write target, matching the kernel's own `ELOOP`
+ * budget (Linux allows 40): a link cycle has to end as an error rather than a hang.
+ */
+const MAX_SYMLINK_HOPS = 40;
+
+/**
+ * The path a write aimed at `target` must actually land on: the end of its symlink chain.
+ *
+ * Every other step of the file tools already goes through the link — `stat` reads the
+ * target's size and permission bits, `readFile` reads the target's bytes — because those
+ * calls dereference. The write is the one step that would not: an atomic write finishes
+ * with `rename`, which operates on the link itself and would replace it with a regular
+ * file, leaving the file the model set out to edit untouched while the tool reports
+ * success. Following the chain here is also what makes `mode` meaningful: the bits come
+ * from the dereferenced `stat`, so they have to be restored onto the same inode.
+ *
+ * Resolution is leaf-only and deliberate: `realpath` is not used, so a link whose target
+ * does not exist yet (a dangling link, which `>` also creates through) still resolves, and
+ * directory symlinks along the way are left alone — the temp file only needs to share a
+ * directory with the final name for `rename` to stay atomic. A chain leaving the Workspace
+ * is followed like any other: these tools already accept absolute paths anywhere, on the
+ * same footing as the shell tool.
+ *
+ * Anything that is not a readable symlink ends the walk and is returned as-is: `EINVAL`
+ * (an ordinary file — the common case, one syscall), `ENOENT` (nothing there yet, so the
+ * caller creates it), or a permission error the caller's own write reports properly.
+ */
+export async function resolveWriteTarget(target: string): Promise<string> {
+ let current = target;
+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop += 1) {
+ let link: string;
+ try {
+ link = await readlink(current);
+ } catch {
+ return current;
+ }
+ current = path.resolve(path.dirname(current), link);
+ }
+ throw new Error(`Too many levels of symbolic links: "${target}"`);
+}
/**
* Atomic file write: writes to a temp file in the target's directory, then renames it over
* the target — a crash or full disk mid-write can no longer leave the target half-written.
- * `mode` preserves an existing file's permission bits (rename replaces the inode, which
- * would otherwise reset them); the temp file is removed on failure (best effort).
+ * A symlinked target is followed first (see `resolveWriteTarget`), so the write lands on
+ * the file it names instead of replacing the link. `mode` preserves an existing file's
+ * permission bits (rename replaces the inode, which would otherwise reset them); the temp
+ * file is removed on failure (best effort).
*/
export async function atomicWriteFile(
target: string,
content: string,
opts: { mode?: number; signal?: AbortSignal } = {},
): Promise<void> {
+ const resolved = await resolveWriteTarget(target);
const tmp = path.join(
- path.dirname(target),
- `.${path.basename(target)}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
+ path.dirname(resolved),
+ `.${path.basename(resolved)}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
);
try {
await writeFile(tmp, content, {
@@ -25,7 +70,7 @@ export async function atomicWriteFile(
...(opts.mode !== undefined ? { mode: opts.mode } : {}),
...(opts.signal ? { signal: opts.signal } : {}),
});
- await rename(tmp, target);
+ await rename(tmp, resolved);
} catch (err) {
await rm(tmp, { force: true }).catch(() => undefined);
throw err;
diff --git a/packages/core/src/environment/tools/write-file.ts b/packages/core/src/environment/tools/write-file.ts
index 2592f635..babb92ff 100644
--- a/packages/core/src/environment/tools/write-file.ts
+++ b/packages/core/src/environment/tools/write-file.ts
@@ -9,8 +9,10 @@
* one-line `+X/−Y lines` summary otherwise (created files carry no diff — the model just
* supplied the content). The write is atomic (temp file + rename, preserving an
* overwritten file's permission bits), so a crash mid-write cannot leave the target
- * half-written. Relative paths resolve against the Workspace; absolute
- * paths are allowed (tools run with the user's full permissions, same as the shell tool).
+ * half-written; a symlinked path is followed to the file it names, so the link survives
+ * and the content lands where it points. Relative paths resolve against the Workspace;
+ * absolute paths are allowed (tools run with the user's full permissions, same as the
+ * shell tool).
* For surgical changes to an existing file, edit_file is the better tool — this one
* replaces the whole content.
*
@@ -23,7 +25,7 @@
*/
import path from "node:path";
import { mkdir, readFile, stat } from "node:fs/promises";
-import { atomicWriteFile } from "./file-utils.js";
+import { atomicWriteFile, resolveWriteTarget } from "./file-utils.js";
import { buildLineDiffHunks, renderHunk } from "./diff.js";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
@@ -109,7 +111,10 @@ export function createWriteFileTool(definition: ToolDefinitionConfig): BuiltinTo
if (signal?.aborted) return { stopReason: "aborted" };
try {
- await mkdir(path.dirname(resolved), { recursive: true });
+ // The parent to create is the one holding the file that will actually be written:
+ // through a symlink that is the target's directory, not the link's (a link pointing
+ // into a directory that does not exist yet is created the way `>` would).
+ await mkdir(path.dirname(await resolveWriteTarget(resolved)), { recursive: true });
await atomicWriteFile(resolved, content, {
...(fileMode !== undefined ? { mode: fileMode } : {}),
...(signal ? { signal } : {}),
diff --git a/packages/core/test/file-tools.test.ts b/packages/core/test/file-tools.test.ts
index 9ffaad3b..8baa0bb3 100644
--- a/packages/core/test/file-tools.test.ts
+++ b/packages/core/test/file-tools.test.ts
@@ -8,6 +8,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
chmod,
+ lstat,
mkdir,
mkdtemp,
readdir,
@@ -724,3 +725,104 @@ describe("write_file — overwrite diffs", () => {
expect(text).not.toContain("@@");
});
});
+
+describe("edit_file / write_file — symlinked targets", () => {
+ const edit = () => createEditFileTool(def(EDIT_FILE_NAME, "rw"));
+ const write = () => createWriteFileTool(def(WRITE_FILE_NAME, "rw"));
+
+ it("edit_file writes through the link and leaves the link in place", async () => {
+ await writeFile(path.join(tmp, "real.md"), "hello\nworld\n");
+ await symlink("real.md", path.join(tmp, "link.md"));
+ const { result } = await run(
+ edit(),
+ { file_path: "link.md", old_string: "world", new_string: "there" },
+ tmp,
+ );
+ expect(result?.stopReason).toBeUndefined();
+ // The edit landed on the file the link names — not on a regular file that replaced it.
+ expect(await readFile(path.join(tmp, "real.md"), "utf8")).toBe("hello\nthere\n");
+ expect((await lstat(path.join(tmp, "link.md"))).isSymbolicLink()).toBe(true);
+ });
+
+ it("write_file overwrites through the link and leaves the link in place", async () => {
+ await writeFile(path.join(tmp, "real.txt"), "old\n");
+ await symlink("real.txt", path.join(tmp, "alias.txt"));
+ const { result, text } = await run(write(), { file_path: "alias.txt", content: "new\n" }, tmp);
+ expect(result?.stopReason).toBeUndefined();
+ expect(text).toContain('Overwrote "alias.txt"');
+ expect(await readFile(path.join(tmp, "real.txt"), "utf8")).toBe("new\n");
+ expect((await lstat(path.join(tmp, "alias.txt"))).isSymbolicLink()).toBe(true);
+ });
+
+ it("follows a chain of links to the file at its end", async () => {
+ await writeFile(path.join(tmp, "end.txt"), "start\n");
+ await symlink("end.txt", path.join(tmp, "middle.txt"));
+ await symlink("middle.txt", path.join(tmp, "head.txt"));
+ const { result } = await run(write(), { file_path: "head.txt", content: "done\n" }, tmp);
+ expect(result?.stopReason).toBeUndefined();
+ expect(await readFile(path.join(tmp, "end.txt"), "utf8")).toBe("done\n");
+ expect((await lstat(path.join(tmp, "middle.txt"))).isSymbolicLink()).toBe(true);
+ expect((await lstat(path.join(tmp, "head.txt"))).isSymbolicLink()).toBe(true);
+ });
+
+ it("resolves a link that crosses directories", async () => {
+ await mkdir(path.join(tmp, "data"), { recursive: true });
+ await writeFile(path.join(tmp, "data", "target.txt"), "before\n");
+ await symlink(path.join("data", "target.txt"), path.join(tmp, "shortcut.txt"));
+ const { result } = await run(write(), { file_path: "shortcut.txt", content: "after\n" }, tmp);
+ expect(result?.stopReason).toBeUndefined();
+ expect(await readFile(path.join(tmp, "data", "target.txt"), "utf8")).toBe("after\n");
+ expect((await lstat(path.join(tmp, "shortcut.txt"))).isSymbolicLink()).toBe(true);
+ });
+
+ it("write_file creates the file a dangling link names, including its parent", async () => {
+ await symlink(path.join("missing", "created.txt"), path.join(tmp, "dangling.txt"));
+ const { result, text } = await run(
+ write(),
+ { file_path: "dangling.txt", content: "made\n" },
+ tmp,
+ );
+ expect(result?.stopReason).toBeUndefined();
+ // Nothing was there to overwrite, so it reads as a creation.
+ expect(text).toContain('Created "dangling.txt"');
+ expect(await readFile(path.join(tmp, "missing", "created.txt"), "utf8")).toBe("made\n");
+ expect((await lstat(path.join(tmp, "dangling.txt"))).isSymbolicLink()).toBe(true);
+ });
+
+ // POSIX-only: Windows has no owner-only mode bits to preserve (chmod maps to the read-only attribute).
+ it.skipIf(process.platform === "win32")(
+ "preserves the permission bits of the file at the end of the link",
+ async () => {
+ const real = path.join(tmp, "moded.txt");
+ await writeFile(real, "old\n");
+ await chmod(real, 0o600);
+ await symlink("moded.txt", path.join(tmp, "moded-link.txt"));
+ const { result } = await run(write(), { file_path: "moded-link.txt", content: "new\n" }, tmp);
+ expect(result?.stopReason).toBeUndefined();
+ expect(await readFile(real, "utf8")).toBe("new\n");
+ expect((await stat(real)).mode & 0o777).toBe(0o600);
+ },
+ );
+
+ it("fails cleanly on a link cycle instead of hanging", async () => {
+ await symlink("b.txt", path.join(tmp, "a.txt"));
+ await symlink("a.txt", path.join(tmp, "b.txt"));
+ const { result, text } = await run(write(), { file_path: "a.txt", content: "x\n" }, tmp);
+ expect(result?.stopReason).toBe("failed");
+ expect(text).toContain("Too many levels of symbolic links");
+ });
+
+ it("leaves no temp file behind next to the resolved target", async () => {
+ await mkdir(path.join(tmp, "nested"), { recursive: true });
+ await writeFile(path.join(tmp, "nested", "t.txt"), "a\n");
+ await symlink(path.join("nested", "t.txt"), path.join(tmp, "l.txt"));
+ await run(write(), { file_path: "l.txt", content: "b\n" }, tmp);
+ // The temp file is created beside the RESOLVED target, so the nested directory is the
+ // one that has to come out clean.
+ expect(await readFile(path.join(tmp, "nested", "t.txt"), "utf8")).toBe("b\n");
+ expect((await readdir(path.join(tmp, "nested"))).filter((e) => e.includes(".tmp-"))).toEqual(
+ [],
+ );
+ expect((await readdir(tmp)).filter((e) => e.includes(".tmp-"))).toEqual([]);
+ });
+});
diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.md
index 3a1ec0e0..6526e648 100644
--- a/packages/docs/content/tools.en.md
+++ b/packages/docs/content/tools.en.md
@@ -142,7 +142,7 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
### File tools
-`read_file` / `edit_file` / `write_file` run with the user's full permissions, same as the shell tool; relative paths resolve against the Workspace and absolute paths are allowed. They are non-streaming (a single final output) and never throw — failures come back as explanatory text with `stop_reason: failed`.
+`read_file` / `edit_file` / `write_file` run with the user's full permissions, same as the shell tool; relative paths resolve against the Workspace and absolute paths are allowed. A symlinked path is followed to the file it names — reads, edits and writes all land on that file, and the link stays a link. They are non-streaming (a single final output) and never throw — failures come back as explanatory text with `stop_reason: failed`.
```ts
// read_file — cat -n style output (line number, tab, content); overlong single lines are
diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.md
index 8775cb32..29501d2e 100644
--- a/packages/docs/content/tools.zh.md
+++ b/packages/docs/content/tools.zh.md
@@ -141,7 +141,7 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window
### 文件工具
-`read_file` / `edit_file` / `write_file` 与 Shell 工具一样以用户完整权限运行:相对路径按 Workspace 解析,也接受绝对路径。三者均为非流式(一次性输出最终结果),从不抛异常——失败以解释性文本收尾,`stop_reason` 为 `failed`。
+`read_file` / `edit_file` / `write_file` 与 Shell 工具一样以用户完整权限运行:相对路径按 Workspace 解析,也接受绝对路径。软链接路径会被解析到它指向的文件——读取、编辑、写入都落在该文件上,链接本身仍然是链接。三者均为非流式(一次性输出最终结果),从不抛异常——失败以解释性文本收尾,`stop_reason` 为 `failed`。
```ts
// read_file — cat -n 风格输出(行号、制表符、内容);超长单行会被截断,