Skip to content

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

fix(server): make the org store's writes atomic and a crashed move survivable

lmliheng479c3151cd46
diff --git a/changelog/unreleased/2026-10-11-org-store-atomic-write.md b/changelog/unreleased/2026-10-11-org-store-atomic-write.md
new file mode 100644
index 00000000..da3f7090
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-org-store-atomic-write.md
@@ -0,0 +1,11 @@
+# The organization store writes atomically and keeps a ticket a crash left in two columns
+
+- **Date:** 2026-10-11
+- **Type:** fix
+- **Scope:** `server`
+
+[中文版](2026-10-11-org-store-atomic-write.zh.md)
+
+Ported from upstream PenguinHarness (#850, commit `ebd9d8d2`).
+
+Every file the organization store writes — `org_config.toml`, `org_chart.yaml`, tickets, channels, calendar events, the handbook — now goes through the core's `atomicWriteFile`, a uniquely named temp file renamed into place, so a crash mid-write cannot leave a truncated file that reconcile would report as invalid and drop from the board. `moveTicket` no longer swallows a failed removal of the old column's file; only an already-missing file passes. A ticket id found in two columns — a crash between the move's write and its unlink — keeps its newest copy on the board, and the stale copy is reported under invalid files instead of both copies disappearing.
diff --git a/changelog/unreleased/2026-10-11-org-store-atomic-write.zh.md b/changelog/unreleased/2026-10-11-org-store-atomic-write.zh.md
new file mode 100644
index 00000000..cb947adb
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-org-store-atomic-write.zh.md
@@ -0,0 +1,11 @@
+# 组织存储原子写文件,并保留崩溃后同时出现在两列的工单
+
+- **Date:** 2026-10-11
+- **Type:** fix
+- **Scope:** `server`
+
+[English](2026-10-11-org-store-atomic-write.md)
+
+移植自上游 PenguinHarness(#850,提交 `ebd9d8d2`)。
+
+组织存储写出的每个文件——`org_config.toml`、`org_chart.yaml`、工单、频道、日程项、手册——现在都经由核心的 `atomicWriteFile` 写入:唯一命名的临时文件再重命名到位,写到一半崩溃不会再留下被对账判为非法并从看板移除的截断文件。`moveTicket` 不再吞掉旧列文件删除失败的错误,只放过文件本已不存在的情形。同一工单 id 出现在两列时——移动的写入与删除之间崩溃——看板保留最新的一份,过期的一份列入非法文件,而不是两份一起从看板消失。
diff --git a/packages/server/src/organization/store.ts b/packages/server/src/organization/store.ts
index d45a7af2..491330a2 100644
--- a/packages/server/src/organization/store.ts
+++ b/packages/server/src/organization/store.ts
@@ -6,6 +6,7 @@
*/
import fs from "node:fs/promises";
import path from "node:path";
+import { atomicWriteFile } from "@lmliheng/penguin-core";
import type { OrgChannelMessage, OrgTicketStatus } from "../api/types.js";
import type {
CalendarEvent,
@@ -109,7 +110,11 @@ async function readText(p: string): Promise<string | null> {
async function writeText(p: string, text: string): Promise<void> {
await fs.mkdir(path.dirname(p), { recursive: true });
- await fs.writeFile(p, text, "utf8");
+ // Atomic whole-file replacement (uniquely-named temp file + rename): a crash mid-write
+ // must not leave a truncated TOML/YAML/MD behind — an unparsable org file drops its
+ // ticket from the board (reconcile's listTickets), so the core's own state-file
+ // discipline applies here too.
+ await atomicWriteFile(p, text);
}
/** Where deleted organizations go, under a Project's `organizations/`. */
@@ -429,7 +434,15 @@ export class OrgStore {
doc: TicketDoc,
): Promise<void> {
await this.writeTicket(dir, ticketId, to, doc);
- if (from !== to) await fs.unlink(ticketPath(dir, ticketId, from)).catch(() => {});
+ if (from !== to) {
+ try {
+ await fs.unlink(ticketPath(dir, ticketId, from));
+ } catch (err) {
+ // Already gone is fine; anything else must not pass in silence — a quietly kept
+ // old column would leave the id in two columns for the reader to resolve.
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ }
+ }
}
// ---- channels ----
diff --git a/packages/server/src/runtime/organization/reconcile.ts b/packages/server/src/runtime/organization/reconcile.ts
index dac0ae13..391544ad 100644
--- a/packages/server/src/runtime/organization/reconcile.ts
+++ b/packages/server/src/runtime/organization/reconcile.ts
@@ -18,6 +18,7 @@ import type { ChannelConfig, TicketDoc } from "../../organization/files.js";
import { parseChannelMessageLine, serializeChannelMessageLine } from "../../organization/files.js";
import { agentPrincipal, parsePrincipal, principalAgentId } from "../../organization/principal.js";
import { DEFAULT_CHANNEL_ID } from "../../organization/paths.js";
+import type { TicketFile } from "../../organization/store.js";
import { zonedDate } from "../../organization/zoned.js";
import { latestSlotAt, slotInWindow } from "../schedule-file.js";
import { budgetLine, computeSpend, pausedEmployees } from "./budget.js";
@@ -59,20 +60,35 @@ function recordError(
});
}
-/** Every ticket file, parsed; an unparsable file or a duplicated id is reported and left out. */
+/** Every ticket file, parsed; an unparsable file is reported and left out, a duplicated id keeps its newest copy (the rest reported). */
export async function listTickets(deps: OrgDeps, org: LoadedOrg): Promise<TicketListing> {
const files = await deps.store.listTickets(org.dir);
- const seen = new Map<string, number>();
- for (const f of files) seen.set(f.ticketId, (seen.get(f.ticketId) ?? 0) + 1);
+ // A crash between moveTicket's write of the new column and its unlink of the old one
+ // leaves the id in two columns. Dropping both used to take the ticket off the board
+ // until someone edited files by hand; the newest file is the move's target (the new
+ // column is written before the old one is removed), so that copy is kept and the stale
+ // one is reported instead.
+ const keep = new Map<string, TicketFile>();
+ const stale = new Map<string, TicketFile[]>();
+ for (const f of files) {
+ const current = keep.get(f.ticketId);
+ if (current === undefined) {
+ keep.set(f.ticketId, f);
+ } else if (f.mtimeMs >= current.mtimeMs) {
+ stale.set(f.ticketId, [...(stale.get(f.ticketId) ?? []), current]);
+ keep.set(f.ticketId, f);
+ } else {
+ stale.set(f.ticketId, [...(stale.get(f.ticketId) ?? []), f]);
+ }
+ }
const tickets: LoadedTicket[] = [];
const invalid: Array<{ path: string; error: string }> = [];
- for (const f of files) {
- if ((seen.get(f.ticketId) ?? 0) > 1) {
+ for (const f of keep.values()) {
+ for (const s of stale.get(f.ticketId) ?? []) {
invalid.push({
- path: f.relPath,
- error: `ticket id ${f.ticketId} appears in more than one column`,
+ path: s.relPath,
+ error: `ticket id ${f.ticketId} appears in more than one column; keeping the newest copy (${f.relPath})`,
});
- continue;
}
if (!f.parsed.ok) {
invalid.push({ path: f.relPath, error: f.parsed.error });
diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.ts
index f21ccc2e..66ae6485 100644
--- a/packages/server/test/organization-runtime.test.ts
+++ b/packages/server/test/organization-runtime.test.ts
@@ -3120,4 +3120,75 @@ describe("organization runtime", () => {
expect(await service.list(P)).toHaveLength(1);
});
});
+
+ describe("crash-window robustness in the org store", () => {
+ const ticketFile = (ticketId: string, column: string): string =>
+ path.join(orgDir(), "tickets", ticketId.slice(0, 7), column, `${ticketId}.md`);
+
+ it("keeps a ticket on the board when a crash left it in two columns", async () => {
+ await createOrg();
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Duplicated by a crash", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ const raw = await fs.readFile(ticketFile(t.ticketId, "proposed"), "utf8");
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, { userId: "alice" });
+ // Recreate the crash window: the old column's file is back (its unlink never ran)
+ // and carries the older mtime, as it would in a real crash — the new column is
+ // written before the old one is removed.
+ await fs.writeFile(ticketFile(t.ticketId, "proposed"), raw, "utf8");
+ const stale = new Date(Date.now() - 60_000);
+ await fs.utimes(ticketFile(t.ticketId, "proposed"), stale, stale);
+
+ const board = await service.tickets(P, ORG);
+ expect(board.columns.in_progress.map((x) => x.ticketId)).toContain(t.ticketId);
+ expect(board.columns.proposed.map((x) => x.ticketId)).not.toContain(t.ticketId);
+ const dup = board.invalidFiles.filter((x) => x.path.includes(t.ticketId));
+ expect(dup).toHaveLength(1);
+ expect(dup[0]?.error).toContain("keeping the newest copy");
+ });
+
+ it("does not swallow a failing removal of the old column on a move", async () => {
+ await createOrg();
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Unremovable origin", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ // Store-level (the service's own ticket lookup would trip over the directory first):
+ // a directory parked where the old column's file lives makes the unlink fail, and
+ // the move must say so instead of leaving the id in two columns in silence.
+ const found = await store.findTicket(orgDir(), t.ticketId);
+ if (!found?.parsed.ok) throw new Error("the ticket file should be there and parsable");
+ const from = ticketFile(t.ticketId, "proposed");
+ await fs.rm(from);
+ await fs.mkdir(from);
+ try {
+ await expect(
+ store.moveTicket(orgDir(), t.ticketId, "proposed", "in_progress", found.parsed.value),
+ ).rejects.toThrow();
+ } finally {
+ await fs.rmdir(from);
+ }
+ });
+
+ it("leaves no temp files behind after ticket writes", async () => {
+ await createOrg();
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "No temp litter", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, { userId: "alice" });
+ const monthDir = path.join(orgDir(), "tickets", t.ticketId.slice(0, 7));
+ const names = (await fs.readdir(monthDir, { recursive: true })).map(String);
+ expect(names.filter((n) => n.includes(t.ticketId)).map((n) => path.basename(n))).toEqual([
+ `${t.ticketId}.md`,
+ ]);
+ });
+ });
});