A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): an organization can be deleted (#803)
Myriad-Dreamin3cb7d6100e3e
diff --git a/changelog/unreleased/2026-09-20-organization-delete.md b/changelog/unreleased/2026-09-20-organization-delete.mdnew file mode 100644index 00000000..9731ceff--- /dev/null+++ b/changelog/unreleased/2026-09-20-organization-delete.md@@ -0,0 +1,15 @@+# Company mode: an organization can be deleted++- **Date:** 2026-09-20+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#803](https://github.com/Prism-Shadow/penguin-harness/pull/803)++[中文版](2026-09-20-organization-delete.zh.md)++Pausing was an organization's whole lifecycle: there was no way to make one go away short of removing its directory by hand. The Project's owner can now delete one.++- `DELETE /api/projects/:projectId/organizations/:orgId` — owner only, like deleting an Agent (a member gets 403); `204` on success, `404` for an organization that does not exist.+- **Only the organization goes.** Its directory moves, whole, to the Project's trash — `organizations/.trash/<orgId>-<timestamp>/` — so a deletion can be undone by moving the directory back. Nothing lists a dot-directory: the organization disappears from every surface. Its id can be used again once the old CEO's Agent (`<orgId>_ceo`, kept like every employee) has been deleted or the new organization takes another id. The rows the server derived from it (session ownership, calendar and ticket state, read cursors, pending desk notices, budget state) are removed with it, so a new organization under the same id inherits nothing.+- **What it had stays.** Its employees remain Agents of the Project with everything they learned. Its desk and ticket Sessions are kept and stay marked as an organization's, so they do not spill into development mode's list — with the organization gone, no page lists them any more.+- Web: the organization's Settings dialog ends with a "Delete organization" row. The confirmation says what goes and what stays, points at pausing as the way to stop an organization without losing anything, and is armed by typing the organization's id.diff --git a/changelog/unreleased/2026-09-20-organization-delete.zh.md b/changelog/unreleased/2026-09-20-organization-delete.zh.mdnew file mode 100644index 00000000..4c909021--- /dev/null+++ b/changelog/unreleased/2026-09-20-organization-delete.zh.md@@ -0,0 +1,15 @@+# 公司模式:组织可以删除++- **Date:** 2026-09-20+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#803](https://github.com/Prism-Shadow/penguin-harness/pull/803)++[English](2026-09-20-organization-delete.md)++此前启停就是组织的全部生命周期:除了手工移除它的目录,没有办法让一个组织消失。现在 Project 的 owner 可以删除组织。++- `DELETE /api/projects/:projectId/organizations/:orgId`——仅 owner,与删除 Agent 同一口径(成员得到 403);成功为 `204`,组织不存在为 `404`。+- **只删组织本身。** 它的目录整个移入 Project 的回收目录——`organizations/.trash/<orgId>-<时间戳>/`——因此把目录移回来即可撤销删除。以点开头的目录不会被任何地方列出:组织从所有界面消失。旧 CEO 的 Agent(`<orgId>_ceo`,与其他员工一样被保留)删除之后,这个 id 才能再次用于新组织,否则请换一个 id。服务端由它派生的行(会话归属、日程与工单状态、已读游标、待送达的工位通知、预算状态)随之删除,同 id 的新组织不会继承任何东西。+- **它拥有的东西原样保留。** 员工仍是 Project 的 Agent,学到的一切都在。工位与工单会话保留,并继续带着「属于组织」的标记,因而不会散落到开发模式的列表里——组织不在了,也就没有页面再列出它们。+- Web:组织的设置弹窗末尾新增「删除组织」一行。确认框说明删什么、留什么,指出「只想让组织停下来而不丢任何东西」应当用暂停,并要求输入组织 id 才能确认。diff --git a/packages/server/src/http/routes/organizations.ts b/packages/server/src/http/routes/organizations.tsindex fd8d85c1..2c148df2 100644--- a/packages/server/src/http/routes/organizations.ts+++ b/packages/server/src/http/routes/organizations.ts@@ -2,6 +2,7 @@* Company-mode routes, nested under a Project:* GET|POST /api/projects/:p/organizations* GET|PATCH /api/projects/:p/organizations/:orgId+ * DELETE …/:orgId # owner only; to the Project's trash* GET …/:orgId/chart* POST …/:orgId/employees # hire* PATCH|DELETE …/:orgId/employees/:agentId@@ -167,7 +168,7 @@ function requireChannelParam(c: Context<AppEnv>): string {/** What this route group needs — declared here, at the consumer. */export interface OrgRouteDeps {orgService: OrgService;- projectService: Pick<ProjectLifecycle, "requireProjectAccess">;+ projectService: Pick<ProjectLifecycle, "requireProjectAccess" | "requireProjectOwner">;serverSettingsRepo: Pick<Settings, "getCompanyMode">;}@@ -275,6 +276,17 @@ export function organizationRoutes(deps: OrgRouteDeps): Hono<AppEnv> {// ---- employees ----+ // Deleting is a Project-level management operation, like deleting an Agent: owner only.+ // The organization itself is what goes (to the Project's trash); its employees' Agents and+ // its Sessions are left as they are.+ app.delete("/:orgId", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const orgId = requireValidId(c, "orgId");+ await deps.orgService.delete(projectId, orgId);+ return c.body(null, 204);+ });+app.get("/:orgId/chart", async (c) => {const projectId = requireValidId(c, "projectId");const orgId = requireValidId(c, "orgId");diff --git a/packages/server/src/organization/store.ts b/packages/server/src/organization/store.tsindex 07e3563d..d45a7af2 100644--- a/packages/server/src/organization/store.ts+++ b/packages/server/src/organization/store.ts@@ -112,6 +112,9 @@ async function writeText(p: string, text: string): Promise<void> {await fs.writeFile(p, text, "utf8");}+/** Where deleted organizations go, under a Project's `organizations/`. */+export const TRASH_DIR = ".trash";+export class OrgStore {constructor(readonly root: string) {}@@ -179,6 +182,20 @@ export class OrgStore {await fs.rm(dir, { recursive: true, force: true });}+ /**+ * Takes an organization out of the Project without destroying it: its directory moves to+ * `organizations/.trash/<orgId>-<stamp>/`, whole. Nothing lists a dot-directory, so the+ * organization is gone from every surface; moving the directory+ * back is how it is restored. Returns where it went.+ */+ async trash(projectId: string, orgId: string, stamp: string): Promise<string> {+ const bin = path.join(organizationsDir(this.root, projectId), TRASH_DIR);+ await fs.mkdir(bin, { recursive: true });+ const target = path.join(bin, `${orgId}-${stamp.replace(/[^0-9A-Za-z]/g, "")}`);+ await fs.rename(this.dir(projectId, orgId), target);+ return target;+ }+// ---- org_config.toml / org_chart.yaml / desks.toml / handbook/ ----async readConfig(dir: string): Promise<OrgFile<OrgConfig> | null> {diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.tsindex 1420d422..83897bbe 100644--- a/packages/server/src/runtime/organization/service.ts+++ b/packages/server/src/runtime/organization/service.ts@@ -628,6 +628,30 @@ export class OrganizationService {return this.detail(projectId, orgId, userId);}+ /**+ * Deletes the organization — and ONLY the organization: its directory goes to the Project's+ * trash (store.trash), whole and restorable, and the rows this server derived from it go+ * with it, since a new organization under the same id must not inherit+ * another's read cursors, calendar state or pending notices.+ *+ * What it had is left exactly as it is. Its employees stay Agents of the Project, with+ * everything they learned. Its desk and ticket Sessions stay too, still marked as an+ * organization's (`client = org`), so they do not spill into development mode's list;+ * with the organization gone no page lists them either, which is the price of not+ * deleting conversations along with a company.+ *+ * Under the organization's lock, so a pass in flight finishes first and the next one finds+ * no directory — the same state a hand-removed directory always was.+ */+ async delete(projectId: string, orgId: string): Promise<void> {+ await this.requireOrg(projectId, orgId);+ await this.scheduler.withLock(projectId, orgId, async () => {+ await this.deps.store.trash(projectId, orgId, new Date(this.now()).toISOString());+ this.deps.cache.deleteOrg(projectId, orgId);+ });+ this.deps.log?.(`[organization] ${projectId}/${orgId} deleted (moved to the trash)`);+ }+async patch(projectId: string,orgId: string,@@ -2641,6 +2665,7 @@ export abstract class OrgService extends Interface<| "list"| "create"| "detail"+ | "delete"| "patch"| "leave"| "suggestId"diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.tsindex 136d0764..e37d118f 100644--- a/packages/server/test/organization-runtime.test.ts+++ b/packages/server/test/organization-runtime.test.ts@@ -2569,6 +2569,43 @@ describe("organization runtime", () => {expect(list.desks.map((d) => d.sessionId)).toEqual([renewed.sessionId]);});+ it("deletes the organization and nothing else: its files to the trash, its Agents and Sessions left alone", async () => {+ await createOrg();+ const desk = await service.desk(P, ORG, CEO, {});+ await service.createTicket(+ P,+ ORG,+ { title: "Goes with the company", owner: `agent:${CEO}` },+ { userId: "alice" },+ );+ await service.delete(P, ORG);++ // Gone from every surface.+ expect((await service.list(P)).map((o) => o.orgId)).toEqual([]);+ await expect(service.detail(P, ORG, "alice")).rejects.toMatchObject({ status: 404 });+ await expect(service.delete(P, ORG)).rejects.toMatchObject({ status: 404 });+ // Whole, in the Project's trash: moving the directory back is how it is restored.+ const bin = path.join(path.dirname(store.dir(P, ORG)), ".trash");+ const [kept] = await fs.readdir(bin);+ expect(kept).toMatch(new RegExp(`^${ORG}-\\d{8}T\\d+Z$`));+ expect(await fs.readFile(path.join(bin, kept!, "org_chart.yaml"), "utf8")).toContain(CEO);+ // What this server derived from it went with it; what it HAD did not.+ expect(cache.ownerOfSession(desk.sessionId)).toBeNull();+ expect(sessions.findById(desk.sessionId)).not.toBeNull();+ expect(existingAgents.has(CEO)).toBe(true);+ // A pass over the Project finds nothing to drive and nothing to complain about.+ const before = created.length;+ await scheduler.tickOnce();+ expect(created).toHaveLength(before);+ expect(errors).toEqual([]);+ // The id itself is free, but its CEO's Agent was kept — and a new organization's CEO+ // is `<orgId>_ceo`. Reusing the id means letting that Agent go first.+ await expect(createOrg()).rejects.toMatchObject({ status: 409, code: "agent_exists" });+ existingAgents.delete(CEO);+ await createOrg();+ expect((await service.list(P)).map((o) => o.orgId)).toEqual([ORG]);+ });+it("rebuilds the session caches from the files after they are dropped", async () => {await createOrg();const desk = await service.desk(P, ORG, CEO, {});diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.tsindex f0506c7c..4fc34c44 100644--- a/packages/server/test/organizations-routes.test.ts+++ b/packages/server/test/organizations-routes.test.ts@@ -1,8 +1,8 @@/*** Organization routes over the real app: the admin master switch starts off, 404s the whole* group while it is off, and is reported by /api/me and /api/admin/settings; Project- * authorization gates reads and writes (an outsider gets 404, a member may write), and no- * route deletes an organization; bodies are validated before the service is asked; and the+ * authorization gates reads and writes (an outsider gets 404, a member may write) and only+ * the owner deletes an organization; bodies are validated before the service is asked; and the* calling session and employee ride write bodies as `sessionId` / `agentId` (a read's query* string), but only from the control environment's API token — a signed-in member's claim is* dropped. The service itself is a recording fake here — its semantics have their@@ -185,13 +185,17 @@ describe("organization routes", () => {});});- it("has no route that deletes an organization", async () => {- // Pause is the whole lifecycle. DELETE is not a route, so the Project's own owner gets 404- // and the service is never asked; pausing is a PATCH like any other setting.- expect((await owner.delete(`/api/projects/${ownerProject}/organizations/acme`)).status).toBe(- 404,- );+ it("deletes an organization for the Project's owner only; pausing stays a setting", async () => {+ // A Project-level management operation, like deleting an Agent: a member who can write+ // everything else in the organization cannot make it go away.+ const path = `/api/projects/${ownerProject}/organizations/acme`;+ const mia = await provisionUser(t.app, "mia");+ await owner.post(`/api/projects/${ownerProject}/members`, { userId: "mia" });+ calls.length = 0;+ expect((await apiClient(t.app, mia.cookie).delete(path)).status).toBe(403);expect(calls).toEqual([]);+ expect((await owner.delete(path)).status).toBe(204);+ expect(calls.at(-1)).toEqual({ method: "delete", args: [ownerProject, "acme"] });const patch = await owner.patch(`/api/projects/${ownerProject}/organizations/acme`, {status: "paused",});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex b34394b3..8e73ecbf 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1757,6 +1757,13 @@ export const patchOrganization = (body: OrganizationPatchRequest,) => apiFetch<OrganizationSettings>(orgBase(projectId, orgId), { method: "PATCH", body });+/**+ * Owner only. The organization itself goes — to the Project's trash, restorable by hand; its+ * employees' Agents and its desk and ticket Sessions are left as they are.+ */+export const deleteOrganization = (projectId: string, orgId: string) =>+ apiFetch<void>(orgBase(projectId, orgId), { method: "DELETE" });+export const getOrgChart = (projectId: string, orgId: string) =>apiFetch<OrgChartResponse>(`${orgBase(projectId, orgId)}/chart`);diff --git a/packages/web/src/features/company/org-dialogs.tsx b/packages/web/src/features/company/org-dialogs.tsxindex adf0ebb9..f34b6d2b 100644--- a/packages/web/src/features/company/org-dialogs.tsx+++ b/packages/web/src/features/company/org-dialogs.tsx@@ -52,6 +52,7 @@ import { Input, Textarea } from "../../components/ui/input";import { Select } from "../../components/ui/select";import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";import { Modal } from "../../components/ui/modal";+import { ConfirmModal } from "../../components/ui/confirm-modal";import { InfoPopover } from "../../components/ui/info-popover";import { toastError, toastSuccess } from "../../components/ui/toast";import { ICON_GAP } from "../../lib/icon-scale";@@ -575,6 +576,7 @@ export function OrganizationSettingsDialog({orgId,onClose,onChanged,+ onDeleted,}: {open: boolean;projectId: string;@@ -582,6 +584,8 @@ export function OrganizationSettingsDialog({onClose: () => void;/** Settings were written (name, mission, status …): the caller refreshes the list. */onChanged: () => void;+ /** The organization was deleted: the caller refreshes the list and leaves its pages. */+ onDeleted?: () => void;}) {/** Stored settings as loaded on open (null until then) — the no-change baseline. */const [settings, setSettings] = useState<OrganizationSettings | null>(null);@@ -594,8 +598,26 @@ export function OrganizationSettingsDialog({const [modelRef, setModelRef] = useState<ModelRefDto | null>(null);const [workspace, setWorkspace] = useState("");const [busy, setBusy] = useState(false);+ /** The delete confirmation, and what has been typed into it (the id, to mean it). */+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [typedId, setTypedId] = useState("");const { models, error: modelsError } = useProjectModels(projectId, open);+ const doDelete = async () => {+ setBusy(true);+ try {+ await api.deleteOrganization(projectId, orgId);+ setConfirmDelete(false);+ toastSuccess(S.company.deleted(orgId));+ onClose();+ onDeleted?.();+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setBusy(false);+ }+ };+const adopt = (next: OrganizationSettings) => {setSettings(next);setName(next.name);@@ -786,7 +808,47 @@ export function OrganizationSettingsDialog({))}</Select></div>+ {/* Deleting is its own decision, below everything Save writes: immediate, confirmed by+ typing the id, and refused by the server for anyone but the Project's owner. */}+ <div className="flex items-center justify-between gap-3 border-t border-gray-200 pt-3 dark:border-gray-800">+ <span className="min-w-0">+ <span className="block text-xs font-semibold text-gray-600 dark:text-gray-400">+ {S.company.deleteOrg}+ </span>+ <FieldHint>{S.company.deleteOrgDesc}</FieldHint>+ </span>+ <Button+ size="sm"+ variant="danger"+ disabled={!hydrated || busy}+ onClick={() => {+ setTypedId("");+ setConfirmDelete(true);+ }}+ >+ {S.common.delete}+ </Button>+ </div></div>+ <ConfirmModal+ open={confirmDelete}+ title={S.company.deleteOrg}+ busy={busy}+ confirmDisabled={typedId.trim() !== orgId}+ onClose={() => setConfirmDelete(false)}+ onConfirm={() => void doDelete()}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">{S.company.deleteOrgConfirm}</p>+ <Input+ size="sm"+ className="mt-3 font-mono"+ aria-label={S.company.deleteOrgTypeId(orgId)}+ placeholder={orgId}+ value={typedId}+ hint={S.company.deleteOrgTypeId(orgId)}+ onChange={(e) => setTypedId(e.target.value)}+ />+ </ConfirmModal></Modal>);}diff --git a/packages/web/src/features/company/org-switcher.tsx b/packages/web/src/features/company/org-switcher.tsxindex 38b37ac6..b064150c 100644--- a/packages/web/src/features/company/org-switcher.tsx+++ b/packages/web/src/features/company/org-switcher.tsx@@ -233,6 +233,9 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {orgId={settingsTarget.orgId}onClose={() => setSettingsOpen(false)}onChanged={() => void company.reloadOrganizations()}+ // The list drops it, and the shell then moves off its pages by itself (the settled+ // listing no longer holds the current organization).+ onDeleted={() => void company.reloadOrganizations()}/>)}</>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 5e88219d..4c75d23b 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4023,6 +4023,13 @@ Scenarios:statusPaused: "Paused",pause: "Pause organization",resume: "Resume organization",+ deleteOrg: "Delete organization",+ deleteOrgDesc:+ "Moves the organization to the Project's trash. Its employees stay as Agents and its conversations are kept.",+ deleteOrgConfirm:+ "The organization disappears from company mode. Its files go to the Project's trash (organizations/.trash) and can be moved back by hand. Its employees remain Agents of the Project; its desk and ticket conversations are kept, but with the organization gone no page lists them any more. Its id can be reused only after the old CEO's Agent is deleted. To stop an organization without losing anything, pause it instead.",+ deleteOrgTypeId: (orgId: string) => `Type ${orgId} to confirm`,+ deleted: (orgId: string) => `Organization ${orgId} deleted`,pauseInfo:"Paused stops every automatic trigger — calendar events no longer fire and @-mentions are not delivered to employees; you can still open any desk session and talk directly. An organization is paused, never deleted: its conversations, employees and tickets stay reachable.",settingsLoadFailed: "The organization's settings could not be read",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 040100a4..6f2047aa 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4039,6 +4039,12 @@ Benchmark:statusPaused: "已暂停",pause: "暂停组织",resume: "恢复组织",+ deleteOrg: "删除组织",+ deleteOrgDesc: "把组织移入 Project 的回收目录。员工保留为 Agent,对话也保留。",+ deleteOrgConfirm:+ "组织会从公司模式里消失。组织的文件移入 Project 的回收目录(organizations/.trash),可以手工移回来恢复。员工仍是 Project 的 Agent;工位与工单的对话会保留,但组织不在了,就没有页面再列出它们。要再次使用这个 id,需先删除旧 CEO 的 Agent。只是想让组织停下来而不丢任何东西,请改用暂停。",+ deleteOrgTypeId: (orgId: string) => `输入 ${orgId} 以确认`,+ deleted: (orgId: string) => `组织 ${orgId} 已删除`,pauseInfo:"暂停后所有自动触发停止——日程不再到点、@ 不再送达员工;你仍可以打开任意工位会话直接对话。组织只会被暂停,不会被删除:它的对话、员工与工单始终可以回去看。",settingsLoadFailed: "组织设置读取失败",