Skip to content

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

feat: write files atomically (#423)

Myriad-Dreamin1e5754f62508
diff --git a/changelog/unreleased/2026-08-23-atomic-state-writes.md b/changelog/unreleased/2026-08-23-atomic-state-writes.md
new file mode 100644
index 00000000..0c019162
--- /dev/null
+++ b/changelog/unreleased/2026-08-23-atomic-state-writes.md
@@ -0,0 +1,42 @@
+# Every Harness state file is replaced atomically
+
+- **Date:** 2026-08-23
+- **Type:** fix
+- **Scope:** `core`, `server`, `cli`, `desktop`
+- **PR:** [#423](https://github.com/Prism-Shadow/penguin-harness/pull/423)
+
+[中文版](2026-08-23-atomic-state-writes.zh.md)
+
+The files the Harness keeps on disk — `system_config.yaml`, `.project_config.toml`, `.vault.toml`,
+`AGENTS.md`, `MEMORY.md`, schedule files, `GOAL.yaml` — were each overwritten in place, so a crash
+or a full disk part-way through a write left the file truncated. A truncated `system_config.yaml`
+is not always a loud failure: when the cut lands inside the `system_prompt` block scalar the file
+still parses as YAML and the Agent boots with everything after it — the tool list, MCP servers,
+vault and skills settings — silently gone, and the next config edit from the web UI persists that
+as the new truth. `atomicWriteFile`, until now a private helper of the `write_file` and `edit_file`
+tools, moved to core's public surface and is now the single writer behind all of them: content
+goes to a temp file in the same directory, is flushed, and is renamed over the target, so a reader
+sees either the old bytes or the new ones.
+
+## Details
+
+- The secret-carrying files (`.project_config.toml`, `.vault.toml`) get their `0600` mode from an explicit `chmod` on the temp file, which the umask does not mask, so the mode is exact on creation and on every replacement.
+- A config file symlinked into a dotfiles repository is still written through, and so is the shell startup file `penguin lang` edits. The Memory directory is the exception and stays as it was: it is model-writable, so a symlink planted at a topic name is replaced rather than followed out of the scope.
+- The Memory index prune, which deletes a topic's lines from `MEMORY.md`, now goes through the same writer as every other Memory write instead of overwriting the index in place.
+- The desktop app's `~/.local/bin/penguin` wrapper is renamed into place, so a failed write leaves the previous command on PATH rather than a truncated script.
+
+## Skills
+
+Installing a Skill — from the library or from an imported zip — writes into a dot-prefixed staging
+directory and swaps it in as the last step. The old directory was previously deleted first and the
+new files written into place one by one, and since the only completeness criterion is that
+`<name>/SKILL.md` exists, an install interrupted at the wrong moment left a partial Skill that
+looked installed. Both Skill listings skip dot-prefixed directories, which a Skill name can never
+be.
+
+## Hot update
+
+An artifact already holding the exact bytes being pushed is left untouched, and anything else is
+renamed into place. Re-pushing a version, or rolling back to one installed earlier, rewrote the
+content-addressed file the committed manifest was pointing at; a crash during that rewrite left a
+manifest referencing a truncated bundle, which the runtime needs to boot.
diff --git a/changelog/unreleased/2026-08-23-atomic-state-writes.zh.md b/changelog/unreleased/2026-08-23-atomic-state-writes.zh.md
new file mode 100644
index 00000000..dc7465ec
--- /dev/null
+++ b/changelog/unreleased/2026-08-23-atomic-state-writes.zh.md
@@ -0,0 +1,36 @@
+# Harness 的状态文件一律原子替换
+
+- **Date:** 2026-08-23
+- **Type:** fix
+- **Scope:** `core`, `server`, `cli`, `desktop`
+- **PR:** [#423](https://github.com/Prism-Shadow/penguin-harness/pull/423)
+
+[English](2026-08-23-atomic-state-writes.md)
+
+Harness 落在磁盘上的那些文件——`system_config.yaml`、`.project_config.toml`、`.vault.toml`、
+`AGENTS.md`、`MEMORY.md`、定时任务文件、`GOAL.yaml`——此前都是就地覆盖写,写到一半遇上崩溃或磁盘写满,
+留下的就是一个被截断的文件。而被截断的 `system_config.yaml` 未必会响亮地失败:截断点落在
+`system_prompt` 块标量内部时,文件仍是合法 YAML,Agent 照常启动,但它后面的工具列表、MCP 服务器、
+vault 与 skills 设置已经悄悄消失,用户下一次在 Web 上改配置,又把这份残缺文档当成新的事实持久化下去。
+`atomicWriteFile` 原本只是 `write_file` / `edit_file` 两个工具的私有 helper,现在移到 core 的公开出口,
+成为这些文件唯一的写入口:内容先写进同目录下的临时文件,flush 之后再 rename 覆盖目标,读者看到的要么是
+旧字节,要么是新字节。
+
+## 细节
+
+- 存有密钥的文件(`.project_config.toml`、`.vault.toml`)的 `0600` 权限位改由临时文件上的显式 `chmod` 施加,不受 umask 影响,因此无论新建还是替换,权限都准确落到 0600。
+- 被软链接进 dotfiles 仓库的配置文件仍然会被写穿,`penguin lang` 改写的 shell 启动文件同样如此。Memory 目录是例外,维持原样:那里模型可写,落在主题文件名上的软链接会被替换,而不是被跟随出这个 scope。
+- Memory 索引裁剪(从 `MEMORY.md` 中删掉某个主题的行)不再就地覆盖索引,而是走与其他 Memory 写入相同的写入口。
+- 桌面端的 `~/.local/bin/penguin` wrapper 改为 rename 就位,写失败时留在 PATH 上的是原来那个命令,而不是一个被截断的脚本。
+
+## Skills
+
+安装 Skill——无论来自内置库还是导入的 zip——都先写进一个点号开头的暂存目录,最后一步整体换入。此前是先删掉旧目录、
+再逐个写入新文件,而判定"已安装"的唯一标准就是 `<name>/SKILL.md` 存在,于是在错误的时刻中断,会留下一个
+看起来装好了的残缺 Skill。两处 Skill 列举都会跳过点号开头的目录——Skill 名字不可能是这种形式。
+
+## 热更新
+
+推送的字节与磁盘上已有文件完全一致时不再重写,其余情况一律 rename 就位。重复推送同一版本、或回滚到之前装过的
+版本时,写的正是当前 manifest 已经指向的那个内容寻址文件;这次重写中途崩溃,留下的就是一个指向被截断 bundle 的
+完好 manifest,而运行时正要用它启动。
diff --git a/packages/cli/src/lang-config.ts b/packages/cli/src/lang-config.ts
index 6c156d26..d084a388 100644
--- a/packages/cli/src/lang-config.ts
+++ b/packages/cli/src/lang-config.ts
@@ -9,8 +9,9 @@
* terminals will read the variable from the startup file, so it persists.
*/
import { spawn } from "node:child_process";
-import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
+import { atomicWriteFile } from "@prismshadow/penguin-core";
import type { Language } from "./i18n.js";
const BEGIN = "# >>> PenguinHarness PENGUIN_LANG >>>";
@@ -86,7 +87,9 @@ export async function applyLanguageToRc(
} catch {
/* File doesn't exist yet; treat as empty content */
}
- await writeFile(rc.rcPath, upsertBlock(content, rc.body(lang)), "utf8");
+ // The rc file is the user's, and often a symlink into a dotfiles repository: write through
+ // the link, and replace it atomically so a failed write cannot truncate their shell startup.
+ await atomicWriteFile(rc.rcPath, upsertBlock(content, rc.body(lang)), { followSymlinks: true });
return { rcPath: rc.rcPath, kind: rc.kind };
}
diff --git a/packages/core/src/environment/tools/edit-file.ts b/packages/core/src/environment/tools/edit-file.ts
index cb8ddeeb..68c660b6 100644
--- a/packages/core/src/environment/tools/edit-file.ts
+++ b/packages/core/src/environment/tools/edit-file.ts
@@ -27,7 +27,7 @@ import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
import type { ToolDefinitionConfig } from "../../interfaces.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
-import { atomicWriteFile } from "./file-utils.js";
+import { atomicWriteFile } from "../../internal/atomic-write.js";
import { buildReplacementHunks, renderHunk } from "./diff.js";
import { missingPathHint } from "./path-hint.js";
@@ -159,6 +159,7 @@ export function createEditFileTool(definition: ToolDefinitionConfig): BuiltinToo
await atomicWriteFile(resolved, newContent, {
...(fileMode !== undefined ? { mode: fileMode } : {}),
...(signal ? { signal } : {}),
+ followSymlinks: true,
});
} catch (err) {
if (signal?.aborted) return { stopReason: "aborted" };
diff --git a/packages/core/src/environment/tools/file-utils.ts b/packages/core/src/environment/tools/file-utils.ts
deleted file mode 100644
index a38b34f7..00000000
--- a/packages/core/src/environment/tools/file-utils.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Shared helpers for the file tools (edit_file / write_file).
- */
-import path from "node:path";
-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.
- * 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(resolved),
- `.${path.basename(resolved)}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
- );
- try {
- await writeFile(tmp, content, {
- encoding: "utf8",
- ...(opts.mode !== undefined ? { mode: opts.mode } : {}),
- ...(opts.signal ? { signal: opts.signal } : {}),
- });
- 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 babb92ff..60818381 100644
--- a/packages/core/src/environment/tools/write-file.ts
+++ b/packages/core/src/environment/tools/write-file.ts
@@ -25,7 +25,7 @@
*/
import path from "node:path";
import { mkdir, readFile, stat } from "node:fs/promises";
-import { atomicWriteFile, resolveWriteTarget } from "./file-utils.js";
+import { atomicWriteFile, resolveWriteTarget } from "../../internal/atomic-write.js";
import { buildLineDiffHunks, renderHunk } from "./diff.js";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
@@ -118,6 +118,7 @@ export function createWriteFileTool(definition: ToolDefinitionConfig): BuiltinTo
await atomicWriteFile(resolved, content, {
...(fileMode !== undefined ? { mode: fileMode } : {}),
...(signal ? { signal } : {}),
+ followSymlinks: true,
});
} catch (err) {
if (signal?.aborted) return { stopReason: "aborted" };
diff --git a/packages/core/src/goal/goal-file.ts b/packages/core/src/goal/goal-file.ts
index 4b776857..1d70c616 100644
--- a/packages/core/src/goal/goal-file.ts
+++ b/packages/core/src/goal/goal-file.ts
@@ -19,6 +19,7 @@
import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+import { atomicWriteFile } from "../internal/atomic-write.js";
/** Budget option value meaning "no budget" (also used for an absent budget option). */
export const UNLIMITED_BUDGET = -1;
@@ -48,7 +49,7 @@ export function serializeGoalFile(goal: GoalFile): string {
*/
export async function writeGoalFile(filePath: string, goal: GoalFile): Promise<void> {
await fs.mkdir(path.dirname(filePath), { recursive: true });
- await fs.writeFile(filePath, serializeGoalFile(goal), "utf8");
+ await atomicWriteFile(filePath, serializeGoalFile(goal));
}
/**
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 16507356..06c15926 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -55,6 +55,11 @@ export { appendAttachmentLines } from "./internal/session-support.js";
// Model-visible path spelling (forward slashes on Windows); the server uses it for its
// [attached file: ...] lines so every path the model reads has one spelling per platform.
export { modelVisiblePath } from "./internal/model-visible-path.js";
+// Atomic file replacement: the writer behind every Harness state file, shared with the server so
+// both sides of the same file (core's saveProjectConfig, the server's writeRaw) replace it the
+// same way.
+export { atomicWriteFile } from "./internal/atomic-write.js";
+export type { AtomicWriteOptions } from "./internal/atomic-write.js";
export { Agent, createAgent } from "./agent.js";
export type { CreateAgentOptions, CreateSessionOptions, ResumeSessionOptions } from "./agent.js";
diff --git a/packages/core/src/internal/atomic-write.ts b/packages/core/src/internal/atomic-write.ts
new file mode 100644
index 00000000..062f3647
--- /dev/null
+++ b/packages/core/src/internal/atomic-write.ts
@@ -0,0 +1,102 @@
+/**
+ * Atomic file replacement: the shared writer for every file the Harness keeps on disk.
+ *
+ * A plain `writeFile` truncates the target before it writes, so a crash or a full disk part-way
+ * through leaves the file half-written. For a state file that is worse than losing the write —
+ * a truncated `system_config.yaml` can still parse as YAML (the cut lands inside the
+ * `system_prompt` block scalar) and the Agent then boots with everything after it silently
+ * missing. Writing to a temporary file in the same directory and renaming it over the target
+ * makes the replacement a single atomic step: a reader sees the old bytes or the new ones.
+ */
+import path from "node:path";
+import { chmod, 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;
+
+export interface AtomicWriteOptions {
+ /**
+ * Permission bits for the result. Rename replaces the inode, so an existing file's bits are
+ * not inherited — pass them (or the intended mode for a secret) to keep them. Applied with an
+ * explicit chmod, which the umask does not mask, so `0o600` really is `0o600`.
+ */
+ mode?: number;
+ signal?: AbortSignal;
+ /**
+ * Write through a symlink standing at `target` — what a plain `writeFile` does, and what a
+ * user who linked their config into a dotfiles repository expects (see
+ * `resolveWriteTarget`). Left off, the rename replaces the link with a regular file: the
+ * right behavior where the directory is model-writable and a link planted there would
+ * carry the write outside it.
+ */
+ followSymlinks?: boolean;
+}
+
+/** Writes `content` to `target` atomically. The temp file is removed on failure (best effort). */
+export async function atomicWriteFile(
+ target: string,
+ content: string | Uint8Array,
+ opts: AtomicWriteOptions = {},
+): Promise<void> {
+ const dest = opts.followSymlinks === true ? await resolveWriteTarget(target) : target;
+ const tmp = path.join(
+ path.dirname(dest),
+ `.${path.basename(dest)}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
+ );
+ try {
+ await writeFile(tmp, content, {
+ ...(typeof content === "string" ? { encoding: "utf8" as const } : {}),
+ ...(opts.mode !== undefined ? { mode: opts.mode } : {}),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ // Rename orders the directory entry, not the data behind it: without this fsync a power
+ // loss can commit the new name over blocks that never reached the disk, which is the
+ // zero-length file the whole exercise is meant to prevent.
+ flush: true,
+ });
+ if (opts.mode !== undefined) await chmod(tmp, opts.mode);
+ await rename(tmp, dest);
+ } catch (err) {
+ await rm(tmp, { force: true }).catch(() => undefined);
+ throw err;
+ }
+}
+
+/**
+ * The path a write aimed at `target` must actually land on: the end of its symlink chain.
+ *
+ * For the file tools (edit_file / write_file) every other step 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: it 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. A config file a user symlinked into a
+ * dotfiles repository wants the same treatment, which is why the state writers opt in too.
+ *
+ * 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}"`);
+}
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index cc81132f..af8dd20c 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -20,6 +20,7 @@ import {
type SkillMetadata,
} from "@prismshadow/penguin-skills";
import type { ToolConfig, ToolDefinitionConfig } from "../interfaces.js";
+import { atomicWriteFile } from "../internal/atomic-write.js";
import {
AGENT_ID_PLACEHOLDER,
AGENTS_MD_PLACEHOLDER,
@@ -199,7 +200,7 @@ export async function loadOrInitAgentState(opts?: {
? loadPreinstalledSkills()
: (opts?.preset?.skills ?? []);
await Promise.all([
- fs.writeFile(mdPath, agentsMd, "utf8"),
+ atomicWriteFile(mdPath, agentsMd, { followSymlinks: true }),
...skills.map((skill) => installSkill(root, projectId, agentId, skill)),
// The example Benchmark is only provisioned alongside default_agent (so the evaluation
// center has data out of the box): idempotently skipped if benchmarks/ already exists,
@@ -211,7 +212,7 @@ export async function loadOrInitAgentState(opts?: {
// system_config.yaml is written last: its existence is the "initialization complete" marker
// (the load/init decision point). If this fails partway (disk full / crash), the next run
// still takes the init path and self-heals, so no half-initialized state with missing Skills is left behind.
- await fs.writeFile(configPath, stringifyYaml(systemConfig), "utf8");
+ await atomicWriteFile(configPath, stringifyYaml(systemConfig), { followSymlinks: true });
}
return { root, projectId, agentId, stateDir, systemConfig, agentsMd };
@@ -279,7 +280,7 @@ export async function resetSystemConfigToDefaults(
...defaultSystemConfig(),
version: agentStateVersion(prev),
};
- await fs.writeFile(configPath, stringifyYaml(next), "utf8");
+ await atomicWriteFile(configPath, stringifyYaml(next), { followSymlinks: true });
return next;
}
@@ -450,7 +451,7 @@ function assertSafeSkillFile(rel: string): void {
* Installs a Skill into the target Agent: writes `skills/<name>/SKILL.md` verbatim (the full
* SKILL.md content including frontmatter, ensuring a trailing newline). An optional icon.svg and
* any auxiliary `files` the SKILL.md references (e.g. `reference/API.md`, subdirectories
- * preserved) are written alongside it. The directory is replaced wholesale first, so reinstalling
+ * preserved) are written alongside it. The directory is replaced wholesale, so reinstalling
* updates to the latest content and drops files the new version no longer ships — the directory
* content always matches the Skill being installed. Each file path is checked to stay within the
* skill directory before anything is written.
@@ -468,26 +469,51 @@ export async function installSkill(
const auxiliary = Object.entries(skill.files ?? {});
for (const [rel] of auxiliary) assertSafeSkillFile(rel);
const dir = path.join(skillsDir(root, projectId, agentId), skill.name);
- // Clean replace: drop the old directory so no stale file survives a reinstall (same semantics
- // as the archive route), then write SKILL.md, the optional icon, and every auxiliary file.
- await fs.rm(dir, { recursive: true, force: true });
- await fs.mkdir(dir, { recursive: true });
const content = skill.content.endsWith("\n") ? skill.content : `${skill.content}\n`;
- const writes: Array<Promise<unknown>> = [
- fs.writeFile(path.join(dir, "SKILL.md"), content, "utf8"),
+ const files: Array<[string, string]> = [
+ ["SKILL.md", content],
+ ...(skill.icon !== undefined ? ([["icon.svg", skill.icon]] as Array<[string, string]>) : []),
+ ...auxiliary,
];
- if (skill.icon !== undefined) {
- writes.push(fs.writeFile(path.join(dir, "icon.svg"), skill.icon, "utf8"));
- }
- for (const [rel, data] of auxiliary) {
- const file = path.join(dir, rel);
- writes.push(
- fs
- .mkdir(path.dirname(file), { recursive: true })
- .then(() => fs.writeFile(file, data, "utf8")),
+ // Clean replace: no stale file survives a reinstall (same semantics as the archive route).
+ await replaceSkillDirectory(dir, files);
+}
+
+/**
+ * Replaces one Skill directory with exactly `files` (relative path → content, subdirectories
+ * created as needed). Everything is written into a staging directory and swapped in as the last
+ * step, so an interrupted install cannot leave a half-written Skill standing under the real name
+ * — the loader's only completeness criterion is that `<name>/SKILL.md` exists, which a directory
+ * written file-by-file satisfies long before it is complete. The staging name is dot-prefixed
+ * (never a valid Skill name, so it is skipped by the listings) and is cleared first, so a
+ * leftover from an earlier crash is never merged into this install.
+ *
+ * Shared with the server's archive-import route, which installs the same directory from a zip.
+ */
+export async function replaceSkillDirectory(
+ dir: string,
+ files: Iterable<[string, string | Uint8Array]>,
+): Promise<void> {
+ const staging = `${path.join(path.dirname(dir), `.${path.basename(dir)}`)}.incoming`;
+ await fs.rm(staging, { recursive: true, force: true });
+ await fs.mkdir(staging, { recursive: true });
+ try {
+ await Promise.all(
+ [...files].map(async ([rel, data]) => {
+ const file = path.join(staging, rel);
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, data);
+ }),
);
+ // rename(2) refuses to replace a non-empty directory, so the old one goes first. The window
+ // between the two is the one case this cannot make atomic; it is bounded by a single rm and
+ // leaves the Skill absent rather than corrupt.
+ await fs.rm(dir, { recursive: true, force: true });
+ await fs.rename(staging, dir);
+ } catch (err) {
+ await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);
+ throw err;
}
- await Promise.all(writes);
}
/** Uninstalls a Skill: deletes the entire `skills/<name>/` directory; idempotent, no error if it doesn't exist. */
@@ -539,6 +565,9 @@ export async function listInstalledSkills(
const skills: InstalledSkill[] = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
+ // A Skill name never starts with a dot (assertValidId), so a dot-prefixed directory is
+ // this Agent's staging directory, mid-install or left behind by an interrupted one.
+ if (entry.name.startsWith(".")) continue;
let raw: string;
try {
raw = await fs.readFile(path.join(dir, entry.name, "SKILL.md"), "utf8");
diff --git a/packages/core/src/state/agent-vault.ts b/packages/core/src/state/agent-vault.ts
index 9292a3f5..4bdab685 100644
--- a/packages/core/src/state/agent-vault.ts
+++ b/packages/core/src/state/agent-vault.ts
@@ -12,6 +12,7 @@
import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
+import { atomicWriteFile } from "../internal/atomic-write.js";
import { agentVaultPath } from "./paths.js";
import { assertValidId } from "./agent-state.js";
@@ -101,10 +102,9 @@ export async function saveAgentVault(
return;
}
await fs.mkdir(path.dirname(file), { recursive: true });
- // The secret file is written to disk with mode 0600 (a hidden file blocks `ls`, not reads; mode
- // only takes effect on creation, so chmod is applied to converge an existing file too).
- await fs.writeFile(file, `${stringifyToml(vault)}\n`, { encoding: "utf8", mode: 0o600 });
- await fs.chmod(file, 0o600);
+ // The secret file is written to disk with mode 0600 (a hidden file blocks `ls`, not reads); the
+ // atomic write applies that mode to every replacement, so an existing file converges to it too.
+ await atomicWriteFile(file, `${stringifyToml(vault)}\n`, { mode: 0o600, followSymlinks: true });
}
/**
diff --git a/packages/core/src/state/kernel-update.ts b/packages/core/src/state/kernel-update.ts
index 1a02a2b4..8194cfb2 100644
--- a/packages/core/src/state/kernel-update.ts
+++ b/packages/core/src/state/kernel-update.ts
@@ -23,6 +23,7 @@
*/
import fs from "node:fs/promises";
import { parseDocument, parse as parseYaml } from "yaml";
+import { atomicWriteFile } from "../internal/atomic-write.js";
import { defaultSystemConfig } from "./default-config.js";
import {
KERNEL_SUPERSEDED_TAB_HASHES,
@@ -126,6 +127,6 @@ export async function applyKernelUpdate(
}
doc.setIn(["kernel_version"], KERNEL_VERSION);
- await fs.writeFile(configPath, doc.toString(), "utf8");
+ await atomicWriteFile(configPath, doc.toString(), { followSymlinks: true });
return { advanced, kept, kernelVersion: KERNEL_VERSION };
}
diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.ts
index 6b108122..f1a4d644 100644
--- a/packages/core/src/state/project-config.ts
+++ b/packages/core/src/state/project-config.ts
@@ -28,6 +28,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import type { CommandPolicyConfig, CommandPolicyRule, ThinkingLevelName } from "../interfaces.js";
+import { atomicWriteFile } from "../internal/atomic-write.js";
import { DEFAULT_COMMAND_POLICY_RULES } from "./command-policy-defaults.js";
import { canonicalClientType, presetModelEntries } from "./model-catalog.js";
import { projectConfigPath } from "./paths.js";
@@ -421,8 +422,8 @@ export function renderProjectConfigToml(data: Record<string, unknown>): string {
/**
* Saves the Project config: writes the full table to the single config file
* `.project_config.toml`. The file contains secrets like api_key, so it's written to disk with
- * mode 0600 (a hidden file blocks `ls`, not reads; mode only takes effect on creation, so chmod
- * converges an existing file too).
+ * mode 0600 (a hidden file blocks `ls`, not reads); the atomic write applies that mode to every
+ * replacement, so an existing file converges to it as well.
*/
export async function saveProjectConfig(
root: string,
@@ -431,11 +432,10 @@ export async function saveProjectConfig(
): Promise<void> {
const file = projectConfigPath(root, projectId);
await fs.mkdir(path.dirname(file), { recursive: true });
- await fs.writeFile(file, renderProjectConfigToml({ ...cfg }), {
- encoding: "utf8",
+ await atomicWriteFile(file, renderProjectConfigToml({ ...cfg }), {
mode: 0o600,
+ followSymlinks: true,
});
- await fs.chmod(file, 0o600);
}
/**
diff --git a/packages/core/test/agent-skills.test.ts b/packages/core/test/agent-skills.test.ts
index 75de5c79..8bdd94d7 100644
--- a/packages/core/test/agent-skills.test.ts
+++ b/packages/core/test/agent-skills.test.ts
@@ -115,6 +115,13 @@ describe("installSkill / removeSkill", () => {
}
});
+ it("stages the install and leaves no staging directory behind", async () => {
+ const skill = librarySkill("penguin-sdk")!;
+ await install(skill.name, skill.content);
+ const entries = await fs.readdir(skillsDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID));
+ expect(entries).toEqual(["penguin-sdk"]);
+ });
+
it("removeSkill deletes the whole skill directory and is idempotent", async () => {
const skill = librarySkill("penguin-sdk")!;
await install(skill.name, skill.content);
@@ -196,6 +203,14 @@ describe("listInstalledSkills", () => {
const dir = skillsDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
await fs.mkdir(path.join(dir, "empty-dir"), { recursive: true });
await fs.writeFile(path.join(dir, "stray.md"), "stray", "utf8");
+ // A staging directory an interrupted install left behind is complete enough to look like a
+ // Skill; the dot prefix (never a valid Skill name) is what keeps it out.
+ await fs.mkdir(path.join(dir, ".half-installed.incoming"), { recursive: true });
+ await fs.writeFile(
+ path.join(dir, ".half-installed.incoming", "SKILL.md"),
+ "---\nname: half-installed\n---\nBody\n",
+ "utf8",
+ );
expect(await list()).toEqual([{ name: "broken", description: "", version: 1, updated: "" }]);
});
});
diff --git a/packages/core/test/atomic-write.test.ts b/packages/core/test/atomic-write.test.ts
new file mode 100644
index 00000000..cf10d01d
--- /dev/null
+++ b/packages/core/test/atomic-write.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Behavior tests for atomicWriteFile — the writer behind every Harness state file: the
+ * replacement leaves no temp file behind on either path, `mode` lands exactly (the umask does
+ * not mask it), and the symlink question is answered both ways, since the state files follow a
+ * link into a dotfiles repository while the model-writable Memory directory deliberately does
+ * not.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ chmod,
+ lstat,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { atomicWriteFile } from "../src/internal/atomic-write.js";
+
+let dir: string;
+
+beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), "penguin-atomic-"));
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+describe("atomicWriteFile", () => {
+ it("creates a file and replaces its content, leaving no temp file behind", async () => {
+ const file = path.join(dir, "system_config.yaml");
+ await atomicWriteFile(file, "first\n");
+ expect(await readFile(file, "utf8")).toBe("first\n");
+
+ await atomicWriteFile(file, "second\n");
+ expect(await readFile(file, "utf8")).toBe("second\n");
+ expect(await readdir(dir)).toEqual(["system_config.yaml"]);
+ });
+
+ it("writes bytes as given when the content is not a string", async () => {
+ const file = path.join(dir, "bundle.webz");
+ await atomicWriteFile(file, new Uint8Array([0x1f, 0x8b, 0x00, 0xff]));
+ expect([...(await readFile(file))]).toEqual([0x1f, 0x8b, 0x00, 0xff]);
+ });
+
+ it("leaves the previous content and no temp file when the write fails", async () => {
+ const file = path.join(dir, "keep.toml");
+ await atomicWriteFile(file, "kept\n");
+ const aborted = AbortSignal.abort();
+ await expect(atomicWriteFile(file, "lost\n", { signal: aborted })).rejects.toThrow();
+ expect(await readFile(file, "utf8")).toBe("kept\n");
+ expect(await readdir(dir)).toEqual(["keep.toml"]);
+ });
+
+ it.skipIf(process.platform === "win32")(
+ "applies mode to a new and to an existing file, unmasked by the umask",
+ async () => {
+ const file = path.join(dir, ".vault.toml");
+ await atomicWriteFile(file, "A = 'x'\n", { mode: 0o600 });
+ expect((await lstat(file)).mode & 0o777).toBe(0o600);
+
+ // Rename replaces the inode, so a file that was world-readable before converges to 0600.
+ await chmod(file, 0o644);
+ await atomicWriteFile(file, "A = 'y'\n", { mode: 0o600 });
+ expect((await lstat(file)).mode & 0o777).toBe(0o600);
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "replaces a symlink standing at the target by default",
+ async () => {
+ const outside = path.join(dir, "outside.md");
+ const link = path.join(dir, "MEMORY.md");
+ await writeFile(outside, "untouched\n", "utf8");
+ await symlink(outside, link);
+
+ await atomicWriteFile(link, "index\n");
+ expect((await lstat(link)).isSymbolicLink()).toBe(false);
+ expect(await readFile(link, "utf8")).toBe("index\n");
+ expect(await readFile(outside, "utf8")).toBe("untouched\n");
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "writes through a symlink when asked, keeping the link",
+ async () => {
+ const real = path.join(dir, "dotfiles", "zshrc");
+ const link = path.join(dir, ".zshrc");
+ await mkdir(path.dirname(real), { recursive: true });
+ await writeFile(real, "old\n", "utf8");
+ await symlink(real, link);
+
+ await atomicWriteFile(link, "new\n", { followSymlinks: true });
+ expect((await lstat(link)).isSymbolicLink()).toBe(true);
+ expect(await readFile(real, "utf8")).toBe("new\n");
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "follows a symlink chain that ends at a file which does not exist yet",
+ async () => {
+ const target = path.join(dir, "absent.yaml");
+ const middle = path.join(dir, "middle.yaml");
+ const link = path.join(dir, "GOAL.yaml");
+ await symlink(target, middle);
+ await symlink("middle.yaml", link);
+
+ await atomicWriteFile(link, "objective: x\n", { followSymlinks: true });
+ expect(await readFile(target, "utf8")).toBe("objective: x\n");
+ expect((await lstat(link)).isSymbolicLink()).toBe(true);
+ expect((await lstat(middle)).isSymbolicLink()).toBe(true);
+ },
+ );
+});
diff --git a/packages/desktop/src/cli-install.ts b/packages/desktop/src/cli-install.ts
index 579fcfe3..04bd3f4e 100644
--- a/packages/desktop/src/cli-install.ts
+++ b/packages/desktop/src/cli-install.ts
@@ -150,8 +150,13 @@ function installAppImage(win: BrowserWindow | null): void {
}
try {
fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(wrapper, script, { mode: 0o755 });
- fs.chmodSync(wrapper, 0o755); // writeFileSync mode is ignored when the file existed.
+ // Written to a temp file and renamed over the wrapper: a failed write leaves the previous
+ // command in place instead of a truncated script on PATH. chmod before the rename, since
+ // writeFileSync's mode is masked by the umask.
+ const tmp = `${wrapper}.tmp`;
+ fs.writeFileSync(tmp, script, { mode: 0o755, flush: true });
+ fs.chmodSync(tmp, 0o755);
+ fs.renameSync(tmp, wrapper);
} catch (err) {
showResult(win, false, String(err));
return;
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index a8de73d6..88e640db 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -485,13 +485,18 @@ export class HmrHost {
* that a push which fails to boot leaves an unreferenced file behind; the next
* successful push's prune collects it, and the committed version is force-kept
* regardless of how many failures sit between them.
+ *
+ * The write goes through writeStoreFile, which matters more here than for the other
+ * two artifacts: this path is taken before the commit, so an idempotent re-push aims
+ * at the exact file the current manifest points at — and the running version boots
+ * from it.
*/
private async storePlatformBundle(content: string): Promise<{ file: string; sha: string }> {
const sha = sha1(content).slice(0, 16);
const dir = path.join(this.storeDir, "platform");
await fsp.mkdir(dir, { recursive: true });
const file = path.join(dir, `${sha}.mjs`);
- await fsp.writeFile(file, content, "utf8");
+ await writeStoreFile(file, Buffer.from(content, "utf8"));
return { file, sha };
}
@@ -586,15 +591,16 @@ export class HmrHost {
): Promise<boolean> {
try {
// The platform bundle is already in the store: storePlatformBundle put it at its
- // content-addressed path so the boot could import it from there.
+ // content-addressed path so the boot could import it from there, through the same
+ // writeStoreFile the other two artifacts go through.
const cliSha = sha1(cliContent).slice(0, 16);
const cliDir = path.join(this.storeDir, "cli");
await fsp.mkdir(cliDir, { recursive: true });
- await fsp.writeFile(path.join(cliDir, `${cliSha}.mjs`), cliContent, "utf8");
+ await writeStoreFile(path.join(cliDir, `${cliSha}.mjs`), Buffer.from(cliContent, "utf8"));
const webDir = path.join(this.storeDir, "web");
await fsp.mkdir(webDir, { recursive: true });
- await fsp.writeFile(path.join(webDir, `${webSha}.webz`), webGz);
+ await writeStoreFile(path.join(webDir, `${webSha}.webz`), webGz);
await this.commitManifest(() => ({
platform: { bundle: `store/platform/${platformSha}.mjs` },
@@ -731,6 +737,27 @@ function filesDigest(files: Record<string, string>): string {
return hash.digest("hex");
}
+/**
+ * Writes one content-addressed artifact. A file that already holds these exact bytes is left
+ * untouched — the store is keyed by content hash, so re-pushing a version (an idempotent push, a
+ * rollback to something installed before) otherwise rewrites the very file the committed manifest
+ * points at, and a crash during that rewrite truncates a bundle the runtime still needs to boot.
+ * Anything else is written to a temp file and renamed into place, so an interrupted write leaves
+ * the store's previous state rather than a half-written artifact under a hash that promises
+ * complete content.
+ */
+async function writeStoreFile(file: string, content: Buffer): Promise<void> {
+ if (await sameFileContent(file, content)) return;
+ const tmp = `${file}.${process.pid}.tmp`;
+ try {
+ await fsp.writeFile(tmp, content, { flush: true });
+ await fsp.rename(tmp, file);
+ } catch (err) {
+ await fsp.rm(tmp, { force: true }).catch(() => undefined);
+ throw err;
+ }
+}
+
/** No absolute paths, no `..` segments — the map is looked up by exact key, but a malformed key must never be stored. */
/** Whether `file` already holds exactly these bytes (missing/unreadable counts as no). */
async function sameFileContent(file: string, content: Buffer): Promise<boolean> {
diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.ts
index 1f489427..2377a210 100644
--- a/packages/server/src/http/routes/skills.ts
+++ b/packages/server/src/http/routes/skills.ts
@@ -21,6 +21,7 @@ import {
installSkill,
listInstalledSkills,
removeSkill,
+ replaceSkillDirectory,
skillsDir,
} from "@prismshadow/penguin-core";
import {
@@ -295,14 +296,10 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
throw new HttpError(409, "skill_exists", `Skill is already installed: ${skill.name}`);
}
}
- // Replace semantics (same as reinstalling from the library): drop the old directory
- // first so no stale file survives, then write every archive file (subdirectories kept).
- await fs.rm(dir, { recursive: true, force: true });
- for (const [rel, data] of skill.files) {
- const file = path.join(dir, rel);
- await fs.mkdir(path.dirname(file), { recursive: true });
- await fs.writeFile(file, data);
- }
+ // Replace semantics (same as reinstalling from the library): the archive's files are
+ // staged and swapped in, so no stale file survives and an interrupted import leaves no
+ // half-written Skill behind (subdirectories kept).
+ await replaceSkillDirectory(dir, skill.files);
return c.json(await listResponse(projectId, agentId), 201);
});
diff --git a/packages/server/src/runtime/schedule-store.ts b/packages/server/src/runtime/schedule-store.ts
index 355765f8..e7a0c297 100644
--- a/packages/server/src/runtime/schedule-store.ts
+++ b/packages/server/src/runtime/schedule-store.ts
@@ -8,7 +8,7 @@
import fs from "node:fs/promises";
import path from "node:path";
import { stringify as stringifyToml } from "smol-toml";
-import { resolveModelRef, scheduleDir } from "@prismshadow/penguin-core";
+import { atomicWriteFile, resolveModelRef, scheduleDir } from "@prismshadow/penguin-core";
import type { ProjectConfig } from "@prismshadow/penguin-core";
import { cacheable, statMtime } from "../internal/mtime-gate.js";
import type { ScheduleDefinition } from "./schedule-file.js";
@@ -261,7 +261,7 @@ export async function writeScheduleFile(
): Promise<void> {
const dir = scheduleDir(root, projectId, agentId);
await fs.mkdir(dir, { recursive: true });
- await fs.writeFile(path.join(dir, `${name}.toml`), raw, "utf8");
+ await atomicWriteFile(path.join(dir, `${name}.toml`), raw, { followSymlinks: true });
}
/** Delete a schedule file; returns false if it doesn't exist. */
diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.ts
index 4e42257e..982b8c19 100644
--- a/packages/server/src/services/agent-config-service.ts
+++ b/packages/server/src/services/agent-config-service.ts
@@ -20,6 +20,7 @@ import {
LEGACY_VAULT_SECTION,
agentsMdPath,
applyKernelUpdate,
+ atomicWriteFile,
isKernelOutdated,
agentStateDir,
agentStateVersion,
@@ -265,7 +266,9 @@ export class AgentConfigService {
await this.applyConfigUpdate(projectId, agentId, req.config);
}
if (req.agentsMd !== undefined) {
- await fs.writeFile(agentsMdPath(this.root, projectId, agentId), req.agentsMd, "utf8");
+ await atomicWriteFile(agentsMdPath(this.root, projectId, agentId), req.agentsMd, {
+ followSymlinks: true,
+ });
}
}
@@ -382,7 +385,7 @@ export class AgentConfigService {
doc.setIn(["tools", "mcpServers"], validateMcpServers(cfg.mcpServers));
}
- await fs.writeFile(yamlPath, doc.toString(), "utf8");
+ await atomicWriteFile(yamlPath, doc.toString(), { followSymlinks: true });
}
/**
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index 241430d5..06783ad6 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -155,7 +155,8 @@ export class AgentService {
}
const present = await Promise.all(
dirents
- .filter((d) => d.isDirectory())
+ // Dot-prefixed directories are install staging, never a Skill (a Skill name has no dot).
+ .filter((d) => d.isDirectory() && !d.name.startsWith("."))
.map(async (d) => {
try {
await fs.access(path.join(base, d.name, "SKILL.md"));
diff --git a/packages/server/src/services/memory-service.ts b/packages/server/src/services/memory-service.ts
index f9d5cbf4..34ac7494 100644
--- a/packages/server/src/services/memory-service.ts
+++ b/packages/server/src/services/memory-service.ts
@@ -25,12 +25,12 @@
* Files are the source of truth and are read fresh on every request (they are small, requests
* are rare, and the model edits the same files from its side).
*/
-import { randomBytes } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import {
MEMORY_INDEX_FILENAME,
USER_SCOPE_KEY,
+ atomicWriteFile,
hasMemoryPlaceholder,
insertMemoryPlaceholder,
memoryDir,
@@ -434,7 +434,7 @@ export class MemoryService {
const added: string[] = [];
for (const file of planned) {
if (request.mode === "skip" && present.has(file.name)) continue;
- await this.writeScopeFile(dir, file.target, file.content);
+ await this.writeScopeFile(file.target, file.content);
if (!present.has(file.name)) added.push(file.name);
}
for (const name of removed) {
@@ -447,7 +447,7 @@ export class MemoryService {
let indexWritten = false;
if (index !== null) {
if (replacesIndex || !(await this.hasIndexFile(dir))) {
- await this.writeScopeFile(dir, path.join(dir, MEMORY_INDEX_FILENAME), index);
+ await this.writeScopeFile(path.join(dir, MEMORY_INDEX_FILENAME), index);
indexWritten = true;
} else {
indexWritten = await this.extendIndex(dir, index, written);
@@ -479,28 +479,23 @@ export class MemoryService {
}
if (additions.length === 0) return false;
const head = current === "" || current.endsWith("\n") ? current : `${current}\n`;
- await this.writeScopeFile(dir, indexPath, `${head}${additions.join("\n")}\n`);
+ await this.writeScopeFile(indexPath, `${head}${additions.join("\n")}\n`);
return true;
}
/**
- * The write path for imported content, shared by the topic files and the index.
+ * The write path for every change this service makes to Memory content, shared by the imported
+ * topic files and the index.
*
* The target has already been through `resolveFile` (or is the reserved index name, which is
* never client-supplied), so it names a file directly inside this scope. The write goes to a
* temporary dotfile — invisible to every topic listing — and is renamed over the target, so a
- * symlink standing at that name is replaced rather than followed out of the Memory directory,
- * and a reader never sees a half-written memory.
+ * reader never sees a half-written memory. Symlinks are deliberately not followed: the Memory
+ * directory is model-writable, and a link planted at a topic's name would otherwise carry the
+ * write out of it. Replacing the link keeps the write inside the scope.
*/
- private async writeScopeFile(dir: string, target: string, content: string): Promise<void> {
- const tmp = path.join(dir, `.import-${randomBytes(6).toString("hex")}.tmp`);
- try {
- await fs.writeFile(tmp, content, "utf8");
- await fs.rename(tmp, target);
- } catch (err) {
- await fs.rm(tmp, { force: true });
- throw err;
- }
+ private async writeScopeFile(target: string, content: string): Promise<void> {
+ await atomicWriteFile(target, content);
}
/** Reads a regular file as text, null when it is absent, unreadable, or not a regular file (lstat, so a symlink is never followed). */
@@ -548,7 +543,7 @@ export class MemoryService {
const lines = content.split("\n");
const kept = lines.filter((line) => !link.test(line));
if (kept.length === lines.length) return;
- await fs.writeFile(indexPath, kept.join("\n"), "utf8");
+ await this.writeScopeFile(indexPath, kept.join("\n"));
}
private async fileInfo(dir: string, name: string): Promise<MemoryFileInfo | null> {
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 1165f99b..2d1d81b6 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -28,6 +28,7 @@ import path from "node:path";
import { parse as parseToml } from "smol-toml";
import {
CHAT_APPROVAL_MODES,
+ atomicWriteFile,
DEFAULT_CHAT_THINKING_LEVELS,
DEFAULT_COMMAND_POLICY_RULES,
effectiveCommandPolicyRules,
@@ -290,9 +291,8 @@ export class ProjectConfigService {
/**
* Writes the whole object to disk: the file inlines secrets like api_key, always
- * written with mode 0600 (the `mode` option only applies at creation time, so
- * chmod is used to enforce it on existing files too — matching core's
- * saveProjectConfig behavior).
+ * written with mode 0600, and replaced atomically so a crash mid-write cannot
+ * truncate it — matching core's saveProjectConfig behavior.
*/
async writeRaw(projectId: string, data: RawTable): Promise<void> {
const file = this.filePath(projectId);
@@ -300,8 +300,10 @@ export class ProjectConfigService {
// Rendering goes through core's single writer: paired references become inline
// tables, models is placed last — matching the CLI's output format exactly
// (the same file should never have two formats).
- await fs.writeFile(file, renderProjectConfigToml(data), { encoding: "utf8", mode: 0o600 });
- await fs.chmod(file, 0o600);
+ await atomicWriteFile(file, renderProjectConfigToml(data), {
+ mode: 0o600,
+ followSymlinks: true,
+ });
// Every service write funnels through here: invalidate synchronously so the next
// read re-parses (external writers are caught by readTable's stat instead).
this.cache.delete(projectId);