import { isLifecycleState, LifecycleError, setLifecycle } from "@/lib/lifecycle"; import { parsePieceId, readPieceGraph } from "@/lib/pieces"; import { clearRailCounts } from "@/lib/rail"; export const dynamic = "force-dynamic"; // Park a piece, mark it done, or make it active again (lib/lifecycle.ts). // // POST { piece: "a:/" | "p:", state: "active" | "parked" | "done" } // → { piece, state, at, by } // // 400 for a body that is not a piece id and a state; 404 for a piece nothing on // disk is (a research case `c:` is reserved until research boards exist); 409 // when lifecycle.json does not parse (it is never overwritten). A "looks done" // signal never comes through here: only this POST sets a lifecycle. const NO_STORE = { "cache-control": "no-store" }; const fail = (status: number, error: string) => Response.json({ error }, { status, headers: NO_STORE }); export async function POST(request: Request) { const body = (await request.json().catch(() => null)) as { piece?: unknown; state?: unknown } | null; if (!body || typeof body !== "object") return fail(400, "the body is { piece, state }"); const parsed = parsePieceId(body.piece); if (!parsed) return fail(400, `not a piece id: ${JSON.stringify(body.piece ?? null)} (a:/ or p:)`); if (!isLifecycleState(body.state)) return fail(400, `state is active | parked | done, not ${JSON.stringify(body.state ?? null)}`); if (parsed.kind === "case") return fail(404, "research cases have no lifecycle yet"); const graph = await readPieceGraph(); if (!graph.byId.has(body.piece as string)) { // A project an article claims is part of that article's piece. const owner = parsed.kind === "project" ? graph.pieceOfProject.get(parsed.project) : undefined; return fail(404, owner ? `${body.piece} is part of ${owner}: set that piece's lifecycle` : `no piece ${body.piece}`); } try { const entry = await setLifecycle(body.piece as string, body.state, "operator"); clearRailCounts(); return Response.json({ piece: entry.id, state: entry.state, at: entry.at, by: entry.by ?? null }, { headers: NO_STORE }); } catch (err) { if (err instanceof LifecycleError) return fail((err as LifecycleError & { status: number }).status, err.message); return fail(500, (err as Error).message); } }