A local-first multi-agent app development platform, built on PenguinHarness
fix(server): an organization's creation layout is written under the org lock
lmliheng8a96b8b0f46c
diff --git a/changelog/unreleased/2026-10-13-org-create-under-lock.md b/changelog/unreleased/2026-10-13-org-create-under-lock.mdnew file mode 100644index 00000000..65fa70d1--- /dev/null+++ b/changelog/unreleased/2026-10-13-org-create-under-lock.md@@ -0,0 +1,23 @@+# Creating an organization writes its layout under the organization's lock++- **Date:** 2026-10-13+- **Type:** fix+- **Scope:** `server`++[中文版](2026-10-13-org-create-under-lock.zh.md)++Ported from upstream PenguinHarness (#957, commit `10b43edc`).++Creating an organization now writes its directory layout — the skeleton, `org_config.toml`,+`org_chart.yaml`, the handbook — and creates the CEO's Agent under the same lock a delete holds+while it moves the directory to the trash. The pre-checks (the id, the mission, the timezone,+a free id) still run before the lock.++Before this, a delete landing in the milliseconds between create's first written file and its+lock passed its own guard, moved the half-made directory away, and left create writing the chart+and the handbook beside a config that was no longer there: a directory no listing shows, a CEO+Agent holding the id against reuse, and a not-found for the caller who had just watched the+create succeed. Now a delete arriving mid-creation waits, and then finds either no directory or+the finished whole — the same two states a delete after a completed create always had.++No API, wire format or stored data changes.diff --git a/changelog/unreleased/2026-10-13-org-create-under-lock.zh.md b/changelog/unreleased/2026-10-13-org-create-under-lock.zh.mdnew file mode 100644index 00000000..7bed9ba7--- /dev/null+++ b/changelog/unreleased/2026-10-13-org-create-under-lock.zh.md@@ -0,0 +1,15 @@+# 创建组织时在组织的锁内写入目录布局++- **Date:** 2026-10-13+- **Type:** fix+- **Scope:** `server`++[English](2026-10-13-org-create-under-lock.md)++移植自上游 PenguinHarness(#957,提交 `10b43edc`)。++创建组织现在在组织的锁内写入目录布局——骨架、`org_config.toml`、`org_chart.yaml`、手册——并创建 CEO 的 Agent;删除组织把目录移入回收站时持有的正是同一把锁。前置检查(id、使命、时区、id 是否空闲)仍在加锁前进行。++在此之前,一次落在「创建写出第一个文件」与「加锁」之间那几毫秒里的删除能通过自己的守卫、把写了一半的目录移走,让创建继续在一份已不存在的配置旁写图表与手册:留下一个任何列表都不显示的目录、一个占着该 id 的 CEO Agent,以及给调用者一个「未找到」——而他刚刚看着创建成功。现在创建进行中到达的删除会等待,随后看到的要么是尚不存在的目录,要么是完整的组织,与「创建完成后再删除」本就只有的这两种状态一致。++接口、线上格式与已存数据都没有变化。diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.tsindex 8414da19..a38913e2 100644--- a/packages/server/src/runtime/organization/service.ts+++ b/packages/server/src/runtime/organization/service.ts@@ -569,53 +569,59 @@ export class OrganizationService {...(req.model !== undefined ? { model: req.model } : {}),};const dir = this.deps.store.dir(projectId, orgId);- await this.deps.store.createLayout(dir, new Date(this.now()).toISOString());- try {- await this.deps.store.writeConfig(dir, config);- await this.deps.store.writeChart(dir, {- employees: [- {+ // The layout is written under the organization's lock — the same one a delete holds when+ // it moves the directory to the trash. Unlocked, a delete landing between the exists+ // check above and the lock below would move the half-made directory away and leave this+ // method writing chart and handbook beside a config that is no longer there.+ await this.scheduler.withLock(projectId, orgId, async () => {+ await this.deps.store.createLayout(dir, new Date(this.now()).toISOString());+ try {+ await this.deps.store.writeConfig(dir, config);+ await this.deps.store.writeChart(dir, {+ employees: [+ {+ agentId: ceo,+ title: "CEO",+ reportsTo: null,+ duties:+ language === "zh"+ ? "把使命拆成工单、招募、划分公共工作区、审核工单、向董事会汇报"+ : "Turn the mission into tickets, hire, partition the shared workspace, review tickets, report to the board",+ workspace: CEO_WORKSPACE,+ // Compared on the cumulative line, so this one number is the whole company's cap.+ budget: req.ceoBudget ?? DEFAULT_CEO_BUDGET,+ },+ ],+ });+ await this.deps.store.writeHandbook(+ dir,+ renderHandbook({ orgId, name, mission, ceoAgentId: ceo, createdBy: userId, language }),+ );+ await this.deps.agents.create(+ projectId,+ ceo,+ `${name} CEO`,+ `CEO of ${name}`,+ DEFAULT_EMPLOYEE_PLUGINS,+ );+ await this.deps.agents.writeAgentsMd(+ projectId,+ ceo,+ employeeBrief({+ orgId,+ name,+ mission,agentId: ceo,title: "CEO",reportsTo: null,- duties:- language === "zh"- ? "把使命拆成工单、招募、划分公共工作区、审核工单、向董事会汇报"- : "Turn the mission into tickets, hire, partition the shared workspace, review tickets, report to the board",- workspace: CEO_WORKSPACE,- // Compared on the cumulative line, so this one number is the whole company's cap.- budget: req.ceoBudget ?? DEFAULT_CEO_BUDGET,- },- ],- });- await this.deps.store.writeHandbook(- dir,- renderHandbook({ orgId, name, mission, ceoAgentId: ceo, createdBy: userId, language }),- );- await this.deps.agents.create(- projectId,- ceo,- `${name} CEO`,- `CEO of ${name}`,- DEFAULT_EMPLOYEE_PLUGINS,- );- await this.deps.agents.writeAgentsMd(- projectId,- ceo,- employeeBrief({- orgId,- name,- mission,- agentId: ceo,- title: "CEO",- reportsTo: null,- language,- }),- );- } catch (err) {- await this.deps.store.remove(dir);- throw err;- }+ language,+ }),+ );+ } catch (err) {+ await this.deps.store.remove(dir);+ throw err;+ }+ });await this.scheduler.withLock(projectId, orgId, async () => {const org = await this.requireValidOrg(projectId, orgId);const spend = await computeSpend(this.deps, org, []);diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.tsindex 71bf7cca..4d965114 100644--- a/packages/server/test/organization-runtime.test.ts+++ b/packages/server/test/organization-runtime.test.ts@@ -12,6 +12,7 @@* Session (`source: "company"`) stamped with the `org` client; and every pass brings an* employee whose company plugins fell behind the library back up to it.*/+import { existsSync } from "node:fs";import fs from "node:fs/promises";import { wire } from "@lmliheng/penguin-core/kernel";import path from "node:path";@@ -579,6 +580,59 @@ describe("organization runtime", () => {).rejects.toMatchObject({ code: "invalid_org_id" });});+ it("writes the creation layout under the org lock, so a delete landing mid-creation cannot leave a half-made directory behind", async () => {+ // A delete cannot be timed into the real millisecond window, so the test opens one: the+ // first writeConfig fires a delete, and — while the layout is written unlocked — holds+ // create right there until the trash rename has landed, the worst point the race allows.+ // Under the lock the hold is skipped (create is inside it) and the delete queues behind+ // the layout instead: the directory is then moved whole, or not at all.+ const realWriteConfig = store.writeConfig.bind(store);+ const realTrash = store.trash.bind(store);+ const realWithLock = scheduler.withLock.bind(scheduler);+ let trashLanded: () => void = () => {};+ const trashDone = new Promise<void>((resolve) => {+ trashLanded = resolve;+ });+ let insideOrgLock = false;+ scheduler.withLock = ((projectId: string, orgId: string, fn: () => Promise<unknown>) =>+ realWithLock(projectId, orgId, async () => {+ const restore = insideOrgLock;+ if (projectId === P && orgId === ORG) insideOrgLock = true;+ try {+ return await fn();+ } finally {+ insideOrgLock = restore;+ }+ })) as typeof scheduler.withLock;+ store.trash = async (projectId, orgId, stamp) => {+ const target = await realTrash(projectId, orgId, stamp);+ trashLanded();+ return target;+ };+ let triggered = false;+ store.writeConfig = async (dir, cfg) => {+ await realWriteConfig(dir, cfg);+ if (triggered) return;+ triggered = true;+ void service.delete(P, ORG).catch(() => {});+ const wasInsideLock = insideOrgLock;+ if (!wasInsideLock) await trashDone;+ };++ await expect(+ service.create(P, { orgId: ORG, mission: "Build it" }, "alice"),+ ).rejects.toMatchObject({ status: 404, code: "org_not_found" });+ // The delete may still be queued behind the layout when create fails; wait it out so the+ // assertions below see the final state of the directory either way.+ await trashDone;+ // Either way the caller loses the organization. What must never happen is the leftover:+ // a directory without its config, which every listing skips while the CEO Agent it+ // already created keeps the id from being reused.+ expect(await store.exists(P, ORG)).toBe(false);+ expect(existsSync(orgDir())).toBe(false);+ expect(existingAgents.has(CEO)).toBe(true);+ });+it("hires through the API, writes the chart and announces it in the all-hands channel", async () => {await createOrg();await fs.mkdir(path.join(orgDir(), "workspace", "people"));