#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix: replace confined files only after the new content is written
Rohit Ghumaree03390303be7
diff --git a/src/functions/path-guard.ts b/src/functions/path-guard.tsindex 3ec4419b..9bb37440 100644--- a/src/functions/path-guard.ts+++ b/src/functions/path-guard.ts@@ -1,5 +1,6 @@import { constants } from "node:fs";-import { mkdir, open, realpath } from "node:fs/promises";+import { randomBytes } from "node:crypto";+import { lstat, mkdir, open, realpath, rename, rm } from "node:fs/promises";import { homedir } from "node:os";import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";@@ -81,7 +82,7 @@ export async function confinePath(};}-const WRITE_NO_FOLLOW = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW;+const CREATE_EXCLUSIVE_NO_FOLLOW = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;async function requireConfined(path: string, roots: string[]): Promise<string> {const confined = await confinePath(path, roots);@@ -97,11 +98,23 @@ export async function mkdirConfined(dir: string, roots: string[]): Promise<strinexport async function writeConfinedFile(path: string, content: string, roots: string[]): Promise<string> {const target = await requireConfined(path, roots);- const handle = await open(target, WRITE_NO_FOLLOW);+ const existing = await lstat(target).catch((err: NodeJS.ErrnoException) => {+ if (err.code === "ENOENT") return null;+ throw err;+ });+ if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a symbolic link: ${target}`);+ const temp = await requireConfined(join(dirname(target), `.${basename(target)}.${randomBytes(6).toString("hex")}.tmp`), roots);try {- await handle.writeFile(content, "utf-8");- } finally {- await handle.close();+ const handle = await open(temp, CREATE_EXCLUSIVE_NO_FOLLOW, existing ? existing.mode & 0o777 : 0o644);+ try {+ await handle.writeFile(content, "utf-8");+ } finally {+ await handle.close();+ }+ await rename(temp, target);+ } catch (err) {+ await rm(temp, { force: true }).catch(() => {});+ throw err;}return target;}diff --git a/test/compress-file.test.ts b/test/compress-file.test.tsindex b66ef6a8..bb32499c 100644--- a/test/compress-file.test.ts+++ b/test/compress-file.test.ts@@ -7,6 +7,11 @@ vi.mock("../src/logger.js", () => ({const fileStore = new Map<string, string>();const symlinkPaths = new Set<string>();const openEloopPaths = new Set<string>();+const failWritePaths = new Set<string>();+const matches = (set: Set<string>, path: string) =>+ [...set].some((p) => path === p || path.startsWith(p.replace(/[^/]+$/, (name) => `.${name}.`)));++const { constants: fsConstants } = await vi.importActual<typeof import("node:fs")>("node:fs");vi.mock("node:fs/promises", () => ({realpath: vi.fn(async (path: string) => path),@@ -19,21 +24,34 @@ vi.mock("node:fs/promises", () => ({code: "ENOENT",});}- return { isSymbolicLink: () => false };+ return { isSymbolicLink: () => false, mode: 0o644 };}),- open: vi.fn(async (path: string) => {- if (openEloopPaths.has(path)) {+ open: vi.fn(async (path: string, flags?: number) => {+ if (typeof flags === "number" && (flags & fsConstants.O_TRUNC) && fileStore.has(path)) fileStore.set(path, "");+ if (matches(openEloopPaths, path)) {throw Object.assign(new Error("ELOOP: too many levels of symbolic links"), {code: "ELOOP",});}return {writeFile: vi.fn(async (content: string) => {+ if (matches(failWritePaths, path)) {+ throw Object.assign(new Error("ENOSPC: no space left on device"), { code: "ENOSPC" });+ }fileStore.set(path, content);}),close: vi.fn(async () => {}),};}),+ rename: vi.fn(async (from: string, to: string) => {+ const value = fileStore.get(from);+ if (value === undefined) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });+ fileStore.set(to, value);+ fileStore.delete(from);+ }),+ rm: vi.fn(async (path: string) => {+ fileStore.delete(path);+ }),readFile: vi.fn(async (path: string) => {const value = fileStore.get(path);if (value === undefined) throw new Error("ENOENT");@@ -98,6 +116,7 @@ describe("mem::compress-file", () => {fileStore.clear();symlinkPaths.clear();openEloopPaths.clear();+ failWritePaths.clear();sdk = mockSdk();kv = mockKV();summarize = vi.fn();@@ -137,6 +156,21 @@ describe("mem::compress-file", () => {expect(result.error).toContain("symlink");});+ it("keeps the original file when writing the compressed version fails", async () => {+ const path = "/tmp/notes.md";+ const original = "# Title\n\nVisit https://example.com\n\n```ts\nconst x = 1;\n```\n\nContent.";+ fileStore.set(path, original);+ summarize.mockResolvedValue("# Title\n\nVisit https://example.com\n\n```ts\nconst x = 1;\n```\n\nShort.");+ failWritePaths.add(path);++ const result = (await sdk.trigger("mem::compress-file", {+ filePath: path,+ })) as { success: boolean };+ expect(result.success).toBe(false);+ expect(fileStore.get(path)).toBe(original);+ expect([...fileStore.keys()].filter((k) => k.endsWith(".tmp"))).toEqual([]);+ });+it("rejects non-markdown paths", async () => {const result = (await sdk.trigger("mem::compress-file", {filePath: "/tmp/readme.txt",diff --git a/test/obsidian-export.test.ts b/test/obsidian-export.test.tsindex 92a3ac36..ba3d5142 100644--- a/test/obsidian-export.test.ts+++ b/test/obsidian-export.test.ts@@ -15,12 +15,27 @@ vi.mock("node:fs/promises", () => ({writeFile: vi.fn(async (path: string, content: string) => {writtenFiles.set(path, content);}),+ lstat: vi.fn(async (path: string) => {+ if (!writtenFiles.has(path)) {+ throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });+ }+ return { isSymbolicLink: () => false, mode: 0o644 };+ }),open: vi.fn(async (path: string) => ({writeFile: vi.fn(async (content: string) => {writtenFiles.set(path, content);}),close: vi.fn(async () => {}),})),+ rename: vi.fn(async (from: string, to: string) => {+ const value = writtenFiles.get(from);+ if (value === undefined) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });+ writtenFiles.set(to, value);+ writtenFiles.delete(from);+ }),+ rm: vi.fn(async (path: string) => {+ writtenFiles.delete(path);+ }),}));import { registerObsidianExportFunction } from "../src/functions/obsidian-export.js";