Skip to content

AI-native design editor. Open-source Figma alternative.

refactor: write replaced files through one atomic helper in @open-pencil/core/node/fs (#1555)

Danila Poyarkov39a8180177d1
diff --git a/bun.lock b/bun.lock
index 4efab7381..370169a31 100644
--- a/bun.lock
+++ b/bun.lock
@@ -515,6 +515,7 @@
"@ai-sdk/harness-pi": "1.0.140",
"@ai-sdk/sandbox-just-bash": "1.0.138",
"@earendil-works/pi-tui": "0.85.1",
+ "@open-pencil/core": "workspace:*",
"amaro": "1.2.2",
},
"devDependencies": {
diff --git a/changes/1555/fixed.md b/changes/1555/fixed.md
new file mode 100644
index 000000000..78c95b1da
--- /dev/null
+++ b/changes/1555/fixed.md
@@ -0,0 +1 @@
+- CLI commands that save a `.fig`, such as `eval --write`, `convert`, and `import`, replace the file only once it is fully written, so a failed save keeps the previous file.
diff --git a/packages/cli/src/commands/export/storybook/manifest.ts b/packages/cli/src/commands/export/storybook/manifest.ts
index 5890d368c..ff5a7d46f 100644
--- a/packages/cli/src/commands/export/storybook/manifest.ts
+++ b/packages/cli/src/commands/export/storybook/manifest.ts
@@ -1,8 +1,10 @@
-import { readFile, rename, writeFile } from 'node:fs/promises'
+import { readFile } from 'node:fs/promises'
import { isAbsolute, join, posix } from 'node:path'
import * as v from 'valibot'
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
+
/**
* Records which document and page generated each file in a Storybook output folder, so a
* re-export replaces its own stories and leaves every other file alone.
@@ -58,9 +60,7 @@ export async function readManifest(outputDir: string): Promise<StoryManifest> {
return result.output
}
-/** Written beside the stories and renamed into place, so a failed write keeps the old one. */
+/** Written all at once, so a failed write keeps the old one. */
export async function writeManifest(outputDir: string, manifest: StoryManifest): Promise<void> {
- const path = join(outputDir, MANIFEST_FILE)
- await writeFile(`${path}.tmp`, `${JSON.stringify(manifest, null, 2)}\n`)
- await rename(`${path}.tmp`, path)
+ await writeFileAtomic(join(outputDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`)
}
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index 52d14f58b..096f5715d 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -1,4 +1,4 @@
-import { readFile, realpath, writeFile } from 'node:fs/promises'
+import { readFile, realpath } from 'node:fs/promises'
import { dirname, resolve, sep } from 'node:path'
import { SkiaRenderer } from '@open-pencil/core/canvas'
@@ -11,6 +11,7 @@ import {
installTextMeasurer,
sizeAutoResizingText
} from '@open-pencil/core/layout'
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
import { prepareGraphFonts, type DocumentFontStatus } from '@open-pencil/core/text'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { collectSceneMutation } from '@open-pencil/scene-graph/mutation-impact'
@@ -96,7 +97,7 @@ export const documentWriteOptions = {
/** Save a headless document as `.fig`, with the thumbnail `export --format fig` renders. */
export async function writeFigDocument(graph: SceneGraph, filePath: string): Promise<void> {
const result = await io.writeDocument('fig', graph, { renderThumbnail: true })
- await writeFile(filePath, result.data as Uint8Array)
+ await writeFileAtomic(filePath, result.data as Uint8Array, { symlink: 'follow' })
}
export function populateDocumentPage(graph: SceneGraph, pageId: string): boolean {
diff --git a/packages/cli/src/library/catalog.ts b/packages/cli/src/library/catalog.ts
index 631f8d980..6e169fbe4 100644
--- a/packages/cli/src/library/catalog.ts
+++ b/packages/cli/src/library/catalog.ts
@@ -1,4 +1,4 @@
-import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
+import { mkdir, readFile } from 'node:fs/promises'
import { dirname, resolve, sep } from 'node:path'
import * as v from 'valibot'
@@ -20,6 +20,7 @@ import {
storedLibraryRevisionSchema,
validateLibraryRevision
} from '@open-pencil/core/library'
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
const catalogPublicationQueues = new Map<string, Promise<void>>()
@@ -140,9 +141,7 @@ export class FileSystemLibraryCatalog implements LibraryCatalog {
async #writeJSON(relative: string, value: unknown): Promise<void> {
const path = this.#path(relative)
- const temporaryPath = `${path}.${crypto.randomUUID()}.tmp`
await mkdir(dirname(path), { recursive: true })
- await writeFile(temporaryPath, JSON.stringify(value, null, 2))
- await rename(temporaryPath, path)
+ await writeFileAtomic(path, JSON.stringify(value, null, 2))
}
}
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 41a058331..b16e25a11 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -4,6 +4,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- The root entry is the editor (`createEditor` and its types); every other domain is a subpath listed in `packages/core/package.json` `exports`. Add a subpath there rather than deep-importing, and never re-export another package's names.
- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.
+- Node-only helpers live under `@open-pencil/core/node/*`, which nothing browser code imports. Files the CLI, MCP server, and harness replace are written with `writeFileAtomic` from `@open-pencil/core/node/fs` rather than a hand-rolled temporary file and rename; only a document saved in place follows a symlink (`packages/core/tests/node/fs.test.ts`).
- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement.
- Content an author wrote (design JSX, HTML, `.pen`) gets its sizes and positions from `layoutAuthoredNodes` in `packages/core/src/layout.ts`, which measures text that resizes to its content wherever it sits and then lays out the pages involved; renderers and readers of authored formats call it, while `.fig` keeps the geometry it stores (`packages/core/tests/layout/authored.test.ts`).
- `.pen` documents draw as pen.dev draws them. `bun tools/generate/visual-oracles/src/cli.ts compare pen` exports every frame of the document open in pen.dev into `tests/fixtures/pen-oracles/` with the icons and fonts it uses; a new reading rule adds a probe frame there and a threshold to its `manifest.json` (`packages/core/tests/io/formats/pen/oracle.test.ts`).
diff --git a/packages/core/package.json b/packages/core/package.json
index bd50295d6..616d52c23 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -163,6 +163,12 @@
"types": "./dist/layout.d.ts",
"import": "./dist/layout.js",
"default": "./dist/layout.js"
+ },
+ "./node/fs": {
+ "bun": "./src/node/fs.ts",
+ "types": "./dist/node/fs.d.ts",
+ "import": "./dist/node/fs.js",
+ "default": "./dist/node/fs.js"
}
},
"publishConfig": {
diff --git a/packages/core/src/node/fs.ts b/packages/core/src/node/fs.ts
new file mode 100644
index 000000000..ecfb0d110
--- /dev/null
+++ b/packages/core/src/node/fs.ts
@@ -0,0 +1,77 @@
+import { chmod, lstat, open, realpath, rename, unlink, writeFile } from 'node:fs/promises'
+import { basename, dirname, join } from 'node:path'
+
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+export interface AtomicWriteOptions {
+ /** The file's mode; an existing file otherwise keeps its own, and a new one gets the default. */
+ mode?: number
+ /**
+ * What a symlink at `path` gets. `replace`, the default, puts the new file where the link was,
+ * as a rename does, so a file kept under a root is never written outside it through a planted
+ * link. `follow` writes the file the link points at, as a document saved in place should.
+ */
+ symlink?: 'follow' | 'replace'
+}
+
+function hasCode(error: unknown, ...codes: string[]): boolean {
+ return error instanceof Error && 'code' in error && codes.includes(String(error.code))
+}
+
+async function resolveTarget(path: string): Promise<string> {
+ try {
+ return await realpath(path)
+ } catch (error) {
+ if (hasCode(error, 'ENOENT')) return path
+ throw error
+ }
+}
+
+/** The mode of the regular file at `path`, which a symlink or a missing file does not have. */
+async function fileMode(path: string): Promise<number | undefined> {
+ try {
+ const stats = await lstat(path)
+ return stats.isFile() ? stats.mode & 0o7777 : undefined
+ } catch (error) {
+ if (hasCode(error, 'ENOENT')) return undefined
+ throw error
+ }
+}
+
+/**
+ * Writes `data` to `path` all at once: into a new file beside it, which then replaces it, so a
+ * reader never sees half a file and a failed write leaves the old one. An existing file in a
+ * directory that takes no new files is written in place, as it could be before.
+ */
+export async function writeFileAtomic(
+ path: string,
+ data: string | Uint8Array,
+ options: AtomicWriteOptions = {}
+): Promise<void> {
+ const target = options.symlink === 'follow' ? await resolveTarget(path) : path
+ const existing = await fileMode(target)
+ const mode = options.mode ?? existing
+ const temporary = join(dirname(target), `.${basename(target)}.${randomHex(8)}.tmp`)
+ let handle
+ try {
+ handle = await open(temporary, 'wx', mode ?? 0o666)
+ } catch (error) {
+ if (existing === undefined || !hasCode(error, 'EACCES', 'EPERM')) throw error
+ await writeFile(target, data)
+ return
+ }
+ try {
+ try {
+ await handle.writeFile(data)
+ // The mode `open` takes is masked by the umask; the file keeps the one it had.
+ if (mode !== undefined) await chmod(temporary, mode)
+ await handle.sync()
+ } finally {
+ await handle.close()
+ }
+ await rename(temporary, target)
+ } catch (error) {
+ await unlink(temporary).catch(() => undefined)
+ throw error
+ }
+}
diff --git a/packages/core/tests/node/fs.test.ts b/packages/core/tests/node/fs.test.ts
new file mode 100644
index 000000000..672aaddb2
--- /dev/null
+++ b/packages/core/tests/node/fs.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test } from 'bun:test'
+import { chmod, lstat, mkdtemp, readdir, readFile, stat, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
+
+async function scratch() {
+ return mkdtemp(join(tmpdir(), 'open-pencil-atomic-'))
+}
+
+describe('writeFileAtomic', () => {
+ test('replaces a file, keeping its mode and leaving nothing beside it', async () => {
+ const dir = await scratch()
+ const path = join(dir, 'doc.json')
+ await writeFile(path, 'old')
+ await chmod(path, 0o640)
+
+ await writeFileAtomic(path, 'new')
+
+ expect(await readFile(path, 'utf8')).toBe('new')
+ expect((await stat(path)).mode & 0o777).toBe(0o640)
+ expect(await readdir(dir)).toEqual(['doc.json'])
+ })
+
+ test('gives a new file the mode it is asked for', async () => {
+ const dir = await scratch()
+ const path = join(dir, 'token.json')
+
+ await writeFileAtomic(path, new TextEncoder().encode('{}'), { mode: 0o600 })
+
+ expect(await readFile(path, 'utf8')).toBe('{}')
+ expect((await stat(path)).mode & 0o777).toBe(0o600)
+ })
+
+ test('writes a document through a symlink to the file it points at when asked', async () => {
+ const dir = await scratch()
+ const target = join(dir, 'real.fig')
+ const link = join(dir, 'link.fig')
+ await writeFile(target, 'old')
+ await symlink(target, link)
+
+ await writeFileAtomic(link, 'new', { symlink: 'follow' })
+
+ expect((await lstat(link)).isSymbolicLink()).toBe(true)
+ expect(await readFile(target, 'utf8')).toBe('new')
+ })
+
+ test('replaces a symlink by default, leaving the file it pointed at', async () => {
+ const dir = await scratch()
+ const target = join(dir, 'elsewhere')
+ const link = join(dir, 'discovery.json')
+ await writeFile(target, 'untouched')
+ await symlink(target, link)
+
+ await writeFileAtomic(link, 'token', { mode: 0o600 })
+
+ expect((await lstat(link)).isSymbolicLink()).toBe(false)
+ expect(await readFile(link, 'utf8')).toBe('token')
+ expect(await readFile(target, 'utf8')).toBe('untouched')
+ })
+
+ test('writes an existing file in place where its directory takes no new files', async () => {
+ const dir = await scratch()
+ const path = join(dir, 'doc.fig')
+ await writeFile(path, 'old')
+ await chmod(dir, 0o500)
+ try {
+ await writeFileAtomic(path, 'new', { symlink: 'follow' })
+ } finally {
+ await chmod(dir, 0o700)
+ }
+
+ expect(await readFile(path, 'utf8')).toBe('new')
+ expect(await readdir(dir)).toEqual(['doc.fig'])
+ })
+})
diff --git a/packages/harness/package.json b/packages/harness/package.json
index f08005769..92d6aa656 100644
--- a/packages/harness/package.json
+++ b/packages/harness/package.json
@@ -37,6 +37,7 @@
"@ai-sdk/harness-pi": "1.0.140",
"@ai-sdk/sandbox-just-bash": "1.0.138",
"@earendil-works/pi-tui": "0.85.1",
+ "@open-pencil/core": "workspace:*",
"amaro": "1.2.2"
},
"devDependencies": {
diff --git a/packages/harness/src/session-store.ts b/packages/harness/src/session-store.ts
index ccf02a3cb..f12787728 100644
--- a/packages/harness/src/session-store.ts
+++ b/packages/harness/src/session-store.ts
@@ -1,7 +1,8 @@
-import { randomBytes } from 'node:crypto'
-import { mkdir, open, readFile, rename, rm } from 'node:fs/promises'
+import { mkdir, readFile, rm } from 'node:fs/promises'
import { dirname, join } from 'node:path'
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
+
import type { HarnessResumeState } from './backends/types'
const MAX_RESUME_STATE_BYTES = 1024 * 1024
@@ -63,14 +64,7 @@ export class FileResumeStateStore implements ResumeStateStore {
throw new Error('Harness state exceeds the persistence size limit')
}
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
- const temporaryPath = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`
- const handle = await open(temporaryPath, 'wx', 0o600)
- try {
- await handle.writeFile(content, 'utf8')
- } finally {
- await handle.close()
- }
- await rename(temporaryPath, path)
+ await writeFileAtomic(path, content, { mode: 0o600 })
}
async remove(sessionId: string): Promise<void> {
diff --git a/packages/mcp/src/transport/discovery.ts b/packages/mcp/src/transport/discovery.ts
index f67ac352a..e58421d9a 100644
--- a/packages/mcp/src/transport/discovery.ts
+++ b/packages/mcp/src/transport/discovery.ts
@@ -1,9 +1,10 @@
-import { randomBytes } from 'node:crypto'
-import { access, constants, lstat, readFile, rename, unlink, writeFile } from 'node:fs/promises'
+import { access, constants, lstat, readFile, unlink } from 'node:fs/promises'
import { Socket } from 'node:net'
import * as v from 'valibot'
+import { writeFileAtomic } from '@open-pencil/core/node/fs'
+
import { MCP_TOOL_SCOPES, type MCPToolScope } from '#mcp/tool/scope'
import { getDiscoveryPath, getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'
@@ -55,11 +56,9 @@ export function parseDiscoveryInfo(raw: string): DiscoveryInfo | null {
* Writes the discovery JSON file at the platform-appropriate location.
* Overwrites any existing file (from a previous server instance).
*
- * The write is atomic: a sibling temp file is written first with `0o600`
- * permissions, then renamed over the final path. This avoids leaving
- * a half-written file visible to readers if the process is killed
- * mid-write, and prevents concurrent writers from corrupting the file
- * by interleaving their writes.
+ * The file is written all at once with `0o600` permissions, replacing a symlink at the path
+ * rather than writing through it, so readers never see half a file and concurrent writers never
+ * interleave.
*
* WARNING: The auth token is written in plaintext. Do not sync the discovery
* file to cloud storage or include it in backups without encryption.
@@ -67,17 +66,7 @@ export function parseDiscoveryInfo(raw: string): DiscoveryInfo | null {
export async function writeDiscoveryFile(info: DiscoveryInfo): Promise<void> {
const path = await getDiscoveryPath()
const json = JSON.stringify(info, null, 2)
- // Add a random component to guarantee uniqueness
- const random = randomBytes(6).toString('hex')
- const tmpPath = `${path}.${process.pid}.${random}.tmp`
- await writeFile(tmpPath, json, { mode: 0o600, encoding: 'utf-8' })
- try {
- await rename(tmpPath, path)
- } catch (err) {
- // Best-effort cleanup of the temp file on rename failure
- await unlink(tmpPath).catch(() => undefined)
- throw err
- }
+ await writeFileAtomic(path, json, { mode: 0o600 })
}
/**