Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

retire DONE.md — git log + .changelog/ are the audit trail (#362)

[._.]/ Adam Eivy82b60addf0ab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fcdef49016..a3d162b5fc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Changed
+
+- **Retire `DONE.md` — the audit trail for completed work is now `git log` + `.changelog/`.** Slashdo v2.18.0 dropped DONE.md handling from `/do:replan` and friends; PortOS follows suit. Bumped the slashdo submodule to `v2.18.0`, deleted the repo-root `DONE.md`, and updated PLAN.md's preamble to point at the changelog and `git log` instead. `/claim` (`.claude/commands/claim.md`) now removes the picked item from PLAN.md outright and appends an entry to `.changelog/NEXT.md`. Server prompts retire DONE.md too: `feature-ideas` (PROMPT_VERSIONS v8→v9) and `plan-task` (v5→v6) no longer read DONE.md or write archive entries — they scan `.changelog/` + `git log` for completed-work signal and remove items from PLAN.md outright. Old v8/v5 bodies are captured in `PREVIOUS_DEFAULT_PROMPTS` so existing schedules on stock prompts auto-upgrade on next read. Also stripped DONE.md mentions from `documentation`, `do-replan`, `code-reviewer-review`, and `code-reviewer-implement` task prompts (unversioned — stock copies behave like custom and stick until the user resets, which is fine). `server/routes/apps.js#ALLOWED_DOCUMENTS` no longer lists DONE.md so the Documents tab won't surface it for managed apps. `server/services/cos.js#applyPlanIdMetadata` stopped reading DONE.md for slug-uniqueness (PLAN.md is now the only source). `server/lib/planIds.js` comments/tests updated. Client copy in `SlashDoPanel.jsx` (`/do:replan` button) + `TaskItem.jsx` reflect the new replan behavior. Existing repos with a DONE.md on disk are left untouched — slashdo simply no longer reads or writes them.
+
## Added
- **Network Exposure dashboard widget.** New widget surfaces how PortOS is actually exposed on the network: HTTPS vs HTTP, bind address + audience (loopback-only / all-interfaces / specific-interface), cert mode (Tailscale-trusted hostname vs self-signed), the loopback HTTP mirror port when HTTPS is on, and a mic-availability hint computed from the browser origin (HTTPS or loopback ⇒ available; HTTP on a Tailscale IP ⇒ blocked by the browser's secure-context rule). Renders a warning banner when bound on all interfaces over plain HTTP. Seeded into the `default` (Everything) and `ops` built-in dashboard layouts so the security posture is visible product UX, not a docs-only invariant. Backed by `GET /api/network-exposure/status`.
diff --git a/.claude/commands/claim.md b/.claude/commands/claim.md
index 325ea04d0e..3db7b8151b 100644
--- a/.claude/commands/claim.md
+++ b/.claude/commands/claim.md
@@ -16,7 +16,7 @@ Claim the next unclaimed `- [ ]` item from PLAN.md via the slug-ID system, work
## Phase 1: Pick
-1. Read `PLAN.md` and `DONE.md` from the repo root.
+1. Read `PLAN.md` from the repo root.
2. **If any `- [ ]` line lacks an `[<slug>]` ID, stop and run `/do:replan` first** — Phase 0 of `/do:replan` populates IDs in one pass, after which `/claim` can find work to claim.
3. Build the in-flight set:
```bash
@@ -88,7 +88,7 @@ Write the code, tests, and any docs the item requires. Follow the repo conventio
Run the relevant test suite as you go (`cd server && npm test -- <area>` for focused runs).
-**Commit messages.** Reference the slug in the subject line so the work is grep-able across DONE.md, branches, and PR titles:
+**Commit messages.** Reference the slug in the subject line so the work is grep-able across the changelog, branches, and PR titles:
```
feat([<slug>]): <one-line description>
@@ -98,24 +98,23 @@ feat([<slug>]): <one-line description>
Use `feat:` / `fix:` / `refactor:` / `chore:` / etc. per conventional commit prefixes — PortOS uses these throughout.
-## Phase 5: Update PLAN.md and DONE.md
+## Phase 5: Update PLAN.md
-**Move the item out of PLAN.md and into DONE.md.** Do NOT leave a checked `- [x]` behind in PLAN.md — that's only the convention for items intentionally left as a design log (rejected items, shipped items with rich completion notes, etc.).
+**Remove the item from PLAN.md outright.** The audit trail for shipped work lives in `git log` and `.changelog/` — slashdo v2.18.0 retired the DONE.md archive, and PortOS follows the same convention. Do NOT leave a checked `- [x]` behind in PLAN.md — that's only the convention for items intentionally left as a design log (rejected items, items with rich completion notes the human wants preserved on the active plan, etc.).
1. Remove the picked `- [ ]` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is `/do:replan`'s job.
-2. Append to DONE.md under today's date heading (`## YYYY-MM-DD`). Insert today's heading directly below the top-of-file preamble if it doesn't exist yet.
-3. Entry shape — **slug lifted verbatim from PLAN.md, never re-derived from the description**:
+2. **Add an entry to `.changelog/NEXT.md`** capturing what shipped. Mirror the prose style of other entries in `NEXT.md`. Lead with the slug in brackets so `git log` and `.changelog/` greps line up:
```markdown
- **[<slug>] <Title from the PLAN.md line>** — <1–3 sentences on what shipped, key files touched, any caveats>
```
- The slug is immutable (per [lib/slashdo/lib/plan-id-format.md](../../lib/slashdo/lib/plan-id-format.md)). The bold-wrapped title format makes the slug greppable across DONE.md and lets the next `/do:replan` Phase 0 collision scan parse the line deterministically.
+ The slug is immutable (per [lib/slashdo/lib/plan-id-format.md](../../lib/slashdo/lib/plan-id-format.md)). Bracketing it makes the change findable via `git log --grep='<slug>'` and `grep -rn '<slug>' .changelog/`.
-Stage both files (`git add PLAN.md DONE.md`) and commit:
+Stage both files (`git add PLAN.md .changelog/NEXT.md`) and commit:
```bash
-git commit -m "docs([<slug>]): archive to DONE.md"
+git commit -m "docs([<slug>]): remove from PLAN.md and log to changelog"
```
## Phase 6: Review and ship
diff --git a/DONE.md b/DONE.md
deleted file mode 100644
index d935aedf4d..0000000000
--- a/DONE.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# PortOS — Completed Milestones
-
-Archive of completed work — feature-level only. Each release ships a per-version file under [.changelog/](./.changelog/) with the full implementation specifics; this file is the bird's-eye view for understanding what the app does and when it shipped.
-
-For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./GOALS.md).
-
----
-
-## 2026-05
-
-### 2026-05-19
-
-- **[high-tests-add-coverage-for-server-services-shell] Add coverage for `server/services/shell.js` and `server/services/feeds.js`.** Both services had exported functions but no sibling test. New `shell.test.js` (36 cases) pins the full PTY-session lifecycle: `createShellSession` (allow-listed env filtering with caller opt-in, defaults, max-session cap with + without socket, spawn-failure path, PTY output → socket emit + onData hook, 50KB ring-buffer trim with newest-retained assertion, hook sync-error logging path, PTY exit cleanup, deferred `initialCommand` write); `attachSession` (unknown id, socket swap + bufferedOutput replay, `shell:detached` emit on displaced socket, claim-true displacement reject + same-socket re-attach + unbound take-over); `listAllSessions` (recipient-relative `attached` true/false/global view, metadata fields); `subscribeSessionList`/`unsubscribeSessionList` broadcast wiring; `writeToSession`/`resizeSession`/`killSession` happy + miss paths; `detachSocketSessions` count + list-subscriber unsubscribe; `getSession`/`getSessionProcess`/`getSessionCount`. Uses a captured PTY fake (records `onData`/`onExit` handlers so tests can fire them) and `vi.resetModules()` per case so the module-level `shellSessions` map starts empty. New `feeds.test.js` (35 cases) covers `parseRSS` + `parseAtom` paths through `addFeed` (RSS title + CDATA strip + `dc:creator` fallback, Atom `rel="alternate"` preference verified against a sibling `rel="self"` link, hostname fallback when feed `<title>` empty), SSRF guards (non-http(s) protocols, literal private IPv4 — `127.0.0.1`/`10.x`/`172.16-31.x`/`192.168.x`/`169.254.x`/`0.0.0.0` — assert without DNS lookup, DNS-resolved private IP rejection, empty DNS records rejection), redirect handling (safe redirect followed to the named URL with `redirect: 'error'`, private-IP redirect rejected before the second fetch fires), CRUD + lifecycle (`removeFeed`, `refreshFeed` dedupe + `lastFetched` bump via fake timers + missing/unfetchable errors, `refreshAllFeeds` parallel-fetch + failure counting), and read paths (`getItems` feedId/unreadOnly/limit+offset/newest-first invariant, `markItemRead` + `markAllRead` scoped + unscoped, `getFeeds` unread counts, `getFeedStats`). Reuses `makePathsProxy` from `server/lib/mockPathsDataRoot.js` (function-form `dataRoot` so each test gets a fresh tmpdir for isolation); mocks `fetchWithTimeout` for canned XML and `dns.resolve4` for SSRF paths. Per-file `console.log`/`console.warn` suppression drops the feeds suite from ~6s to ~90ms. One real-world SSRF gap surfaced while writing tests — `http://[::1]/feed` slips past `isHostSafe` because `URL.hostname` returns the bracketed form, captured in PLAN.md as `[feeds-ssrf-ipv6-bracket-hostname-gap]`. All 71 new tests pass.
-- **[codex5-network-exposure-ui] Network Exposure dashboard widget.** New `server/lib/networkExposure.js` snapshots boot-frozen exposure state (scheme + bind + cert mode from `meta.json` + Tailscale hostname + loopback mirror port) and a new `GET /api/network-exposure/status` route surfaces it. New `client/src/components/NetworkExposureWidget.jsx` renders an at-a-glance HTTPS/HTTP badge, bind audience (loopback-only / all-interfaces / specific-interface), Tailscale-trusted cert vs. self-signed pill, loopback HTTP mirror link, and a mic-availability hint computed client-side from `window.location.protocol` + loopback-host check. Flags an actionable warning when the server is bound on all interfaces over plain HTTP. Registered in `widgetRegistry.jsx` with `MicroGlyph` chrome and seeded into the `default` (Everything) and `ops` built-in layouts so the security posture is visible product UX, not a docs-only invariant. Two `/simplify` follow-ups deferred to PLAN: extract a shared `readCertMeta()` helper (third independent meta.json reader landed) and hoist `isLoopbackHost` to `client/src/lib/loopbackHost.js`.
-- **[extract-requiretoolkit-pattern-to-runner-js] Extend `requireToolkit()` pattern to `server/services/runner.js` + `promptService.js`.** The 13 inlined `if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized')` sites in `runner.js` (across `createRun`, `finalizeRunRecord`, `executeCliRun`, `executeApiRun`, `registerActiveRun`, `stopRun`, `getRun`, `getRunOutput`, `getRunPrompt`, `listRuns`, `deleteRun`, `deleteFailedRuns`, `isRunActive`) plus 12 sibling sites in `promptService.js` (across `loadPrompts`, `getStages`, `getStage`, `getStageTemplate`, `updateStageTemplate`, `updateStageConfig`, `getVariables`, `getVariable`, `updateVariable`, `createVariable`, `deleteVariable`, `buildPrompt`) now go through a private `requireToolkit()` helper that throws `new ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — mirroring the helper `providers.js` already exports. Promoting `promptService.js` to the typed-error shape too was a /simplify finding from this PR — leaving prompt-service failures on the untyped string-throw while runner + providers were typed would have left callers (e.g. `visionTest.js`'s `err.code === 'AI_TOOLKIT_NOT_INITIALIZED'` gate) unable to discriminate by source. In runner.js, multi-use callsites (`finalizeRunRecord`, `executeCliRun`, `stopRun`, `registerActiveRun`) hoist `const toolkit = requireToolkit()` once so the `aiToolkitInstance.services.X` chains collapse to `toolkit.services.X` without re-checking. `unregisterActiveRun` is unchanged — its optional-chained `.delete` is deliberately best-effort cleanup that runs from child-process teardown callbacks and must not throw. Error message string preserved verbatim so `server/lib/promptRunner.test.js`'s `rejects.toThrow(/AI Toolkit not initialized/)` regex still matches. Follow-up deferred to PLAN.md as `[extract-shared-requiretoolkit-helper]` — three copies of the 8-line helper now exist; extract to `server/lib/aiToolkitState.js` when a 4th caller appears or somebody wants to consolidate. All 5832 server tests pass.
-- **[move-usenextevalcountdown-to-hooks] Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** Relocated `client/src/components/cos/useNextEvalCountdown.js` (1s-tick countdown to the next CoS evaluation) to `client/src/hooks/useNextEvalCountdown.js` to conform to the CLAUDE.md "Module Organization" rule that `useX` hooks live exclusively under `client/src/hooks/`. Dropped the re-export from `components/cos/index.js`, added the catalog row to `client/src/hooks/README.md` (Apps / Sessions / Domain), and added the barrel re-export to `client/src/hooks/index.js`. Only consumer (`client/src/pages/ChiefOfStaff.jsx`) now imports the hook directly from `../hooks/useNextEvalCountdown`, matching the existing direct-import pattern it already uses for `useSocket` and `useLocalStorageBool`. Pure relocation — no behavioral changes. All 154 client tests pass (the `hooks/index.test.js` barrel-shape invariant test confirms the move is correctly wired).
-- **[sharing-annotationssync-cache-bucket-asset-keys] Cache `listBucketAssetKeys` per (bucket, manifests-dir mtime).** `server/services/sharing/annotationsSync.js#listBucketAssetKeys` previously re-scanned every manifest in every auto-merge bucket on every 2s-debounced annotation flush. Manifests are the only source of truth post-v2 (content-addressed `assets/blobs/<hash>` paths don't carry filenames), so per-flush fan-out scaled O(buckets × manifests). The function now stats `<bucket>/manifests/` on each call and reuses the previously-parsed `Set<assetKey>` whenever the directory mtime matches — every manifest write/archive goes through `atomicWrite` (temp + rename) or `rename`, both of which bump the dir mtime, so the mtime is a complete invalidation signal. The legacy v1 `assets/{images,videos}/` dir scan stays uncached (small + rare fall-through). The annotation manifest emitted by `exportAnnotationsToBucket` rolls the cached mtime forward so the post-write bump doesn't immediately invalidate the same bucket's cache on the next flush. New `__resetBucketAssetKeysCache` test hook + 7 new vitest cases in `annotationsSync.test.js` covering hit, mtime-advance miss, per-bucket isolation, legacy-dir-scan-still-runs, ENOENT-on-manifests-dir as a stable cache key, non-ENOENT stat error bypasses caching, and post-write mtime-roll-forward keeps the next flush hot.
-- **[export-isplainobject-helper-from-server-lib-objects] Export `isPlainObject` from `server/lib/objects.js`.** Promoted the previously-private `isPlainObject(v) = !!v && typeof v === 'object' && !Array.isArray(v)` helper to a named export of `server/lib/objects.js` (surfaces automatically through the `server/lib/index.js` barrel) and migrated 18 inline call sites onto it — every site that exactly matched the 3-part check pattern. Sites: the previously-private declarations in `server/lib/objects.js` + `server/lib/mediaModels.js` (which now imports from objects.js), the 12 sites enumerated in PLAN (`services/calendarAccounts.js`, `messageAccounts.js`, `messagePlaywrightSync.js`, `loras.js`, `mortalLoomStore.js`, `updateChecker.js`, `meatspacePost.js`, `dataSync.js`, `featureAgents.js`, `taskSchedule.js` — also dropped its single-use local `const isPlainObject`, `pipeline/issues.js`, `sharing/exporter.js`), and 4 additional matching sites that landed between when the PLAN entry was authored and now (`routes/loras.js#DELETE /auth/civitai`, `services/universeBuilderExpand.js#sanitizeCategory`, `server/scripts/moltbook-probe.mjs`, and `scripts/check-themes.js` ×2 — the last two caught by codex review after the initial grep missed `.mjs` files and the top-level `scripts/` dir). Sites with a partial-shape second predicate (`mortalLoomStore.js`'s `current[k] && typeof current[k] === 'object'` and the symmetric block in `featureAgents.js`) kept their second predicate intact — only the full 3-part check was migrated, keeping the PR a pure refactor. Helper retains the loose "non-null, non-array `object`" semantics that match every call site's behavior (Date / Map / class instances still return true — documented in the JSDoc and locked in by 3 new vitest cases). `server/lib/README.md` row updated to name both `deepMerge` and `isPlainObject`. No behavioral changes. All 5832 server tests + 154 client tests pass.
-- **[unify-videogen-resolutions-with-shared-image-gen] Unify VideoGen `RESOLUTIONS` with shared image-gen list.** New `client/src/lib/videoGenResolutions.js` holding `VIDEO_RESOLUTIONS` as the companion to `imageGenResolutions.js`, registered in the lib barrel + README so future image+video work finds it via the catalog. New `resolveResolutionLabel(list, w, h) → { matched, label }` helper in `imageGenResolutions.js` collapses the duplicate "find matching preset OR fall back to `${w}×${h}` for the custom-fallback dropdown option" pattern that lived inline in both `client/src/pages/VideoGen.jsx` and `client/src/components/imageGen/ImageGenControls.jsx`. Both consumers now import the helper; image side's prior `(width && height ? ... : '')` empty-string-when-unset guard is preserved in the helper (returns `label: ''` when either dimension is falsy). Picked a distinct constant name (`VIDEO_RESOLUTIONS` vs the image side's `RESOLUTIONS`) to avoid a flat-barrel name collision in the lib `index.js` `export *` chain. All 154 client tests pass (barrel-shape test confirms the new module is wired correctly into both `index.js` and `README.md`).
-- **[med-universe-builder-server-routes-universebuilder] [med-pipeline-server-routes-pipeline-js-145-149] [med-pipeline-server-services-pipeline-volumepdf-js] [med-pipeline-server-services-pipeline] [med-canon-server-services-pipeline-series-js-210] [low-ai-dispatch-server-lib-promptrunner-js-146] [low-ai-dispatch-server-services-loops-js-181-fire] [low-canon-server-services-pipeline-textstages-js] [low-canon-server-services-pipeline] [low-importer-server-services-importer-js-444-446] [low-ai-dispatch-server-lib-ansistrip-js-14-pattern] v2.1.0 pre-release review residue — small isolated fixes bundle.** Eleven items from the v2.1.0 main→release multi-agent review shipped together because each is a 1–10 line isolated fix and most touch independent files. (1) `server/routes/universeBuilder.js` — `registerUniverseBuilderRun(...)` moved BEFORE the enqueue loop using `compiled.length` as the authoritative job count, so the worker can no longer pick up the first job and emit `completed` before the run is registered (which would lose the per-image emit coalescing the hook depends on). (2) `server/routes/pipeline.js` — `seasonCoverSchema` gained `.passthrough()` so a "save full series" round-trip echoing the server-built `proofImage` / `finalImage` render fields no longer 400s; matches the parent `seasonSchema`'s shape. (3) `server/services/pipeline/volumePdf.js` — issue sort in `assembleVolumePdf` now uses `(a.arcPosition ?? Infinity) - (b.arcPosition ?? Infinity) || (a.number ?? 0) - (b.number ?? 0) || a.id.localeCompare(b.id)`, sinking arcPosition-null items to the end instead of letting `number`-fallback interleave them with positioned ones. (4) `server/services/pipeline/seasonCoverFilenameHook.js` — verified the empty-patch short-circuit is already in `updateSeasonOnSeries` (`series.js:335-344` returns `cur` unchanged when `patchFn` returns `{}`); item archived as already-done. (5) `server/services/pipeline/series.js` — `updateSeries` emits `console.warn` when the incoming patch carries `characters` / `settings` / `objects` (post-B.4 those live on the universe), so a stale browser tab POSTing legacy canon is observable in logs instead of vanishing silently with 200 OK. (6) `server/lib/promptRunner.js` — `effectiveCwd` now uses `(typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd()` matching `tuiPromptRunner.js:103`'s pattern; an empty-string override no longer leaks through `??` to spawn(). (7) `server/services/loops.js` — `onComplete({success:true})` is wrapped in `Promise.resolve().then().catch()` so a throw in the success branch is no longer misclassified as iteration-failed by the trailing `.catch` and falsely emits `iteration:error`. (8) `server/services/pipeline/textStages.js` — dropped the dead `|| series.characters` middle clause from the canon-fallback (post-B.4 `series.characters` is always undefined). (9) `server/services/pipeline/migrateSeriesCanon.js` — orphan-series link write (`updateSeries({ universeId })`) is deferred until AFTER the universe canon patch lands; a crash between create-universe and patch-universe now leaves the legacy series fields intact for retry, instead of stripped + empty. (10) `server/services/importer.js` — emits `console.warn` when the arc-extract LLM returns empty `summary` AND empty `logline` (the synthetic fallback `${name} — ${type}` still fires; the warning makes the silent regression observable). (11) `server/lib/ansiStrip.js` — both the streaming stripper and the one-shot `stripAnsi` gained a `.replace(/\x1B(?![@-_\[\]])/g, '')` second pass so a chunk like `\x1B\x1B[31m` no longer leaks the leading orphan escape byte after the trailing CSI is consumed. All 5829 server tests pass.
-- **[med-sharing-server-services-sharing] [med-sharing-server-services-mediaannotations-js-38] [low-sharing-server-services-mediaannotations-js] [low-sharing-server-services-mediaannotations-js-2] [low-sharing-server-services-sharing] Sharing/annotation-merge hardening bundle.** Five v2.1.0 pre-release residue items shipped together because they all touch the same annotation-sync + LWW-merge surface. (1) `annotationsSync.flushAll` no longer resolves one `sourceName` for all buckets — `exportAnnotationsToBucket` now resolves its own per-bucket name, so per-bucket `displayNameOverride` is honored in outgoing annotation manifest envelopes the same way it already was for series/universe/media manifests. The bucket-effective resolver lives in `sharing/annotationIdentity.js` as a new `resolveBucketSourceName(bucket)` export consumed by both the exporter and the annotation flush (the exporter's local copy in `sharing/exporter.js` was deleted in favor of the shared helper). (2) `mediaAnnotations.mergePeerAnnotations` now pre-rejects peer payloads with missing/invalid `updatedAt` before they reach `sanitizeAuthorEntry`'s `now`-fallback — previously a malformed peer record would always win LWW. The pre-check disambiguates "empty tombstone" (still applies as a delete) from "malformed payload" (now ignored entirely, instead of silently deleting the prior peer entry through the tombstone branch). (3) `sanitizeAuthorEntry` gained an opt-in `clampUpdatedAtTo` option used by the merge path so a peer whose clock is years ahead can't ratchet every subsequent LWW round on the same key — its `updatedAt` is clamped to local-now on import without disturbing reasonable timestamps. (4) `mergePeerAnnotations` rejects `peerInstanceId === 'unknown'` (and empty/non-string) on import — the outgoing path already guarded but a hand-crafted manifest or inconsistent peer could otherwise alias every record into the same "unknown" bucket and clobber each other on every merge. (5) `exportAnnotationsToBucket` now has a cheap early-out before `listBucketAssetKeys`: if local has zero annotations AND no prior record exists on disk for this `(bucket, instance)`, skip the manifest+asset-dir scan entirely (the common fresh-install fan-out case). A late-stage skip (both filtered AND prior empty) still covers the case where the bucket has assets but none overlap local. Coverage: 11 new vitest cases across `mediaAnnotations.test.js` (refuses `'unknown'` / empty peer id, drops missing+invalid updatedAt without nuking prior, clamps future-skewed peer ts) and new sibling `sharing/annotationsSync.test.js` (per-bucket displayNameOverride honored in record, cheap early-out skips `listManifestFilenames`, late skip when no local matches + no prior, asset-less bucket short-circuit, inbox-mode short-circuit, tombstone synthesis preserved for prior keys still in bucket). `/simplify` follow-up deferred to `[promote-unknown-instance-id-constant]` — promote the existing `UNKNOWN_INSTANCE_ID` constant from `importer.js` to a shared module + replace the bare `'unknown'` literal at the four remaining sites. All 5775 server tests pass.
-- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.
-- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.
-- **[sharing-exporter-cache-sourcefile-hash-by-mtime] Cache `sha256File` results in the exporter by `(sourcePath, mtime, size)`.** `server/services/sharing/exporter.js#copyAssetIfPresent` no longer re-hashes every referenced asset on every export — a subscription re-export of a 200MB series previously re-read 200MB of bytes just to confirm "blob already there." Added a per-bucket sidecar `<bucket>/assets/blobs/.index.json` mapping `<sourcePath>:<mtimeMs>:<size> → <hash>` (the size is part of the key as defense-in-depth alongside mtime). New `loadAssetHashCache(bucketPath)` reads the JSON once at the start of each top-level exporter (`exportSeries`, `exportUniverse`, `exportMedia`); `copyAssetIfPresent(filename, kind, bucketPath, cache)` reads the cache before computing the hash and only falls through to `sha256File` + `copyFile` when the cache key is missing OR the recorded blob no longer exists in `assets/blobs/`. New cache entries accumulate in the shared object across all parallel `Promise.all` branches (jobs + image + video + image-ref) and `saveAssetHashCache` atomically writes once after the `Promise.all` resolves. Cache key includes the absolute source path so unrelated buckets pointing at the same asset still benefit independently. mtime change automatically invalidates because it's part of the key. The threaded cache also flows through `exportMediaJobAndAsset` so media-job-driven asset copies share the same cache. `isHexHash` validates cached values before trusting them so a hand-edited or torn `.index.json` can't poison `bucketBlobPath` (the existing hostile-hash guard already throws on bad shapes; the read-side filter just makes the cache fall back to recompute instead of throwing). The existing content-addressed-dedup test (`readdirSync(blobs/)`) now filters dotfiles so the `.index.json` sidecar isn't counted as a blob. New integration test pins all four behaviors: the index file is created, the key format matches the documented contract, an unchanged re-export keeps the cache file byte-identical, an mtime-only bump (same bytes) records a new key with the unchanged hash, and a content mutation records a fresh hash + lands a new blob under the new content-addressed path. All 5756 server tests + 121 client tests pass.
-- **[wardroberow-migrate-to-userowdraft] Migrate `WardrobeRow` to consume `useRowDraft`.** `client/src/components/pipeline/CanonCard.jsx` no longer runs two `useFieldDraft` calls per outfit row — a single `useRowDraft(wardrobe, onCommit)` call covers both columns, so wardrobe entries pick up the same sibling-draft ride-along race protection that landed for `ListRow` in `[characterdetaileditor-listrow-row-draft-hook]`. `WardrobeSection.commit` reshapes from `(idx, field, value)` to `(idx, nextRow)`; the pending-row promotion trigger moves from "per-field `name` commit with non-empty value" to "any commit where `nextRow.name.trim()` is non-empty" — same end state, and the rewrite fires earlier for the ride-along case (description blur with a pending name draft now promotes the row instead of stranding it in `pendingNew`). The deferred concern from PLAN ("promotion semantics need their own design pass") resolved by following the existing `CharacterDetailEditor.updateRow` pattern, which already runs the same required-column check against `nextRow`. Removed the now-unused `useFieldDraft` import from `CanonCard.jsx`. +1 ride-along regression test in `CanonCard.test.jsx` (description blurs first with a pending name draft → row promotes with both fields intact). All 121 client tests pass.
-- **[code-quality-dedup-batch] Code quality / dedup batch — 8 items shipped together.** (1) `[extract-optionalbooleanmap-zod-helper]` — new `optionalBooleanMap(keys)` helper in `server/lib/validation.js` collapsing the `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))` pattern at 3 sites (`server/routes/universeBuilder.js`, `server/routes/pipeline.js` ×2). (2) `[extract-a-tryreadfile-helper]` — new `tryReadFile(path, encoding='utf8')` in `server/lib/fileUtils.js` replacing the `readFile(...).catch(() => null)` pattern at ~60 sites across `server/`; `readFile` import removed from 22 files where all uses migrated. Auto-injected `tryReadFile` mock into ~80 test files' `vi.mock('../lib/fileUtils.js')` bodies to keep partial mocks working. (3) `[aitoolkit-loadproviders-corrupt-fallback]` — `loadProviders` in `server/lib/aiToolkit/providers.js` now wraps `JSON.parse` in a `parseOrRescue(content, source)` helper that renames the corrupt user file to `<path>.corrupt.<timestamp>` + logs + returns `{ activeProvider: null, providers: {} }` so a garbled providers.json can't crash server boot. The shipped-sample path parses BEFORE persisting so a malformed sample can't seed user-side providers.json with garbage (per codex review). (4) `[more-resolveproviderandmodel-migration-candidates]` — migrated 3 sites onto the existing `resolveProviderAndModel` helper (`server/services/agentContentGenerator.js#runAIGeneration`, `server/services/agentPersonalityGenerator.js`, `server/services/loops.js#runIteration`); loops.js wraps with `.catch(() => ({ provider: null }))` to preserve the original "swallow all" semantics across both `getProviderById` and `getActiveProvider` failures. (5) `[extract-assertprovider-helper]` — new `assertProvider(provider, { message, code, status = 503 })` helper in `server/lib/promptRunner.js`; throws `ServerError` with code+status when `code` is provided, plain `Error` otherwise (preserves each caller's original error shape). Migrated 7 `if (!provider) throw …` sites (`universeBuilderAutoSort.js`, `universeBuilderRefine.js`, `universeBuilderExpand.js` ×2, `universeBuilderPromote.js`, `agentContentGenerator.js`, `agentPersonalityGenerator.js`). Auto-injected `assertProvider` mock into 6 test files mocking `promptRunner.js`. (6) `[extract-uselocktoggle-hook]` — new `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage })` returning `{ busy, toggle }` in `client/src/hooks/useLockToggle.js` collapsing the optimistic-PATCH lock toggle pattern at 4 sites: `toggleArcLock`/`FieldLockToggle#toggle`/`toggleSeasonLock` in `client/src/components/pipeline/ArcCanvas.jsx`, `handleStageLockToggle` in `client/src/pages/PipelineIssue.jsx` (removes the now-dead `stageLockSaving` useState). (7) `[skip-the-text-accumulator-in-promptrunner]` — `runPromptThroughProvider`'s `onData` now skips the `APPEND_CHUNK` text concat for TUI providers (which discard the accumulated `text` anyway in favor of `result.text` from `executeTuiRun`); TUI screen-redraw streams can hit hundreds of KB per run. (8) `[aitoolkit-createprovider-field-parity-test]` — new exhaustive test in `server/lib/aiToolkit/providers.test.js` that round-trips all 20 fields defined in `createProvider`'s explicit field list through `create → save → reload`, guarding against the regression where a Zod-schema field is added without being mirrored into the explicit `createProvider` field list. All 5690 server tests + 103 client tests pass; client build clean.
-- **[characterdetaileditor-listrow-row-draft-hook] Extract `ListRow`'s multi-column row-draft state into a shared `useRowDraft` hook.** `client/src/components/universe/CharacterDetailEditor.jsx`'s `ListRow` carried 19 lines of inline `useState({})` draft buffer + `draftFor`/`setDraft`/`commit` triple, with the load-bearing sibling-draft "ride-along" merge (`{...row, ...drafts, [col]: v}`) that keeps a fast A-blur → B-blur sequence from losing column A when the parent hasn't re-rendered yet. Lifted into new `client/src/hooks/useRowDraft.js` — the row-level analogue of `useFieldDraft` (single-field draft+blur). Hook signature is `useRowDraft(row, onChange)` returning `{ draftFor, setDraft, commit }`; preserves the ride-along merge verbatim and coerces `null`/`undefined` persisted columns to `''` so inputs stay controlled. `ListRow` collapses to a single hook call. 9 new vitest cases cover persisted/empty fallback, draft buffering without firing onChange, commit no-op when value equals persisted, commit no-op when no draft set, null-as-empty equivalence, the ride-along race-protection invariant (committing column B with a pending column-A draft ships both in one onChange), and that commit clears only the committed column from the drafts map. All 112 client tests pass.
-- **Better-audit residue refactor bundle.** Shipped four PLAN.md items from the Better-audit residue section as one PR — three landed as scoped fixes, one was rescoped after the underlying premise eroded. (1) `[medium-client-4-components-still-redefine]` — added `formatTimecode` (M:SS.ss for video timecodes), `formatDurationSec` (M:SS for seconds, `'—'` fallback), and `formatDateShort` (short-month date, `'—'` fallback) to `client/src/utils/formatters.js`; migrated `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, and `ImportTab.jsx` off their local re-definitions. `MortalLoomTab.jsx` (also named in PLAN) already imported `formatBytes` from the shared module, so no change there. (2) `[medium-perf-feeds-js-getitems-303-319-full-sort]` — `server/services/feeds.js` now maintains the newest-first sort invariant on writes (`addFeed`, `refreshFeed`, `applyParsedFeed` end-of-batch in `refreshAllFeeds`); `getItems` drops the per-call sort. New `ensureItemsSorted()` runs once on first read after server boot to normalize legacy disk data, with an `isSortedNewestFirst()` guard so an already-sorted file isn't re-saved on every restart. (3) `[medium-code-magic-numbers-in-cos-js-166-357]` — replaced the brittle `err.message.startsWith('unknown piper voice:')` check in `routes/voice.js` and the `err.message.includes('not initialized')` check in `services/visionTest.js` with typed error codes. `services/voice/tts.js` now throws `new ServerError(\`unknown piper voice: …\`, { status: 400, code: 'UNKNOWN_VOICE' })`; `services/providers.js` consolidated its nine `if (!aiToolkitInstance) throw new Error(…)` duplicates into a single `requireToolkit()` helper that throws `new ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })`. Both new ServerErrors bubble through `asyncHandler` automatically — the voice.js try/catch around `synthesize` dropped entirely (~10 LOC + 1 narrative comment). visionTest.js's error path now surfaces a more accurate "AI provider service is still initializing" message when the toolkit isn't warmed (previously it masqueraded as "provider not found", sending the user looking for the wrong root cause). Named time constants extracted in `cos.js` (`CD_RECOVERY_BOOT_TIMEOUT_MS = 60_000`, `POST_STARTUP_QUEUE_DELAY_MS = 30_000`, `RECENT_COMPLETION_GRACE_MS = 60_000`) and `lmStudioManager.js` (`DEFAULT_REQUEST_TIMEOUT_MS = 30_000`, `AVAILABILITY_PROBE_TIMEOUT_MS = 5_000`). (4) `[low-client-extract-shared-usepopoverposition-hook]` — **skipped, premise eroded.** The original PLAN flagged 4 components (`AddToCollectionMenu`, `BulkTargetPicker`, `ThemeSwitcher`, `VisualStylePicker`) but `VisualStylePicker` no longer exists in the codebase and `AddToCollectionMenu`/`BulkTargetPicker` no longer use the portal-positioning pattern. Today only `ThemeSwitcher` and `CollectionPickerShell` match the shape; the abstraction isn't worth the indirection at 2 callers. PLAN.md entry rewritten to reflect current state — extract when a 3rd caller lands. Updated `voice.test.js` to mock `ServerError` directly (drops the legacy back-compat test, asserts `code: 'UNKNOWN_VOICE'` on the body); loosened `visionTest.integration.test.js`'s "non-existent provider" assertion to accept either the "not found" branch (toolkit warmed) or "still initializing" branch (toolkit not yet wired in the test context). One `/simplify` follow-up deferred to PLAN.md as `[extract-requiretoolkit-pattern-to-runner-js]` — `runner.js` has 13 more sites of the same inlined `if (!aiToolkitInstance)` check that should adopt the new `requireToolkit()` helper. All 5703 server tests + 103 client tests pass.
-- **[clear-pending-sheet-slot-on-entry-delete] Prune `_latestPendingByCharacter` on character / universe delete.** The in-process slot map that supersede-checks character reference-sheet renders previously persisted entries for the full Node process lifetime — even after the character or its universe was deleted. Extracted the Map + its `claim`/`get`/`release` helpers into `server/services/universeCharacterSheetSlot.js` (standalone module so `universeBuilder.js` can clear slots without a `universeCharacterSheet.js → universeBuilder.js` import cycle) and added two delete-path helpers: `clearPendingSheetSlot(universeId, entryId)` (unconditional single-character drop) and `clearPendingSheetSlotsForUniverse(universeId)` (walks the map once, drops every `${universeId}:` prefix). `universeCharacterSheet.js` now consumes `claimPendingSheetSlot` / `getPendingSheetSlot` / `releasePendingSheetSlot` instead of inline `_latestPendingByCharacter.set/.get/.delete` — behavior is unchanged, the supersede-aware contract still holds. Wired into two paths: (a) `deleteUniverse` calls `clearPendingSheetSlotsForUniverse(id)` after the file-write queue releases, alongside the existing `unlinkCollectionsForUniverse` cascade; (b) `updateUniverse` computes a `prevIds`/`nextIds` diff against `cur.characters` vs `mergedRecord.characters` INSIDE the write queue (so the diff sees the freshest persisted state) and calls `clearPendingSheetSlot(id, removedId)` for each dropped id after the queue returns. The in-flight render path is unaffected — if a render's character is deleted mid-flight the slot becomes empty, `onSheetComplete` treats itself as superseded, saves the file on disk, and skips stamping a now-orphaned `referenceSheetImageRef` pointer (the `updateUniverse` mutator inside `onSheetComplete` is also a no-op since the character record is gone). Coverage: 11 new tests in `universeCharacterSheetSlot.test.js` covering claim/get/release contracts, unconditional vs conditional drop, prefix-anchored universe sweep (with explicit anti-collision case proving `u-a` doesn't match `u-ab`), falsy-id no-ops; 3 new integration tests in `universeBuilder.test.js#"pending sheet slot cleanup"` covering character-drop via PATCH, character-preserve when the patch keeps them, and universe-delete clearing only that universe's slots. All 5703 server tests + 14 reused `universeCharacterSheet.test.js` cases pass.
-- **[purge-reference-sheet-image-ref-on-sheet-delete] Active-purge `character.referenceSheetImageRef` on sheet delete.** Shipped both the sheet-delete route the original PLAN entry was gated on AND the eager purge it needed. New `purgeReferenceSheetFromAllUniverses(filename)` helper in `server/services/universeCanon.js` mirrors `purgeImageRefFromAllUniverses` but targets the single-string sheet pointer; uses `updateUniverse`'s mutator form because `referenceSheetImageRef` is in `SERVER_OWNED_CHARACTER_FIELDS` and a literal-object PATCH would be guarded against clobbering the pointer. New `deleteCharacterReferenceSheet(universeId, entryId)` in `server/services/universeCharacterSheet.js` reads the character's current pointer, re-validates via `assertSafeFilename` as defense-in-depth, unlinks the PNG from `PATHS.imageRefs` (ENOENT is benign — surfaced via `fileDeleted: false`), then calls the purge to clear every matching pointer across all universes. Mirrors the renderer's lock guard (`UNIVERSE_CANON_LOCKED` 409) so locked characters' sheets stay delete-protected. New `DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet` route. Client: `deleteCharacterReferenceSheet` helper in `apiUniverseBuilder.js` (silent option), trash button in `CharacterReferenceSheetPanel.jsx` (only rendered when a sheet exists + not in-flight) with inline `[Cancel] [Delete sheet]` confirm row per the user's confirmation-UX preference, `onSheetDeleted` callback wired through `characterExtensions` in `CanonCard.jsx` → `UniverseCanonSection.jsx` (`handleSheetDeleted` mirrors `handleSheetCompleted`'s `latestUniverseRef` read so a parallel edit during the DELETE isn't clobbered). Coverage: 3 new tests in `universeCanon.test.js` for `purgeReferenceSheetFromAllUniverses` + 2 backfill tests for the previously-untested `purgeImageRefFromAllUniverses`; new `universeCharacterSheetDelete.test.js` with 8 tests covering happy path, ENOENT benign, non-ENOENT propagation, no-pointer no-op, 404 character, 409 locked, traversal-rejection, and cross-universe purge. All 5710 server tests + 103 client tests pass; client build clean.
-- **[per-field-locks-arc-and-stage-granularity] Per-field arc locks + per-stage issue locks.** Follow-on to per-season locks (`[per-season-and-per-field-locks-extend-arc-lock]`). Two layered ratchets, both enforced server-side and surfaced in the UI. (1) **Per-field arc locks** — `series.locked.arcFields` carries an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); new `mergeArcWithLocks(currentArc, nextArc, lockedFields)` helper in `arcPlanner.js` rewrites the incoming arc to preserve locked field values verbatim from the existing arc, called from `commitSeasonsWithRemap` so both auto-resolve (via `resolveVerifyIssues`) and the `/series/:id/arc/generate?commit=true` path honor the lock; new `ARC_LOCKABLE_FIELDS = ['logline','summary','protagonistArc','themes','shape']` export in `pipeline/series.js` is mirrored as the Zod schema in `seriesLockedSchema`. Arc Canvas read view now renders a small `FieldLockToggle` icon (subtle 4×4 inline button, Lock/Unlock-with-spinner) next to each field that's currently displayed — logline paragraph, story-shape badge, themes chip row, summary `<summary>`, protagonistArc `<summary>` — toggling PATCHes through `updatePipelineSeries({ locked: { ...series.locked, arcFields: nextFields } })` with optimistic update + toast. (2) **Per-stage issue locks** — every `issue.stages.{id}` (text + visual + audio) carries `locked: boolean` (default `false`, strict-true coercion so `locked: 'yes'` typos can't accidentally freeze the stage). New `assertStageUnlocked(issue, stageId)` helper in `pipeline/issues.js` throws `ServerError({ status: 400, code: 'PIPELINE_STAGE_LOCKED' })` and is called from every regeneration entry point: `textStages.generateStage`, `visualStages.enqueueComicCoverLike` / `enqueueVisualComicPage` / `enqueueVisualImage` / `enqueueStoryboardSceneVideo` / `enqueueStoryboardShotStartFrame` / `refineComicPanelPrompt` / `refineStoryboardScenePrompt`, `episodeVideo.startEpisodeVideoForIssue` (fresh-start branch only; reuse of existing `cdProjectId` is still permitted), `arcPlanner.generateComicCoverConcepts` (`commit: true` path), and the four route-level audio/extract paths (`/audio/extract-lines`, `/audio/lines/:n/render`, `/storyboards/extract-scenes`, `/comicPages/extract-pages`). The text-stage gate runs *before* `updateStage({ status: 'generating' })` so a locked stage doesn't get stuck at "generating" only to be reset. `PipelineIssue.jsx` (a) gates the per-tab `<Lock>` indicator on per-stage `locked` first (then falls back to the ambient arc/season-wide lock); (b) adds a Lock/Unlock toggle button to the action bar that targets the currently-active stage and PATCHes `{ stages: { [stageId]: { locked: next } } }` via `updatePipelineIssue`; (c) the lock-banner under the TabPills strip prefers the per-stage message when the active tab is locked. Coverage: 11 new tests — 4 in `issues.test.js` (default `locked: false` on every stage, PATCH round-trip, non-boolean coerce-to-false, `assertStageUnlocked` throw/no-op), 1 in `textStages.test.js` (refuse + leave status untouched on locked stage), 6 in `arcPlanner.test.js` (`mergeArcWithLocks` per-field preservation, empty/null/undefined locks pass through, no-current-arc passthrough, null/undefined next no-op, unknown lock keys ignored, full `commitSeasonsWithRemap` round-trip with locked logline + themes). All 5689 server tests + 103 client tests pass.
-- **[pipeline-visual-stages-setting-field-injection] Inject setting `palette`/`era`/`weather`/`recurringDetails` into visual stages.** Visual prompts now pull the full RICH place descriptor set (description + Palette + Era + Weather + recurringDetails) instead of the SHORT subset (description + Palette + recurringDetails) — era + weather are continuity-critical visual cues that diffusion models weight strongly for lighting, atmosphere, and period dress, and they were already wired through the bible schema + LLM extraction but silently dropped at the visual-prompt boundary. Two surfaces touched: (1) `buildScenePrompt` in `server/lib/scenePrompt.js` + the client mirror at `client/src/lib/scenePrompt.js` swap `shortCanonDescriptorFragments('place', …)` for `richCanonDescriptorFragments('place', …)`, so storyboard scene renders (via `composeVisualPrompt` in `visualStages.js`) AND Writers Room's `SceneCard.jsx` pick up era/weather; (2) `composeComicPagePrompt`'s hand-rolled multi-place clause is replaced with the same `richCanonDescriptorFragments` helper, so the per-page `Setting — Place: description. Palette: X. Era: Y. Weather: Z. recurringDetails` shape is consistent with the scene-prompt path. The capital-cased `Palette:` prefix replaces the previous lowercase `palette:` in comic-page output as a side-effect of the shared helper (RICH_SPEC's uniform capitalization convention). UI card summaries (`KINDS[].descFor` in `UniverseCanonSection`) still use the narrower SHORT spec — those don't drive renders, so widening would just clutter the bible. Truncation order under tight budget pressure: description survives longest; recurringDetails drops first, then weather, era, palette — the priority order documented in `buildScenePrompt`'s header comment. Coverage: 2 new tests in `scenePrompt.test.js` (RICH frags pinned in display order; era/weather omitted when blank) + 3 new tests in `visualStages.test.js` for `composeComicPagePrompt` (full RICH injection + order; blank-field skip without bare prefixes; multi-place ` | `-join). All 5661 server tests + 103 client tests pass; client build clean. Two `/simplify` follow-ups deferred to PLAN.md: `[extract-flatten-canon-descriptor-fragments-helper]` (collapse the 4-site `.map(f => prefix ? ...).join(...)` pattern) and `[cleanplateprompt-migrate-to-rich-canon-fragments]` (sibling visual-prompt surface still on SHORT spec).
-
-### 2026-05-18
-
-- **[per-season-and-per-field-locks-extend-arc-lock] Per-season editorial locks.** Extends the existing series-level arc lock to a per-volume editorial freeze. New `season.locked: boolean` field on each season record (`server/lib/storyArc.js#sanitizeSeason`, default `false`, strict-true coercion so a `locked: 'yes'` typo can't accidentally freeze a volume), opt-in through the existing `seasonSchema.passthrough()` in `server/routes/pipeline.js` (explicit `.locked z.boolean().optional()` per the CLAUDE.md "all inputs validated" convention). Three rewriter gates fire on `locked === true`: (1) `arcPlanner.generateSeasonEpisodes` refuses before any LLM call — same `ERR_VALIDATION` code as the existing arc-lock for symmetry; (2) `issuesSvc.bulkReassignSeason` refuses to move issues OUT of or INTO a locked volume (new `ERR_SEASON_LOCKED` code, mapped to HTTP 409) — checks the latest season state inside `queueIssueWrite` even though the source-of-truth is on the *series* file (which has its own queue), since the per-season-lock toggle isn't a hot path and a stale read here would let a single race window leak in; (3) `seasonsSvc.deleteSeason` refuses (new `ERR_LOCKED` code, also 409). The `updateSeason` content-patch gate uses a `LOCKED_SEASON_ALLOWED_KEYS = { locked, status }` allow-list — `locked` itself must always be patchable (otherwise the user can't unlock), and `status` is orthogonal to editorial content (the production workflow can flip `verified`→`in-production` while the editorial body stays frozen). A patch that includes `locked: false` lets the UI offer "unlock + edit" as one round-trip; any other content key on a still-locked season throws `ERR_LOCKED` with the forbidden field list in the message. `seasonsSvc.deleteSeason` passes its already-loaded series into `bulkReassignSeason` via a new `_preloadedSeries` option so the lock check skips the duplicate file read (same micro-opt as the cover-filer dispatcher in DONE for `[coverautofiler-dispatcher-redundant-getseries]`). UI: `ArcCanvas.jsx#SeasonRow` gains a Lock/Unlock toggle button in the header (mirrors the page-level arc-lock button's visual idiom — `border-port-warning/40 text-port-warning` accent when locked, `border-port-border text-gray-400` unlocked, Loader2 spinner on the in-flight PATCH); the trash button gates on `seasonLocked` with a "unlock to delete" tooltip; `SeasonEditor` flips all six content inputs to `disabled` + `opacity-60` (status select stays editable, save button stays enabled and only PATCHes `{ status }` so the server gate never fires on an attempted-no-op); `SeasonActions` disables the "Generate issues / episodes (LLM)" button with a "unlock to generate" tooltip; a new locked-state banner (`Lock` icon + "Volume locked — generation, delete, and content edits are blocked. Unlock above to make changes.") renders under the season header so the user has one canonical place to read the freeze status. `PipelineIssue.jsx` finds the parent season via the existing `series.seasons` array on first render and surfaces the lock as both (a) a trailing `<Lock>` icon in place of the per-stage status dot across the entire TabPills strip and (b) a sub-header pill with the unlock-on-arc-canvas hint — covers the PLAN's "surface a stage-progress strip" ask without duplicating any state-fetch (issue page already loads its series for the LLM picker). New tests: 5 in `seasons.test.js` (toggle on+off, content-patch refused, status flip allowed on locked, unlock+edit in one patch, delete refused), 3 in `issues.test.js` (out-of-locked refused, into-locked refused, post-unlock allowed), 1 in `arcPlanner.test.js` (generateSeasonEpisodes skips LLM when locked), 1 in `storyArc.test.js` (sanitizer default + truthy-non-boolean rejection). All 5666 server tests + 103 client tests pass; client build clean. Two follow-ups deferred to PLAN.md: `[per-field-locks-arc-and-stage-granularity]` (per-arc-field granularity + per-issue-stage locks — the more complex half of the original PLAN scope) and `[season-lock-aware-arc-resolve]` (teach `resolveVerifyIssues` to either refuse on locked seasons or preserve locked-season payloads in `commitSeasonsWithRemap`).
-- **[pipeline-idea-stage-character-detail-plumbing] Plumb richer character bible into idea-stage prompt + extract migration scaffold.** Three slugs landed in one PR. (1) `data.sample/prompts/stages/pipeline-idea-expansion.md`'s `{{#series.characters}}` iteration now matches the prose/comicScript/teleplay templates verbatim: `**{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}`. The beat-sheet LLM now sees the same character interiority + role that downstream stages see, so arc decisions made at idea-stage don't lose context the bible already carries. New migration `scripts/migrations/025-idea-stage-character-detail.js` rewrites any of three legacy shipped hashes (pre-003, post-003/pre-004, post-004/pre-025) onto the new shape; customized installs get a manual-merge warning. `scripts/setup-data.js` drift table updated in parallel (`1ee44cf95851ff8debf18729ebcd40b4` appended to the auto-updatable OLD list, NEW bumped to `1f3c5d077a5ef9a4b610335d5e3edd9c`). (2) `[extract-migration-scaffolding-into-scripts]` shipped — `scripts/migrations/_lib.js` exposes `md5`, `applyPromptReplaceMigration({ rootDir, accepted, current, label, customizedHint })`, and `makePromptReplaceMigration({ accepted, current, label, customizedHint, skipFooter? })` returning `{ applyMigration, up }`. Per-migration files collapse to ~50 LOC of hash table + label + hint. (3) `[extract-migration-test-helpers]` shipped — `scripts/migrations/_testHelpers.js` exposes `md5` (re-exported from `_lib.js`), `repoRoot`, `sampleBody(filename, subdir?)`, `customizedBody(filename)`, and a `runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix, subdir? })` describe-block builder that fires the six standard cases (missing-file no-op / idempotent / drift-catch / synthetic-OLD upgrade / customized preservation / hash-table shape) inside the surrounding describe. Per-migration test files collapse to a single `runPromptMigrationTests` call. Migration 023 refactored as proof-of-pattern: source went 130→58 LOC, test went 113→21 LOC. `scripts/run-migrations.js` filter gained `&& !f.startsWith('_')` so the shared helpers stay out of the migration sequence; new `scripts/run-migrations.test.js` regression case pins the exclusion against a phantom `_lib.js` fixture. All 257 server test files (5663 tests) + 48 migration/runner tests pass. Three `/simplify` follow-ups deferred to PLAN.md: `[backport-pre-023-migrations-to-_lib]` (collapse the other six prompt-replace migrations onto `_lib.js`), `[setup-data-import-drift-tables-from-migrations]` (drop the hand-mirrored hash tables in `setup-data.js` once every migration exports them), and `[parallelize-applypromptreplacemigration-files]` (theoretical, for the first multi-file migration).
-- **[coverautofiler-dispatcher-redundant-getseries] `fileCoverIntoAutoCollection` dispatcher — pass preloaded series into the universe leaf.** `server/services/pipeline/coverUniverseFiler.js`'s dispatcher now forwards its already-fetched series to `fileCoverIntoUniverseCollection` via an optional `_preloadedSeries` arg; the universe leaf accepts the preload, skips its initial `getSeries`, and preserves the mid-flight race-detection re-read. Net effect for the dominant (universe-linked) path: 2 `getSeries` calls per cover completion instead of 3. The series leaf intentionally does NOT accept a preload — its own first read is load-bearing for the early re-route check (a universe link added between the dispatcher's fetch and the leaf's entry must trigger the re-route into the universe leaf, otherwise the cover would land in the per-series collection and merely get orphaned by the post-`addItem` recovery instead of filed to the universe). Direct callers of the universe leaf (no preload) keep the old shape via a `?? await getSeries(...).catch(() => null)` fallback. +1 test in `coverUniverseFiler.test.js` spies on `seriesSvc.getSeries` and pins the post-optimization universe-path call count (2 total) via the capture-restore-assert pattern so a failing assertion doesn't leak the spy. All 21 cover-filer tests + 349 pipeline-service tests pass.
-- **[importer-canonprompt-preview-fragments-helper] Share a per-kind preview-fragments helper between Importer and `canonPrompt.js`.** New `previewCanonFragments(kind, entry)` helper in the mirrored `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` returns `{ subtitle, body }` where `subtitle` is a single trimmed string and `body` is an ordered `[{ field, value }]` array of non-blank fields. Backed by a new `PREVIEW_SPEC` keyed by canonical kind name (`characters` → `{ subtitleField: 'role', bodyFields: ['physicalDescription','personality','background'] }`, `places` → `{ subtitleField: 'slugline', bodyFields: ['description'] }`, `objects` → `{ subtitleField: null, bodyFields: ['description','significance'] }`). Intentionally wider than `shortCanonDescriptorFragments` (which is scoped to the visual subset that drives render-prompts) — preview exists so the user can disambiguate which entry to commit, so it surfaces narrative-only fields (`personality`, `background`, `slugline`) that have no visual role. The three `CanonReviewSection` callsites in `client/src/pages/Importer.jsx` no longer pass `renderSubtitle`/`renderBody` props — `CanonReviewSection` now calls the helper directly with the `kind` prop it was already passing, collapsing 18 lines of inline ternaries + filter/join calls onto a single helper invocation. 11 new vitest cases in `server/lib/canonPrompt.test.js` cover null/non-object/unknown-kind edge shapes, kind plural/singular passthrough, per-kind field-presence semantics (characters: role subtitle + 3-field body, no description fallback; places: slugline + description only; objects: empty subtitle + description+significance), whitespace trimming, and confirms RICH-only fields (palette/era/weather/recurringDetails) are NOT in preview. PLAN.md's `'places' → 'settings'` alias note was stale — codebase already canonicalized on `'places'` as the kind name (`normalizeKind` returns `'places'` correctly), so no alias work was needed. All 5608 server tests + 92 client tests pass.
-- **[resolve-issues-inherits-verify-gaps-verify-the] Resolve-issues inherits verify gaps.** The auto-resolve LLM pass (`pipeline-arc-resolve.md`) was receiving per-episode `synopsis` strings via `seasonsTreeJson.episodes[].synopsis` (wired in `buildVerifyContext` and inherited by `buildResolveContext`) but its "How to resolve" instructions never told the LLM to use them — only the sibling verify prompt ("Did a character die in episode 4 but get dialogue in episode 7?") called the data out by name. As a result the resolve pass could rewrite a volume's `synopsis` in ways that contradicted what its child episodes already described. Added a new first bullet to `data.sample/prompts/stages/pipeline-arc-resolve.md` that pins the LLM to treat episode synopses as ground truth: volume-level synopsis rewrites must summarize what the child episodes describe, can't invent beats no episode covers, can't paper over contradictions that originate at the episode level, and when a finding cites an episode (e.g. `season:2 / episode:5`) the fix means re-framing the volume around what that episode already shows. Empty/null episode synopses are called out as the "user hasn't drafted that issue yet" signal so the LLM doesn't infer the volume has no content. New migration `scripts/migrations/023-resolve-prompt-episode-anchor.js` rewrites the installed prompt for any of three legacy shipped hashes (pre-005, pre-019, post-019); customized installs get a manual-merge warning. Migration 019's `NEW_SHIPPED_MD5['pipeline-arc-resolve.md']` bumped to the new post-023 live-sample hash so fresh installs (where `data/` is seeded from the latest sample) report `alreadyCurrent` instead of a misleading "customized" warning; the comment block above 019's table now documents the convention that later migrations re-touching a file must bump 019's entry too. `scripts/setup-data.js` drift table updated in parallel (`8e348f3d...` appended to the auto-updatable OLD list, NEW bumped to `5b340885...`). 6 new tests in `023-resolve-prompt-episode-anchor.test.js` cover missing-file no-op, idempotent re-run, drift-catch against the live sample, OLD→NEW upgrade via synthetic fixture, customized-file preservation, and table shape consistency. All 5604 server tests + 28 migration tests pass. Two `/simplify` follow-ups deferred to PLAN.md: `[extract-migration-scaffolding-into-scripts]` expanded to flag that 023 is the fourth clone of the migration scaffold, and new companion item `[extract-migration-test-helpers]` for lifting the test scaffold (md5 helper, repoRoot/sampleBody/customizedBody, mkdtemp seed beforeEach, 5 shared test bodies) alongside `_lib.js`.
-- **[extraction-after-comicscript-teleplay-stages] Extraction after comicScript / teleplay stages.** Resolves the deferred decision in favor of an opt-in, manually-triggered extraction: auto-extract stays prose-only (so the auto-pipeline isn't paying an extra LLM call per script stage on every issue), but writers can now pull canon from a script stage on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (stageId must be `comicScript` or `teleplay`) reads `issue.stages[stageId].output` as the corpus and calls the existing generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping the prose auto-extract uses, so script-derived entries survive later AI refines and stay attributable to the triggering series. Schema `extractCanonFromScriptSchema` accepts an optional `providerOverride`; the route also returns the merged universe plus `{ characters, places, objects }` counts so the UI toast can summarize the merge. Three precondition guards: `PIPELINE_CANON_EXTRACT_BAD_STAGE` (400) for any stage other than the two script stages, `PIPELINE_CANON_EXTRACT_NO_CORPUS` (400) when the script stage has no output, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE` (400) when the series isn't linked to a universe. New shared component `client/src/components/pipeline/stages/ExtractCanonButton.jsx` (BookOpen icon + "Extract canon" label) is gated on stage content + linked universe and surfaces a tooltip explaining the specific blocker when disabled. Wired into both script stages: `TeleplayStage.jsx` passes it through `TextStagePanel`'s `extraActions` slot; `ComicScriptStage.jsx` mounts it directly in its header actions next to the Image-gen settings button. Client helper `extractPipelineCanonFromScript(issueId, stageId, body, options)` in `apiPipeline.js` follows the project's silent/toast convention (helper passes `{ silent: true }` since the button owns its own error toast). 5 new vitest cases in `server/routes/pipeline.test.js` cover all three precondition guards plus the happy path for both stage IDs, asserting the corpus is forwarded and the autoLock/sourceSeriesId stamping matches the prose auto-extract semantics. All 5570 server tests + 92 client tests pass; client build clean.
-- **[same-collection-export-pattern-for-pipeline-series] Same collection-export pattern for pipeline series with auto-collections.** Extends the v1.4 universe→manifest.collection share pattern to also cover universeless series. `mediaCollections.js` gains an optional `seriesId` field on `sanitizeCollection` (mutually exclusive with `universeId` — universe wins on hand-edited dual-stamp records), `seriesCollectionNameFor('Foo') → 'Series: Foo'` naming convention, and `findCollectionBySeriesId` / `findOrCreateSeriesCollection` / `unlinkCollectionsForSeries` / `renameCollectionForSeries` helpers mirroring the universe-side set. `updateCollection` now also locks the visible name when `seriesId` is set; the four mutation paths (`addItem`, `removeItem`, `bulkUpdateCollectionItems`, `deleteCollection`) fan `recordEvents('updated', 'series', seriesId)` alongside the existing universe emit so series subscriptions auto-re-export when peer adds new images. `coverUniverseFiler.js` gains a `fileCoverIntoAutoCollection({ seriesId, filename })` dispatcher that routes universe-linked series to the universe collection path (existing behavior) and universeless series to a new `fileCoverIntoSeriesCollection` path with the same delete-race recovery shape. The two cover hooks (`comicPagesFilenameHook.js`, `seasonCoverFilenameHook.js`) switch from the universe-only helper to the dispatcher. `pipeline/series.js#updateSeries` cascades name changes onto the linked per-series collection (no-op when no series-collection exists, which is the common case for universe-backed series); `deleteSeries` unlinks the per-series collection so the orphan becomes a normal user-owned bucket. `sharing/exporter.js#exportSeries` falls back to `findCollectionBySeriesId(series.id)` when there is no universe-linked collection — same `manifest.collection` shape, just keyed on `seriesId` instead of `universeId`; the local `findCollectionForUniverse`/`findCollectionForSeries` helpers were dropped in favor of the canonical `mediaCollections` exports (better seriesId normalization). `sharing/manifest.js#buildManifest` accepts `collection: { seriesId, ... }` alongside the existing `universeId` shape, using `universeCollectionNameFor`/`seriesCollectionNameFor` for fallback names (proper NAME_MAX_LENGTH truncation). `sharing/importer.js#mergeCollectionPayload` branches on which id the payload carries; defers with `missingSeries: true` when the local series doesn't exist yet (cursor stays un-advanced so a later sync of the series unblocks the merge — mirrors the existing `missingUniverse` path); `applyAutoMerge` returns `collectionPendingSeries` and `processManifest` includes it in the pending-gate predicate. `promoteInboxItem` throws `SHARING_SERIES_PENDING` (status 409 via `routes/sharing.js` mapping) when the collection waits on a missing series. Backward-compatible — older peers' importers no-op on seriesId-keyed payloads via the existing `if (!payload.universeId)` early-return. 30 new tests: 10 in `mediaCollections.test.js` (sanitizer mutual-exclusion, name helpers, find/create/rename/unlink, recordEvents fan-out on both add and delete), 9 in `coverUniverseFiler.test.js` (series-fallback path + dispatcher routing), 3 in `sharing/integration.test.js` (series-export round-trip with per-series collection, prefer-universe-when-both, defer-when-series-missing). All 5587 server + 92 client tests pass. Dispatcher's redundant pre-branch `getSeries` call deferred to PLAN.md as `[coverautofiler-dispatcher-redundant-getseries]`.
-- **[character-bible-simplify-followups] Character bible / reference-sheet `/simplify` follow-ups.** Captured from the simplify review during the character bible expansion PR. Of the eleven sub-bullets: eight fully landed in this PR; one (item 3 — extract the WardrobeSection draft+blur+pending-row editor into a shared hook reused by both `WardrobeSection` and `CharacterDetailEditor.jsx`'s `ListRow`) shipped its `useFieldDraft` half but couldn't unify `ListRow` (the multi-column ride-along race protection doesn't survive a per-field split — captured as `[characterdetaileditor-listrow-row-draft-hook]` in PLAN.md); two more (active-purge `referenceSheetImageRef` + prune `_latestPendingByCharacter`) gate on character/universe-delete routes that don't exist yet (`[purge-reference-sheet-image-ref-on-sheet-delete]` and `[clear-pending-sheet-slot-on-entry-delete]`). Touched files: (1) `client/src/components/pipeline/CanonCard.jsx` + `client/src/components/universe/UniverseCanonSection.jsx` — bundled four character-only props (`universeId`, `onExpandCharacter`, `expanding`, `onSheetCompleted`) into a single `characterExtensions` object so the gate collapses to one truthiness check; NounsStage still passes nothing and stays focused. (2) New `client/src/lib/bibleLimits.js` mirrors `server/lib/storyBible.js` `BIBLE_LIMITS` verbatim; `CharacterDetailEditor.jsx`'s 25+ `max:` literals + `CanonCard.jsx`'s wardrobe `maxLength`s now reference the constants by name. (3) New `client/src/hooks/useFieldDraft.js` — single-field draft+blur hook used by `CharacterDetailEditor#DraftField` and a new per-row `WardrobeRow` sub-component (replaces the indexed `${idx}:${field}` drafts map in `WardrobeSection`). `ListRow`'s multi-column row-state (with sibling-draft "ride-along" race protection) was deliberately left as-is — splitting per-column would lose the protection. (4) `server/services/pipeline/refineHelpers.js` split into `runPromptRefineRaw` (lower-level: runStagedLLM + empty-guard + rationale-trim + optional logTag) and the existing `runPromptRefine` (single-field convenience wrapper built atop the raw variant); `server/services/universeCharacterExpand.js` now consumes `runPromptRefineRaw` with `logTag: null` so it can log a context-rich line after the merge. (5) New `makePathResolver(getRoot, { extensions, cache })` factory in `server/lib/fileUtils.js`; collapses `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` onto one closure. Thunk-only API (throws on non-function `getRoot`) so the late-binding semantics tests rely on (mutating `PATHS.images` at mock-eval time) stay correct; the resolver caches `rootAbsPrefix` lazily on first call. `resolveImageInputPath`'s root-prefix dispatch table is precomputed at module load. (6) New `shortId(id, n=8)` helper in `fileUtils.js` (null-safe); replaces inline `String(x).slice(0, 8)` in `universeCharacterExpand.js`, `universeCharacterSheet.js`, and `universeCanon.js` (the in-scope universe character family). Other call sites (shell, agents, cos) intentionally left alone — outside scope. (7) New `server/services/imageGenWaiter.js` (`createImageGenWaiter`) extracts the shared `imageGenEvents` completion-waiter pattern used by `server/routes/sdapi.js#createCompletionWaiter` (now a thin error-shape wrapper) and `server/services/voice/tools.js#image_gen` (drops the inline duplicate). The `universeCharacterSheet.js#subscribeToSheetJob` pattern stays distinct — it uses a different events bus (`mediaJobEvents`), an internal dispatcher that bounds listeners, callback-style handlers, and a two-stage timeout with `onStarted` reset. (8) `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` moved from `universeCharacterSheet.js` to `server/lib/canonPrompt.js` alongside `RICH_SPEC` so per-page render prompts can reuse them. (9) `CharacterReferenceSheetPanel.jsx#waitForImageRef` accepts an `AbortSignal`; a new `pollAbortRef` is wired into a useEffect-cleanup so unmount aborts the 3 s HEAD-poll loop (and the in-flight fetch) instead of letting it issue requests against a dead component. Sentinel `null` return distinguishes "aborted" from "give up + toast." Coverage: all 5566 server tests pass (added one BIBLE_LIMITS client-mirror drift test); all 92 client tests pass. Test files updated: `server/services/universeCanon.test.js` adds `shortId` to its `fileUtils.js` mock so the new log-line consumer doesn't break the lock-semantics tests.
-- **[solidify-character-descriptions-before-visual] Solidify character descriptions before visual render.** Closed as superseded by the character bible expansion + artist reference sheet work (PR #310). The original spec called for a "Solidify characters" sidebar action running an LLM pass to synthesize one canonical `physicalDescription` from accumulated evidence. The underlying goal — solid, render-ready character descriptions before visual stages — is now met via a different mechanism: `sanitizeCharacter` carries 15 prose fields + 5 structured lists (`stats`, `colorPalette`, `props`, `expressions`, `handGestures`); `POST /api/universe-builder/:id/characters/:entryId/expand` runs an LLM no-clobber fill-blanks pass over the extended fields; `POST .../render-reference-sheet` produces a single dense artist reference sheet image that becomes the visual canonical anchor (`character.referenceSheetImageRef`); and downstream pipeline stages already read `physicalDescription` via `canonPrompt`'s shared field-precedence helper. The accumulated-evidence synthesis primitive itself was not built; if it's needed later (e.g. multi-issue prose extraction starts drifting per-character `physicalDescription` and a one-click "consolidate" pass becomes valuable), it should be a fresh PLAN item against the post-#310 baseline, not this one.
-- **[bible-kind-setting-rename-to-place] Bible `SETTING` kind rename to `PLACE`.** Completes the rename deferred from migration 018 (PR #265, 2026-05-17): renames the bible-domain "setting" entity to "place" everywhere it's an identifier. Server: `BIBLE_KIND.SETTING` → `PLACE` (value `'place'`), `BIBLE_FIELD[PLACE]` → `'places'`, `sanitizeSetting` → `sanitizePlace`, `matchSettingsInText` → `matchPlacesInText`, `PLACE_INT_EXT`/`PLACE_TIME_OF_DAY`/`PLACE_DESCRIPTION_MAX` constants, `CATEGORY_KINDS` plural `'settings'` → `'places'`, writers-room route `/works/:id/settings` → `/works/:id/places`, service file `writersRoom/settings.js` → `places.js` with `listPlaces/createPlace/updatePlace/deletePlace/mergeExtractedPlaces` exports and `wr-place-` id prefix, validation schemas (`writersRoomPlaceCreateSchema`/`UpdateSchema`/`placeBibleCreateSchema`/`UpdateSchema`), `canonPrompt` SHORT_SPEC/RICH_SPEC keys (server + client mirror), `seriesCanon.pickCanon` returns `places`, `canonUsage` keys on `places`, importer KIND_MAP, `universeBuilder.compilePrompts` CANON_TRUNKS, `universeBuilderExpand` LLM prompt + envelope key `parsed.places`. Persisted state migrated by `scripts/migrations/022-rename-bible-setting-to-place.js`: walks `data/universe-builder.json` (renames `state.universes[].settings[]` → `places[]`, `categories[k].kind 'settings'` → `'places'`), `data/pipeline-series.json` (legacy `settings[]` → `places[]`), and `data/writers-room/works/<id>/settings.json` → `places.json` with the inner `settings` key rewritten to `places`. The migration also patches `data/prompts/stages/writers-room-places.md` + `_partials/bible-deference.md` to use `{{existingPlacesJson}}` + `"places": [` when they match the OLD shipped MD5; customized templates are left alone (the drift surfaces in `setup-data.js`'s hash-check warning, which now treats the post-022 hash as the new shipped baseline with the pre-022 hash auto-updatable alongside migration 007's pre-007 hash). Client UI flips to the new vocabulary: `UniverseBuilder.jsx` `TRUNK_TABS` `kind: 'places'`, `mergeCanonByName(..., 'place')`, `pendingCanonAdditionsRef.places`, `bucketsByKind.places`, `groupBucketsByKind` returns `{ characters, places, objects, other }`, `WORLD_CATEGORY_DEFAULT_KINDS` `landscapes/environments/structures → 'places'`. Component updates: `NounsStage.jsx` (key/singular/match), `CanonCard.jsx` (`kind.key === 'places'`), `UniverseCanonSection.jsx` (key/apiKind), `StoryboardPanel.jsx` (`places` prop, `onPlacesChange`, `onRunPlaces`, `placesCount`, `BIBLE_KINDS.world.propName: 'places'`), `WorkEditor.jsx` (`ANALYSIS_KIND.PLACES`, `places` state, `listWritersRoomPlaces`), `ProseReader.jsx` + `proseTokenizer.jsx` (`places` prop), `ProseTokenPopover.jsx` (`places` prop), `apiWritersRoom.js` (`listWritersRoomPlaces`/`createWritersRoomPlace`/`updateWritersRoomPlace`/`deleteWritersRoomPlace`), `SettingsBible.jsx` imports updated. Non-goals stay untouched: `data/settings.json`, the Settings page, `/api/settings` routes, app-level user-prefs — all keep "settings" terminology. Existing pipeline canon entry id prefix `set-` is preserved (ids are opaque after creation; changing the prefix would force a second migration over per-entry records — pure churn). All 5499 server tests pass; 77 client tests pass. ~30 files touched.
-- **[tabpills-pipelineissue-status-dot-trailing-slot] Extend `<TabPills>` with a `trailing` slot to migrate `PipelineIssue.jsx`.** Added an optional `t.trailing` ReactNode to the tab shape, rendered after the count in both `underline` and `pills` variants of `client/src/components/ui/TabPills.jsx`. Migrated `client/src/pages/PipelineIssue.jsx`'s previously-inlined stage tab row (the 11th outlier — its per-tab `STATUS_DOT[status]` indicator didn't fit the prior contract) onto `<TabPills>`, with the status dot supplied via `trailing`. Net 22-line bespoke `<button>` block collapsed onto the shared primitive; the row also picks up the standard mobile touch-target (`min-h-[44px]`) and icon size (16 vs 14) used elsewhere. +1 vitest case in `TabPills.test.jsx` pins the DOM-order contract (`trailing` follows `count`) in both variants; all 78 client tests pass.
-- **[sharing-inbox-live-subscription-badge] "🔄 live" badge on inbox subscription rows.** Subscription rows in the Sharing → Inbox tab now show a small green "live" pill (spinning RefreshCw icon + label) when `item.subscription` is truthy AND `item.receivedAt` is within the last 5 minutes. Re-exports fire on every record edit with a 3s server-side debounce and propagate via chokidar in <1s, so a row received that recently is a real-time signal that the sender is actively editing. Pure `isLiveSubscription(item, now=Date.now())` helper exported from `client/src/pages/Sharing.jsx` (handles null/undefined inputs + unparseable `receivedAt` + one-shot shares without throwing); 5 new vitest cases in `Sharing.test.jsx` cover all four exit paths. Badge placement is inline in the row's metadata strip alongside source/kind/timestamp; freshness is computed on render so the badge naturally decays when the page re-renders (via socket updates) past the 5-min mark. All 82 client tests pass.
-- **[nounsstage-cheaper-seriesnamemap-fetch] NounsStage seriesNameMap — avoid the heavy canon-usage fetch.** `NounsStage.jsx` was calling `GET /api/universe-builder/:id/canon-usage` purely to extract `seriesNameMap` for the CanonCard "from <series>" chip, which makes the server iterate every linked series × every issue × 3 prose matchers — O(series × issues × matchers) work for what should be O(series). Picked option (a) from the PLAN: new `GET /api/universe-builder/:id/series-names` endpoint returns `[{id,name}]` for linked series only, with no per-issue prose scan and no matchers. Backed by `listLinkedSeriesNames` in `server/services/canonUsage.js` (validates the universe via `getUniverse` so 404s mirror the heavier endpoint, then `listSeries().filter(s.universeId === id).map(s ⇒ ({id, name}))`). Client helper `getUniverseSeriesNames` in `apiUniverseBuilder.js`; `NounsStage` builds the map locally with `Object.fromEntries(list.map(...))`. `UniverseCanonSection` continues to use `canon-usage` because it actually needs the per-entry usage counts. +3 vitest cases in `canonUsage.test.js` (linked-series filter + ignores issues; empty result for no-linked universe; 404 for missing universe).
-- **[importer-review-ui-extract-canoncard-once-universe] Importer review UI shares the canon-card shell.** `Importer.jsx#CanonReviewSection` no longer hand-rolls its own checkbox card — it renders through the shared `EntryCard` primitive (the post-Phase-2 shell that `CanonCard` and `VariationCard` already render through). The full `CanonCard` contract (id-bearing entries, image refs, lock/refine/wardrobes, intExt/timeOfDay chips) doesn't fit the importer's pre-commit LLM output, so the cleanest "extract" was to lift the visual primitive instead. `EntryCard.jsx` gains a new `selectable={{ selected, onToggle, label? }}` slot: when provided, the card overlays a `<label htmlFor>` across the padded surface (so the entire bordered card area toggles the checkbox, matching the prior inline card's full-card click target), renders an aria-labelled checkbox column with a unique `useId`, and swaps the `locked` accent for select-on (`border-port-accent bg-port-accent/5`) vs. select-off (`border-port-border opacity-60`) styling. Selectable mode uses `p-3` padding to match the pre-extract Importer card's spacing; `actions` and clickable (`onClick`) `thumbnail` slots sit on a `relative z-10` layer above the overlay so they stay independently clickable without nesting interactive controls inside a `<label>` (invalid HTML). 9 vitest cases in new `client/src/components/universe/EntryCard.test.jsx` cover: checkbox omitted when `selectable` is null, `selected`-bound state, `onToggle` fires on click, selected vs. unselected accent class application, the generic-label fallback, full-card overlay click toggles selection, action buttons stay outside the label and fire independently, and `p-3` spacing parity. All client tests pass; client build succeeds.
-- **[sharing-inbox-orphans-on-peer-instance-id-rotation] Cull rotation-orphan inbox rows.** Closes the regression introduced by `[sharing-v2-per-sender-subscription-filenames]`: a peer that rotates its `senderInstanceId` (factory reset / new device) would otherwise leave its old identity's inbox row stranded forever, because the per-sender dedup keys on the new id. `applyInbox` in `server/services/sharing/importer.js` now culls cross-sender orphans on every subscription-manifest arrival when (a) same `(recordKind, recordId, source)`, (b) DIFFERENT `senderInstanceId`, and (c) existing row's `createdAt` older than the 30-day `ROTATION_CULL_MS` window. The window is conservative — two legitimately distinct peers sharing the same display name (e.g. both devices named "MacBook") would only be culled after a month of one going silent. 4 new integration tests in `integration.test.js` (cull at 60 days, preserve at 2 days, preserve different-source-old, and a freshness-gate early-return regression that asserts the cull still persists when the `inbox-has-newer` short-circuit fires). 79 sharing tests pass.
-- **[content-addressed-asset-dedup-today-asset-copies] Content-addressed asset dedup.** Share-bucket asset blobs are now stored content-addressed at `<bucket>/assets/blobs/<sha256>` (sidecar metadata at `<sha256>.metadata.json`) instead of filename-addressed at `assets/{images,videos}/<filename>`. Two manifests referencing identical bytes under different filenames now share one on-disk blob — every additional reference is a no-op file-existence check on the same hash. New shared helper `sha256File` in `server/lib/fileUtils.js` (one-shot < 512 KB / streaming ≥ 512 KB); `server/services/backup.js#generateManifest` migrated to the same helper (its inline reimplementation deleted). Path/sidecar helpers (`bucketBlobsDir`, `bucketBlobPath`, `bucketBlobSidecarPath`, `imageSidecarName`, `IMAGE_EXT_RE`) live in `server/services/sharing/buckets.js` so storage-layout changes touch one file. `exporter.js#copyAssetIfPresent` computes the hash and returns `{ kind, ref, hash }` per asset; `importer.js#copyAssetsLocally` resolves bucket paths via a `resolveBucketAssetPaths` helper that prefers `assets/blobs/<hash>` when present and falls back to legacy `assets/{kind}/<filename>` for v1 manifests still in-bucket. `SHARING_SCHEMA_VERSION` bumped 1 → 2; bucket layout adds `assets/blobs/` in `ensureBucketLayout`. `annotationsSync.js#listBucketAssetKeys` now derives the user-facing filename set by scanning manifests' `assetRefs` (with the legacy dir scan retained as a fall-through for v1 buckets). Coverage: 4 new unit tests in `fileUtils.test.js` (small/large split, cross-path identical-bytes equality, distinct-bytes inequality) + 2 new integration tests in `integration.test.js` (two manifests with different filenames + identical bytes share one blob and import cleanly; v1 manifest without `hash` field still imports via legacy path) + updated existing integration assertions to expect `assets/blobs/<hash>` paths. All 249 server test files / 5452 tests pass. Two performance follow-ups captured in PLAN.md: per-source hash caching on the exporter, and per-bucket manifest-scan caching on the annotation flush path.
-
-### 2026-05-17
-
-- **[sharing-v2-per-sender-subscription-filenames] Per-sender subscription filenames.** `subscriptionFilename()` now keys on the `senderInstanceId` segment (`sub-<kind>-<recordId>-<senderInstanceId>.json`) so two peers subscribed to the same record write to distinct bucket files instead of clobbering each other. Touched `server/services/sharing/manifest.js` (signature + new `legacySubscriptionFilename` export + `manifestFilename` plumbs `manifest.senderInstanceId` through to the helper + extracted `SUBSCRIPTION_FILE_PREFIX` constant shared with the prune filter), `subscriptions.js` (`unsubscribe` now reads `getInstanceId()` for the new name AND best-effort cleans up the pre-v2 legacy file only when its `senderInstanceId` matches this instance — so a still-subscribed peer's pre-upgrade file isn't stomped), `importer.js` (inbox dedup now keys on `(recordKind, recordId, senderInstanceId)` so peerB's update no longer wipes peerA's inbox row), and the `exporter.js` doc comment. Coverage: 3 new tests in `subscriptions.test.js` (filename-with-sender, legacy cleanup gated on own instance, legacy preserved for other peer's instance), 2 new in `manifest.test.js` (per-sender determinism + two-peer-distinct + `legacySubscriptionFilename` shape), and integration test updated to assert the new naming. All 5,315 server tests pass. Follow-up captured in PLAN.md as `[sharing-inbox-orphans-on-peer-instance-id-rotation]` — per-sender dedup means a peer that rotates its instanceId leaves their old inbox row as an orphan (pre-v2 dedup wiped it implicitly).
-- **[extend-syncorchestrator-to-cover-pipeline-universe] Extend `syncOrchestrator` to cover pipeline + universe categories.** Two new snapshot-based sync categories (`pipeline`, `universe`) in `server/services/dataSync.js`, registered in `CATEGORIES`, added to `DEFAULT_SYNC_CATEGORIES` in `server/services/instances.js`, exposed via `categoryParam` enum in `server/routes/dataSync.js`, and surfaced in the peer-config UI via `SYNC_CATEGORY_META` entries (Sparkles / Film icons) in `client/src/pages/Instances.jsx`. Pipeline bundles `pipeline-series.json` + `pipeline-issues.json` into one snapshot; universe ships only `universe-builder.json` `universes[]` (skips ephemeral `runs[]`). Merge is array-by-id LWW on `updatedAt` — routed through dedicated service-level merge entry points (`mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync`) so the read-modify-write runs INSIDE the per-file write queue and each incoming record passes through the service's sanitizer (`sanitizeTemplate` / `sanitizeSeries` / `sanitizeIssue`) on the way in — concurrent local edits can't clobber the merged remote payload, and older-schema peers land already-migrated. `applyPipelineRemote` returns `{ applied, count, seriesChanged, issuesChanged }` where `count` is records actually changed/added this cycle. Sync is record-level only — image/video blobs continue to flow through the share-bucket system. 13 vitest cases in `server/services/dataSync.pipelineUniverse.test.js` (snapshot shape, checksum stability, missing-file tolerance, LWW merge for insert/update/no-op, local-only `runs[]` preservation, partial-write skip, count-semantics for changed-side-only). Deferred follow-ups: `[datasync-migrate-categories-to-atomicwrite]` (collapse the 6+ duplicate `ensureDir + writeFile + JSON.stringify` sites to `atomicWrite`) and `[datasync-checksum-only-fast-path]` (avoid materializing the full payload just to hash it).
-- **[extract-upsertbyidprepend-helper-universe-builder] Extract `upsertByIdPrepend(list, item)` helper.** New `client/src/lib/upsertByIdPrepend.js` collapses the "filter-by-id then prepend" worlds-list upsert into one helper. The PLAN line called out 3 sites; the actual count was 7 — all collapsed to `setWorlds((prev) => upsertByIdPrepend(prev, entity))`: 1 in `client/src/hooks/useUniverseAction.js` (LLM-action result merge) + 6 in `client/src/pages/UniverseBuilder.jsx` (`handleCreate`, `handleSave`, expand auto-save, refine auto-save, `handleMoveCategoryToTrunk`, `handleGenerateInCategory`). 4 new vitest cases in `upsertByIdPrepend.test.js` (new-id prepend, id replacement, empty-list, no input mutation).
-- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
-- **[canoncard-from-series-name-full-provenance-label] CanonCard "from series: <name>" full provenance label.** The provenance chip now reads `seriesNameMap?.[entry.sourceSeriesId]` to render `from <Series Name>` with `Introduced by series "<name>" (<id>)` in the tooltip; missing-name fallback preserves the existing `from series` label + id-only tooltip. Chip rendering extracted into a `SourceSeriesChip` helper alongside `ChipPicker` / `ReadonlyChip` in `client/src/components/pipeline/CanonCard.jsx`. Map plumbed from both parents: `UniverseCanonSection.jsx` passes `usage?.seriesNameMap` (no new fetch — reuses the canon-usage call it already makes), and `NounsStage.jsx` fetches `getUniverseCanonUsage(series.universeId)` once on universe load. Server-side `getUniverseCanonUsage` (`server/services/canonUsage.js`) gains a top-level `seriesNameMap: { [seriesId]: name }` field built from every `linkedSeries` (not just ones with prose-match rows) so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Coverage: 4 new vitest cases in `CanonCard.test.jsx` (chip omitted with no `sourceSeriesId`; generic fallback when map missing; resolved name + dual-tooltip when present; fallback when id not in map) and 2 new `canonUsage.test.js` cases (linked-with-no-prose-match included; empty map when no series link). NounsStage's per-render fetch is acknowledged as quadratic-cost relative to need; deferred to `[nounsstage-cheaper-seriesnamemap-fetch]` for a thin-endpoint follow-up.
-- **[multi-reference-image-editing-for-flux-2-ui] Multi-reference image editing for FLUX.2 — UI + server contract.** New 4-slot reference-image picker on the Image Gen page, gated on FLUX.2 models (`isFlux2Model`). Each populated slot uploads as `referenceImage1`…`referenceImage4` over multipart with a parallel `referenceStrengths` array (0..1 per slot). Server-side: `optionalUploadFields` helper added to `server/lib/multipart.js`; `generateSchema` in `server/routes/imageGen.js` accepts the new `referenceStrengths` array (max 4, 0..1 per entry); the route resolves the effective backend (`local` / `external` / `codex`) BEFORE staging any uploads and rejects with `REFERENCE_IMAGES_LOCAL_ONLY` for non-local backends + `REFERENCE_IMAGES_FLUX2_ONLY` for non-FLUX.2 models (no orphan files written; both pre-stage rejects also unlink the multer-staged `os.tmpdir()` files). It then packs filled slots in submit order, copies each into a sibling `data/image-refs/ref-<uuid>.<ext>` directory (kept out of `data/images/` so the gallery's flat `.png` enumeration never surfaces them), and threads `referenceImagePaths`/`referenceImageStrengths` arrays through `server/services/imageGen/local.js` to `buildArgs`, which emits `--reference-images <p1> <p2> ...` + `--reference-strengths <s1> ...` to the FLUX.2 Python runner. Defense-in-depth: a new `resolveImageRef` helper in `fileUtils.js` mirrors `resolveGalleryImage` but anchors at `PATHS.imageRefs`; paths and strengths are paired BEFORE filtering so a rejected entry can't shift strengths onto the wrong surviving image; the `clampStrength01` helper falls back to a finite default for NaN/non-finite inputs so a corrupt sidecar replay can't serialize `NaN` into metadata or the CLI flag; sidecar metadata records `referenceImageFilenames`/`referenceImageStrengths` for replay. The UI shows an "Experimental — no-op today" banner above the slot grid: the Python runner ignores the new flags but accepts them via no-op `--reference-images`/`--reference-strengths` argparse stubs in `scripts/flux2_macos.py` — without those the route would break every existing single-init FLUX.2 render with "unrecognized arguments." Full multi-reference diffusers wiring + the `FLUX.2-klein-9B-kv` model swap is captured as `[flux2-multi-reference-python-runner]` in PLAN.md (gated on HF license acceptance). 12 new tests: 3 in `local.test.js` (buildArgs multi-ref branches), 3 in `imageGen.test.js` (schema validation), 6 in `imageGen.multipart.test.js` (real-multipart route packing — verifies `referenceImagePaths`/`referenceImageStrengths` land in submit order, gaps in slot numbering collapse to a packed array via post-filter index pairing, missing strengths default to 1.0, ref files land in `PATHS.imageRefs` not `PATHS.images`, a non-FLUX.2 modelId with refs gets a 400 before any file is staged, refs on a non-local backend get a 400, AND rejected non-FLUX.2 uploads don't leak `upload-*` files under `os.tmpdir()`).
-- **[extract-useuniverseaction-hook] Extract `useUniverseAction` hook from `UniverseBuilder.jsx`.** New `client/src/hooks/useUniverseAction.js` consolidates the scaffolding shared by `handlePromoteVariation` + `handleAutoSort`: `selectedId` guard, per-action ref re-entrancy, `capturedId` snapshot, loading-toast lifecycle (`silent: true` + `.catch` → dismiss + error), mountedRef-gated busy reset, always-update `setWorlds`, and the `mountedRef.current && capturedId === selectedId` stale-write guard. Each caller now passes only what varies — its `ref`/`setBusy`/`loadingMessage`/`errorPrefix`/`notSavedMessage`, the API call (receives `capturedId`), and an `onFreshResult(result)` callback that does the selective `setDraft` and returns the success-toast string. `handleGenerateInCategory` is intentionally NOT a consumer (the PLAN line's "to a lesser extent" — eager local merge first + best-effort save is a different shape; forcing it through would warp it); the hook header documents this. 9 new vitest cases in `useUniverseAction.test.jsx` (selectedId guard, re-entrancy, happy path, stale-write, action-rejects, no-loading-toast variant, falsy-universe result, suppressed-toast onFreshResult, unmount mid-flight). PLAN.md description gated this on "extract when a 4th handler lands"; promoted now with 3 — the hook itself is small and the scaffold is the most-bug-prone piece of these handlers.
-- **[extract-builduniversestylecontext-helper] Extract `buildUniverseStyleContext(universe, options)` helper.** New helper in `server/services/universeBuilder.js` (next to `joinInfluenceList`) renders the shared "Universe context" prompt block (LOGLINE / optional PREMISE / STYLE NOTES / optional EMBRACE INFLUENCES). Three call sites collapsed: `buildAutoSortPrompt` (`universeBuilderAutoSort.js`, `escape: true`), `buildPromotePrompt` (`universeBuilderPromote.js`, default opts + headerSuffix), and `buildCategoryGeneratePrompt` (`universeBuilderExpand.js`, `includePremise: true` + `includeEmbrace: false` since it has its own influences section). Toggles cover the actual variance: `includePremise`, `includeEmbrace`, `escape` (newline/control-char stripping for defense-in-depth), `headerSuffix` (per-call header framing). 9 new unit tests in `universeBuilder.test.js` assert byte-exact outputs for each call shape. Pipeline call sites at `visualStages.js` and `seriesTitleLogo.js` were inspected but are out of scope — they only use `joinInfluenceList` for render-style composition and template variables, not the LOGLINE/STYLE NOTES/EMBRACE block. `buildExpansionPrompt`'s "Current universe state" block also stays separate — its `[LOCKED]` flags + `LOCKABLE_FIELD_LABELS` make it too distinct to fold without compromising the helper.
-- **[extract-descriptorforcanonentry-kind-entry-into] Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** New `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror is the single source of truth for per-kind canon descriptor fields. Exports `shortCanonDescriptorFragments` (UI summary scope: physicalDescription || description for chars; description + Palette + recurringDetails for settings; description || significance for objects), `richCanonDescriptorFragments` (adds role, era, weather, significance-as-additive — the render-prompt scope), `descriptorForCanonEntry` (flattened short string matching legacy `KINDS[].descFor`), and `hasCanonDescriptorContent` (rich-field union for "is there anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` (`server/services/universeBuilder.js`), `KINDS[].descFor` (`client/src/components/universe/UniverseCanonSection.jsx`), `canonEntryHasContent` (`client/src/pages/UniverseBuilder.jsx`), and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Tests: 29 new in `server/lib/canonPrompt.test.js`. Minor cosmetic uniformity in canon render prompts: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes are now capitalized (`Palette:` etc.) to match the UI descriptor format — case-only diff, no functional impact on diffusion models.
-- **[auto-sort-with-ai-llm-classify-each-kind-other] Universe Builder — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` (server: `server/services/universeBuilderAutoSort.js`, `server/routes/universeBuilder.js`) batches every `kind: 'other'` bucket into a single LLM call that returns `{ classifications: [{ key, kind, suggestedKey? }] }`. The service applies kind reassignments atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds); `suggestedKey` renames stay opt-in — they surface as a count in the success toast but the bucket key isn't auto-renamed. Replaces the Other-tab's toast-stub `onAutoSort` handler with a real spinner-driven handler in `client/src/pages/UniverseBuilder.jsx`; new `autoSortBuckets` API helper in `client/src/services/apiUniverseBuilder.js`. Concurrent-edit safety: the service re-fetches the latest universe state immediately before the write so a variation added to a soon-to-be-classified bucket in another tab during the LLM call isn't overwritten; the client merges only the reclassified buckets into the draft to preserve user edits to other buckets. Covered by 16 unit tests in `universeBuilderAutoSort.test.js` (happy path, no-other-buckets short-circuit, hallucinated-key filter, `LLM_INVALID_JSON` (empty response + no-parse + non-array `classifications`) vs `NO_CLASSIFICATIONS` paths, `NO_PROVIDER` gate, prompt-injection defense — ASCII newlines pinned on labels + styleNotes + logline; Unicode LS/PS/NEL + form feed + vertical tab pinned on labels, logline, and styleNotes) + 4 route tests in `universeBuilder.test.js` + 2 client tests in `UniverseBuilder.test.jsx` for `OtherTab` (Auto-sort button fires `onAutoSort` when enabled; disabled with "Sorting…" label while `autoSorting=true`).
-- **[extract-a-shared-tabpills-primitive-in-client-src] Extract a shared `<TabPills>` primitive in `client/src/components/ui/`.** New `client/src/components/ui/TabPills.jsx` with two variants (`underline` default + `pills` for UniverseBuilder) and knobs for the call-site quirks: `runningKind` (StoryboardPanel's per-tab spinner), `stretch` (flex-1 equal-width tabs), `mobileDropdown` (UniverseBuilder's `<select>` fallback), `hideLabelOnMobile` (Brain/DigitalTwin/ChiefOfStaff icon-only at < sm), `controlsIdPrefix` (ChiefOfStaff's `aria-controls` wiring), `listRef`+`onScroll` (ChiefOfStaff's scroll-arrow overlay). Migrated ten call sites — two local `TabNav` components (UniverseBuilder, StoryboardPanel) plus eight inline tab-button blocks (Brain, Calendar, ChiefOfStaff, DigitalTwin, MediaGen, Messages, Settings, Wiki). Net -250+ LOC consolidated into one primitive + 7 vitest cases. Small intentional visual unification across the surface area: StoryboardPanel active text-white → text-port-accent, ChiefOfStaff/Settings gained the standard `bg-port-accent/5` active wash + `hover:bg-port-card` inactive. PipelineIssue's status-dot tab variant is captured in PLAN.md as a follow-up needing a `trailing` slot extension on the primitive.
-- **[unify-canoncard-variation-card-into-a-single] Universe Builder — unify CanonCard + variation card into shared `EntryCard` shell.** New `client/src/components/universe/EntryCard.jsx` slot-based primitive (locked accent, title row, body, action column, optional thumbnail, optional footer). `CanonCard` now renders through it and surfaces a top-left thumbnail derived from `primaryImageRef` (falling back to the first `imageRefs[0]`) so each canon entry has a visual at-a-glance. The variation `<li>` in `CategoryEditor` is extracted into a `VariationCard` helper that also renders through `EntryCard` — view mode shows label + prompt + action column (promote / render / lock / edit / remove); edit mode swaps the body for an inline form. Visual consistency between the two card families now flows from the shared shell rather than parallel Tailwind class strings.
-- **[client-component-tests-for-categoryeditor-promote] Client component tests for `CategoryEditor` + `TrunkView`.** Wired up the first vitest-based client test suite (vitest 3 + jsdom + @testing-library/react + user-event) — new `client/vitest.config.js`, `client/src/test/setup.js`, `test` + `test:watch` scripts in `client/package.json`, CI step in `.github/workflows/ci.yml`. Named-exported `CategoryEditor` and `TrunkView` from `client/src/pages/UniverseBuilder.jsx` and added `client/src/pages/UniverseBuilder.test.jsx` covering: promote button disabled when `!canPromote` (parent's `!selectedId`); promote fires directly with no targetKind for a kinded bucket; clicking promote on a `bucketKind: null` ("other") variation opens the trunk picker; clicking a picker option calls `onPromote(variation, { targetKind })` with the correct kind; `TrunkView` "Bulk-render all" button disabled at zero count and enabled with the right count from variations. Three pre-existing orphaned client tests (`cleanPlatePrompt`, `clipboard`, `normalize`) now run too.
-
-- **CoS — explicit `init()` instead of module-level auto-init.** Dropped the `NODE_ENV !== 'test' && VITEST !== 'true'` guard from `server/services/cos.js`; `init` is now exported and called from `server/index.js` alongside the other startup `*.init()` calls. Test imports no longer spin up event listeners / timers as a side effect, and the prod boot path no longer branches on test-env vars.
-- **Universe Builder DRY — `resolveProviderAndModel` + `findBibleEntryByName`.** Two shared helpers landed in `server/lib/`. The first collapses four inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains across the universe-builder LLM entrypoints onto one helper; the second consolidates the "case-insensitive name OR alias" predicate at the promote duplicate-collision check. (The retired-characters bucket fold keeps its O(1) seen-set index since it folds entries into a growing array — a per-iteration linear scan would have made it O(n*m).)
-- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."
-- **Importer — section follow-ups landed.** Auto-detect content type stage (`importer-classify`, light-tier head pass that pre-selects the radio); in-place `proseExcerpt` edit affordance per issue card so users can trim/correct boundaries without re-running Analyze (3 heavy-tier calls); `replaceMode` flag wipes existing issues + overwrites arc/seasons on re-import (destructive opt-in for existing series); partial-commit retry now drops arc/seasons/canon from the retry payload via `arcAlreadyPersisted` context so a parallel-tab edit isn't overwritten; React.memo on per-issue and per-season cards (with stable patcher + memoized seasonOptions) so unedited cards skip render on keystroke; `ARC_SHAPE_IDS` exposed via `/importer/config` and `IMPORTER_ARC_ROLES_FALLBACK` retired from the client (server is now the sole source of arc roles + shape ids); screenplay-prompt split logic gates on `isUserRequestedCount` rather than conflating it with the per-type default; "(first season)" UI label replaced with the actual lowest-numbered season + title.
-- **Sharing — auto-unsubscribe on local record delete.** `recordEvents.js` now hooks `deleteSeries` / `deleteUniverse` so orphaned `data/sharing/subscriptions.json` entries clean up automatically instead of logging errors on the next re-export attempt.
-- **Pipeline — `spawningTasks` lifecycle.** Widened try/finally around `spawnAgentForTask` (`server/services/agentLifecycle.js`) so a throw in any async setup step releases the per-task spawn lock instead of stranding it forever.
-- **Pipeline — `creativeDirectorPrompts.test.js` imageStrength assertions.** Test now matches the updated prompt template wording; full suite passes.
-- **Importer — Create Suite reverse-engineering page.** `/importer` analyzes a finished story / novel / screenplay / comic script and produces universe canon + series arc + prose-seeded issues; three new stage prompts with Mustache content-type branching; case-insensitive find-or-create; locked-arc gating.
-- **Universe-as-Canon Phase B.4 schema teardown.** Removed `series.{characters,settings,objects}` from sanitizer + Zod schemas; deleted `extractAndMergeIntoSeries` / `refineCharacterDescription` / `nounRefine.js` / `purgeImageRefFromAllSeries`; routes `POST /pipeline/series/:id/extract-bible` + `/characters/:entryId/refine` removed; `seriesCanon.js` simplified to universe-or-empty.
-- **Universe Canon UX follow-ups.** Per-series filter dropdown on Universe Canon page (`?series=<id>` URL param); "Appears in" list sorted by `issueCount`; per-series `stylePromptOverride` wired through `applyWorldStyle` + NounsStage previews.
-- **Sharing v1.4 — collection-aware universe shares.** `mediaCollections.universeId` links a collection to its parent universe; exporter bundles the collection + items + assets + media-job records; importer find-or-creates the local collection and unions items; item add/remove emits `recordEvents` on the linked universe so subscriptions auto-re-export.
-- **Sharing — route-level tests for `server/routes/sharing.js`.** New `server/routes/sharing.test.js` covers bucket CRUD, export (kinds + missing-payload refinement), inbox actions, subscriptions, activity, and error mapping (28 tests). Locks the HTTP/JSON contract (Zod rejection + 201 vs 200 + service-error code passthrough) that integration.test.js + subscriptions.test.js previously bypassed by exercising the service layer directly.
-- **Sharing — manifest archive pruning.** Long-lived sharing buckets no longer accumulate thousands of one-shot manifest JSONs; owned manifests over the cap are archived (peer/subscription manifests exempt).
-- **Sharing — display-name & bio settings tab.** Source-attribution fields now also editable under `/settings/sharing`.
-- **Pipeline — Story Arc Planning.** PipelineSeries rebuilt into an Arc → Season → Episode tree with three LLM passes (arc overview, per-season episodes, cross-season verify) and a two-pane bible-sidebar + card-canvas layout.
-- **Writers Room ↔ Pipeline unification.** Shared story-bible schema (Character/Setting/Object), staged-LLM runner, scene-prompt composer, bible-extraction service, prompt-template partials, "Promote work to Pipeline" bridge, and Storyboards auto-fill from prose or TV script.
-- **Creative Director — episode video end-to-end.** Pipeline `episodeVideo` stage wires storyboards → CD treatment → render → final stitched MP4 inline; slim API endpoint, ScenePreview component, multi-frame evaluator sampling, auto-accept ffprobe watchdog, cheaper smoke-test fixture, per-scene `imageStrength` for i2v continuity.
-- **CoS — Workflow tab.** Left-to-right pipeline view of all scheduled tasks + autonomous jobs grouped into seven canonical stages with `runAfter` dependency arrows.
-- **CoS — review-loop auto-merge.** Tasks with `openPR + reviewLoop` now spawn a follow-up agent that polls Copilot, pushes fixes until clean, and `gh pr merge --squash --auto`.
-- **CoS — dismissible AI recommendations.** Per-card X dismisses Learning Analytics suggestions; count-based alerts only re-surface on significant growth.
-- **World Builder for Media Gen.** One-line starter prompt expands via LLM into a structured prompt set (style prefix, negative, 6–10 variations across five buckets) and batch-renders into an auto-named Media Collection.
-- **Civitai / Z-Image follow-ups (six cleanups).** `RUNNER_FAMILIES` constants module, shared `deepMerge` / `assertSafeFilename` utilities, drift-warning for `mediaModels.js`, and CLI `--model` flag now honored across claude-code + gemini-cli + codex.
-- **Shared `<Modal>` component.** Nine modal call sites converged onto one accessible Modal with backdrop + Esc + portal + ARIA.
-- **Shared LLM / JSON / Python runner helpers.** Unified four near-identical "call provider, accumulate text, reject on error" implementations into `promptRunner.js`; consolidated three CLI-banner JSON extractors into `jsonExtract.js`; extracted ~200 LOC of duplicated device/HF-error handling from flux2 + z-image Python runners into `_runner_common.py`.
-- **Video Gen — LTX-2.3 capabilities.** Native audio-to-video (a2v) on dgrauet (WAV/MP3 + optional first-frame conditioning); native Extend pipeline replacing the legacy chained-i2v fallback; FFLF keyframe-pair guidance hint; deprecated notapalindrome models grouped under "Legacy".
-- **Pipeline — auto-run resumption.** On boot, stuck `running` issues demote to `needs-review` so a crash mid-run doesn't strand the pipeline.
-
-## 2026-04
-
-- **Global Command Palette (⌘K).** Single nav manifest (`navManifest.js`) shared by palette + voice agent's `ui_navigate`; any new page registered there is instantly keyboard- and voice-reachable.
-- **Customizable Dashboard with Saved Layouts.** 15-widget registry + named layouts (`default` / `focus` / `morning-review` / `ops`) with drag/resize Arrange mode; `⌘K` switches layouts by name.
-- **Ask Yourself.** Conversational `/ask` mode with parallel retrieval across memory + brain notes + autobiography + goals + calendar; voice `ui_ask` entry point with intent-classifier gating; per-turn promotions ("Save as Brain note" / "Create CoS task" / "Attach to Goal…").
-- **God-file decomposition.** `routes/cos.js`, `routes/scaffold.js`, `client/api.js`, `services/digital-twin.js`, and `subAgentSpawner.js` split into focused modules.
-- **Better-Audit remediation.** Security overrides for transitive deps (path-to-regexp, lodash, basic-ftp, etc.), centralized helpers (`pgQuoteIdentifier`, `escapeJql`, `atomicWrite`), graceful SIGTERM/SIGINT shutdown, fetch-timeouts via `AbortSignal.timeout` across remaining sites, and significant CoS-route test coverage expansion (83–100%).
-
-## 2026-03
-
-- **Depfree audit (heavy mode).** Removed 13 third-party packages (`uuid`, `cors`, `axios`, `multer`, `unzipper`, `node-telegram-bot-api`, `supertest`, `geist`, `globals`, `fflate`, `react-markdown`, `react-diff-viewer-continued`, `react-hot-toast`) by writing ~1,100 lines of owned in-tree replacements.
-- **Keyboard Shortcuts Help Modal.** Press `?` for a global accessible overlay listing all shortcuts grouped by section.
-- **Code-hardening pass.** `response.ok` checks across PromptManager fetches, type-safe sort comparators, replaced silent catches with logging, optional-chaining on DB row access, centralized 15 path constants in `PATHS`, migrated 36 files to centralized paths, replaced 57 `mkdir({recursive:true})` with `ensureDir()`.
-
----
-
-## Numbered Milestones (M0–M56)
-
-These are the major capability landmarks the app reached over its life. Each links to a feature doc where one exists.
-
-- [x] **M0–M3**: Bootstrap, app registry, PM2 integration, log viewer — Core infrastructure
-- [x] **M4**: App Wizard — Register existing apps or create from templates. See [App Wizard](./docs/features/app-wizard.md)
-- [x] **M5**: AI Providers — Multi-provider AI execution with headless Claude CLI
-- [x] **M6**: Dev Tools — Command runner with history and execution tracking
-- [x] **M8**: Prompt Manager — Customizable AI prompts with variables and stages. See [Prompt Manager](./docs/features/prompt-manager.md)
-- [x] **M9**: Streaming Import — Real-time websocket updates during app detection
-- [x] **M10**: Enhanced DevTools — Provider/model selection, screenshots, git status, usage metrics
-- [x] **M11**: AI Agents Page — Process detection and management
-- [x] **M12**: History Improvements — Expandable entries with runtime/output capture
-- [x] **M13**: Autofixer — Autonomous crash detection and repair. See [Autofixer](./docs/features/autofixer.md)
-- [x] **M14**: Chief of Staff — Autonomous agent manager with task orchestration. See [Chief of Staff](./docs/features/chief-of-staff.md)
-- [x] **M15**: Error Handling — Graceful error handling with auto-fix. See [Error Handling](./docs/features/error-handling.md)
-- [x] **M16**: Memory System — Semantic memory with LLM classification. See [Memory System](./docs/features/memory-system.md)
-- [x] **M17**: PM2 Config Enhancement — Per-process port detection and CDP_PORT support
-- [x] **M18**: PM2 Standardization — LLM-powered config refactoring
-- [x] **M19**: CoS Agent Runner — Isolated PM2 process for agent spawning. See [CoS Agent Runner](./docs/features/cos-agent-runner.md)
-- [x] **M20**: AI Error Handling — Enhanced error extraction and CoS integration
-- [x] **M21**: Usage Metrics — Comprehensive AI usage tracking and mobile UI
-- [x] **M22**: Orphan Auto-Retry — Automatic retry for orphaned agents
-- [x] **M23**: Self-Improvement — Automated UI/security/code analysis with Playwright
-- [x] **M24**: Goal-Driven Mode — COS-GOALS.md mission file and always-working behavior
-- [x] **M25**: Task Learning — Completion tracking and success-rate analysis
-- [x] **M26**: Scheduled Scripts — Cron-based automation with agent triggering
-- [x] **M27**: CoS Capability Enhancements — Dependency updates, performance tracking, learning insights
-- [x] **M28**: Weekly Digest UI — Visual digest with insights and comparisons
-- [x] **M29**: App Improvement — Comprehensive analysis extended to managed apps
-- [x] **M30**: Configurable Intervals — Per-task-type scheduling (daily, weekly, once, on-demand)
-- [x] **M31**: LLM Memory Classification — Intelligent memory extraction with quality filtering
-- [x] **M32**: Brain System — Second-brain capture and classification. See [Brain System](./docs/features/brain-system.md)
-- [x] **M33**: Soul System — Digital twin identity scaffold management. See [Soul System](./docs/features/soul-system.md)
-- [x] **M34**: Digital Twin — Quantitative personality modeling and confidence scoring. See [Digital Twin](./docs/features/digital-twin.md)
-- [x] **M35**: Chief of Staff Enhancement — Proactive autonomous agent with hybrid memory, missions, LM Studio, thinking levels. See [CoS Enhancement](./docs/features/cos-enhancement.md)
-- [x] **M36**: Browser Management — CDP/Playwright browser page
-- [x] **M37**: Autonomous Jobs — Recurring scheduled jobs the CoS executes using digital-twin identity
-- [x] **M38**: Agent Tools — AI content generation, feed browsing, autonomous engagement for Moltbook agents
-- [x] **M39**: Agent-Centric Drill-Down — Agent-first hierarchy with deep-linkable URLs and scoped sub-tabs
-- [x] **M40**: Agent Skill System — Task-type-specific prompts and deterministic workflow skills. See [Agent Skills](./docs/features/agent-skills.md)
-- [x] **M41**: CyberCity Immersive Overhaul — Procedural synthwave audio, post-processing, reflective wet-street ground (Phase 1 operational legibility shipped 2026-05)
-- [x] **M42**: Unified Digital Twin Identity System — Identity orchestrator, chronotype derivation, personalized taste prompting, behavioral feedback loop, mortality-aware goal tracking, Identity Tab dashboard
-- [x] **M43**: Moltworld Platform Support — Second platform integration for AI agents in a shared voxel world
-- [x] **M44**: MeatSpace — Health tracker with death clock, LEV 2045 tracker, alcohol/blood/body/epigenetic/eye tracking, lifestyle questionnaire, TSV import, Apple Health integration
-- [x] **M45**: Data Backup & Recovery — Rsync incremental backup with SHA-256 manifests, `pg_dump`, configurable cron, restore with dry-run preview
-- [x] **M46**: Unified Search (Cmd+K) — Global search across brain, memory, history, agents, tasks, apps (later superseded by the Command Palette)
-- [x] **M48**: Google Calendar Integration — MCP push sync + direct Google OAuth2, subcalendar management, goal-calendar linking, daily review, Life Calendar consolidated under Calendar > Lifetime
-- [x] **M49**: Life Goals — Enhanced goal model with todos, velocity tracking, projected completion, AI phase planning, calendar time-blocking, automated weekly check-ins
-- [x] **M50**: Email Management — Outlook API+Playwright sync, AI triage with security hardening, draft generation, thread capture, Gmail API sync+send
-- [x] **M51**: Memory PostgreSQL Upgrade — pgvector HNSW vector search, tsvector full-text search, federation sync, `pg_dump` backup integration
-- [x] **M52**: Update Detection — GitHub release polling, Socket.IO notifications, Update-tab UI with progress + health polling
-- [x] **M53**: POST (Power On Self Test) — Daily cognitive self-test with mental-math, wit, and memory drills
-- [x] **M54**: MeatSpace Life Calendar — "4000 Weeks" mortality-aware time mapping with goal-activity linking
-- [x] **M55**: POST Enhancement — Memory builder, imagination drills, training mode, balanced sessions, wordplay games. See [POST](./docs/features/post.md)
-- [x] **M56**: Telegram Bot Integration — External notification channel with conversational commands and goal check-in persistence
-
-### Other major capabilities (un-numbered)
-
-- [x] **GSD Tab** — Smart state detection, one-click agent spawn, actionable dashboard
-- [x] **Database Management** — Native PostgreSQL mode reusing system pg on :5432, Docker/native switching UI, resource stats, per-backend backup buttons
-- [x] **Review Hub** — Aggregated review page with alerts, CoS actions, todos, daily briefings
-- [x] **JIRA Sprint Manager** — Autonomous JIRA triage and implementation as opt-in per-app scheduled task. See [JIRA Sprint Manager](./docs/features/jira-sprint-manager.md)
-- [x] **App Icons + Non-PM2 Support** — Icon detection for iOS/macOS/Swift projects, non-PM2 app type management
-
----
-
-## Code Audits
-
-- **2025-02-19 Security Audit** — All 10 items resolved. See [Security Audit](./docs/SECURITY_AUDIT.md).
-- **2026-03-05 Audit (Passes 1–3, PRs #67–72)** — App-status duplication, TOCTOU races, fetch-timeout gaps, Socket.IO reconnection bounds, memory-load races, duplicate constants, hook overuse.
-- **2026-04 Better-Audit remediation** — See the 2026-04 section above.
-- **Known low-severity:** pm2 ReDoS (GHSA-x5gf-qvw8-r2rm) — no upstream fix, not exploitable via PortOS routes.
-
----
-
-## Documentation
-
-### Architecture & Guides
-- [Architecture Overview](./docs/ARCHITECTURE.md) — System design, data flow
-- [API Reference](./docs/API.md) — REST endpoints, WebSocket events
-- [Contributing Guide](./docs/CONTRIBUTING.md) — Code guidelines, git workflow
-- [GitHub Actions](./docs/GITHUB_ACTIONS.md) — CI/CD workflow patterns
-- [PM2 Configuration](./docs/PM2.md) — PM2 patterns and best practices
-- [Port Allocation](./docs/PORTS.md) — Port conventions and allocation
-- [Security Audit](./docs/SECURITY_AUDIT.md) — 2025-02-19 hardening audit (all resolved)
-- [Troubleshooting](./docs/TROUBLESHOOTING.md) — Common issues and solutions
-- [Versioning & Releases](./docs/VERSIONING.md) — Version format, release process
-
-### Feature Documentation
-- [Agent Skills](./docs/features/agent-skills.md)
-- [App Wizard](./docs/features/app-wizard.md)
-- [Autofixer](./docs/features/autofixer.md)
-- [Brain System](./docs/features/brain-system.md)
-- [Browser Management](./docs/features/browser.md)
-- [Chief of Staff](./docs/features/chief-of-staff.md)
-- [CoS Agent Runner](./docs/features/cos-agent-runner.md)
-- [CoS Enhancement](./docs/features/cos-enhancement.md)
-- [Digital Twin](./docs/features/digital-twin.md)
-- [Error Handling](./docs/features/error-handling.md)
-- [Identity System](./docs/features/identity-system.md)
-- [JIRA Sprint Manager](./docs/features/jira-sprint-manager.md)
-- [Memory System](./docs/features/memory-system.md)
-- [Messages Security](./docs/features/messages-security.md)
-- [POST](./docs/features/post.md)
-- [Prompt Manager](./docs/features/prompt-manager.md)
-- [Soul System](./docs/features/soul-system.md)
diff --git a/PLAN.md b/PLAN.md
index 366046e2f8..76982255de 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -1,6 +1,6 @@
# PortOS — Development Plan
-For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md](./DONE.md).
+For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelog/](./.changelog/) and `git log`.
---
diff --git a/client/src/components/apps/SlashDoPanel.jsx b/client/src/components/apps/SlashDoPanel.jsx
index d1ca07756c..6b3677aa2a 100644
--- a/client/src/components/apps/SlashDoPanel.jsx
+++ b/client/src/components/apps/SlashDoPanel.jsx
@@ -8,7 +8,7 @@ import * as api from '../../services/api';
const SLASHDO_COMMANDS = [
{ id: 'push', label: '/do:push', description: 'Commit and push all work', classes: 'bg-port-success/20 text-port-success hover:bg-port-success/30 border-port-success/30' },
{ id: 'review', label: '/do:review', description: 'Deep code review', classes: 'bg-port-accent/20 text-port-accent hover:bg-port-accent/30 border-port-accent/30' },
- { id: 'replan', label: '/do:replan', description: 'Audit and prune PLAN.md, archive done items to DONE.md', classes: 'bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 border-cyan-500/30' },
+ { id: 'replan', label: '/do:replan', description: 'Audit and prune PLAN.md, removing completed items', classes: 'bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 border-cyan-500/30' },
{ id: 'release', label: '/do:release', description: 'Create a release PR', classes: 'bg-purple-500/20 text-purple-400 hover:bg-purple-500/30 border-purple-500/30' },
{ id: 'better', label: '/do:better', description: 'DevSecOps audit', classes: 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30 border-port-warning/30', hideForSwift: true },
{ id: 'better-swift', label: '/do:better-swift', description: 'SwiftUI DevSecOps audit', classes: 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30 border-port-warning/30', swiftOnly: true }
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index b3313f6fb1..c65fea9629 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -51,8 +51,9 @@ function extractTaskType(description) {
if (d.includes('dependency')) return 'task:dependency-updates';
if (d.includes('jira') && d.includes('report')) return 'task:jira-status-report';
if (d.includes('jira') || d.includes('sprint')) return 'task:jira-sprint-manager';
- // plan-task matches before do-replan because its description ("Execute next
- // PLAN.md item and archive it to DONE.md") also contains "plan.md".
+ // plan-task matches before do-replan because both descriptions contain
+ // "plan.md" — plan-task's "Execute next PLAN.md item" must win over
+ // replan's "Audit plan.md" generic match.
if (d.includes('plan-task') || (d.includes('execute next') && d.includes('plan.md'))) return 'task:plan-task';
if (d.includes('replan') || d.includes('audit plan.md') || d.includes('plan.md')) return 'task:do-replan';
}
diff --git a/lib/slashdo b/lib/slashdo
index 90fbd08bac..e3dabea334 160000
--- a/lib/slashdo
+++ b/lib/slashdo
@@ -1 +1 @@
-Subproject commit 90fbd08bac3ef3a3511dc4323a00a1e591848f7d
+Subproject commit e3dabea334fd797cdeeee0254c29d4d823adc728
diff --git a/server/lib/planIds.js b/server/lib/planIds.js
index de04586a50..2c1bb5c6ac 100644
--- a/server/lib/planIds.js
+++ b/server/lib/planIds.js
@@ -7,7 +7,7 @@
* - slugify(title, takenIds) → string (deterministic, unique within `takenIds`)
* - parsePlanItems(markdown) → PlanItem[]
* - assignMissingIds(markdown, extraIds)→ { content, assigned[] }
- * - extractAllIds(markdown) → string[] (PLAN.md or DONE.md, every `[slug]`)
+ * - extractAllIds(markdown) → string[] (every `[slug]` in PLAN.md)
* - findInProgressIds(repoPath, ids) → Set<string> (subset present in branch/PR names)
* - pickFirstAvailable(items, takenIds) → PlanItem | null
*
@@ -113,9 +113,10 @@ export function parsePlanItems(markdown) {
}
/**
- * Return every `[slug]` ID that appears in a PLAN.md / DONE.md document.
- * Captures both checkbox-prefixed IDs (parsePlanItems) AND DONE.md archive
- * entries where IDs are embedded inline like `- **[slug] Title**`.
+ * Return every `[slug]` ID that appears in a PLAN.md-style document.
+ * Captures both checkbox-prefixed IDs (parsePlanItems) AND any `[slug]`
+ * marker embedded inline in narrative copy (e.g. cross-references in
+ * design-log entries left as `- [x] [slug] …` for posterity).
*/
export function extractAllIds(markdown) {
if (!markdown) return [];
@@ -123,10 +124,11 @@ export function extractAllIds(markdown) {
for (const item of parsePlanItems(markdown)) {
if (item.id) ids.add(item.id);
}
- // Pick up DONE.md-style `[slug]` markers not on checkbox lines.
- // Length range 2–81 chars is intentionally wider than slugify()'s 50-char cap
- // so legacy DONE.md entries with longer slugs are still recognized for the
- // uniqueness check (we never want to re-issue a retired slug).
+ // Pick up inline `[slug]` markers not on checkbox lines (e.g. design-log
+ // back-references in `## Shipped` sections or PR descriptions inlined here).
+ // Length range 2–81 chars is intentionally wider than slugify()'s 50-char
+ // cap so historical slugs that exceeded the modern length limit are still
+ // recognized for the uniqueness check (we never want to re-issue one).
const inlineRe = /\[([a-z0-9][a-z0-9-]{1,80})\]/g;
let m;
while ((m = inlineRe.exec(markdown)) !== null) {
@@ -141,7 +143,8 @@ export function extractAllIds(markdown) {
/**
* Assign a slug ID to every `- [ ]` / `- [x]` line that doesn't already have one.
* Idempotent: existing IDs are preserved verbatim. `extraIds` lets the caller
- * pass IDs from a sibling document (e.g. DONE.md) into the uniqueness check.
+ * pass IDs from sibling sources (e.g. an in-flight branch scan) into the
+ * uniqueness check.
*
* @param {string} markdown
* @param {string[]|Set<string>} extraIds
diff --git a/server/lib/planIds.test.js b/server/lib/planIds.test.js
index 9f9fdee5f0..c248c1928c 100644
--- a/server/lib/planIds.test.js
+++ b/server/lib/planIds.test.js
@@ -112,7 +112,7 @@ describe('planIds.js', () => {
expect(twice.assigned).toHaveLength(0);
});
- it('respects extraIds (e.g. DONE.md) so retired slugs are not reused', () => {
+ it('respects extraIds (e.g. retired/in-flight slugs) so they are not reused', () => {
const planMd = '- [ ] **Foo.**';
const { content } = assignMissingIds(planMd, ['foo']);
expect(content).toContain('[foo-2]');
diff --git a/server/routes/apps.js b/server/routes/apps.js
index d9df6fb30e..aceadb9769 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -1026,7 +1026,7 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {
// Document Endpoints
// ============================================================
-const ALLOWED_DOCUMENTS = ['PLAN.md', 'DONE.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];
+const ALLOWED_DOCUMENTS = ['PLAN.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];
const documentUpdateSchema = z.object({
content: z.string().max(500000),
diff --git a/server/services/cos.js b/server/services/cos.js
index 9cd93007cf..27d512a3fb 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -101,23 +101,20 @@ import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable }
const PLAN_PICK_TASK_TYPES = new Set(['feature-ideas', 'plan-task']);
/**
- * For feature-ideas / plan-task, read the target repo's PLAN.md (+ DONE.md
- * for the uniqueness set), find which item IDs are already in flight via
- * branch/PR scan, and pick the first available item. Mutates `metadata` in
- * place by setting `planId` when a pick succeeds. Falls back silently when
- * PLAN.md is missing or every item is unavailable — the prompt's own
- * brainstorm/exit-clean fallback handles those cases.
+ * For feature-ideas / plan-task, read the target repo's PLAN.md, find which
+ * item IDs are already in flight via branch/PR scan, and pick the first
+ * available item. Mutates `metadata` in place by setting `planId` when a
+ * pick succeeds. Falls back silently when PLAN.md is missing or every item
+ * is unavailable — the prompt's own brainstorm/exit-clean fallback handles
+ * those cases.
*/
async function applyPlanIdMetadata(taskType, repoPath, metadata) {
if (!PLAN_PICK_TASK_TYPES.has(taskType)) return;
if (!repoPath) return;
- const [planMd, doneMd] = await Promise.all([
- readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => ''),
- readFile(join(repoPath, 'DONE.md'), 'utf-8').catch(() => '')
- ]);
+ const planMd = await readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => '');
if (!planMd) return;
const items = parsePlanItems(planMd);
- const knownIds = new Set([...extractAllIds(planMd), ...extractAllIds(doneMd)]);
+ const knownIds = new Set(extractAllIds(planMd));
const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());
const pick = pickFirstAvailable(items, inFlight);
if (pick?.id) metadata.planId = pick.id;
@@ -1150,11 +1147,11 @@ function getTaskDescription(taskType, appName) {
'ui-bugs': `Review UI for visual bugs in ${appName}`,
'mobile-responsive': `Check mobile responsiveness of ${appName}`,
'feature-ideas': `Implement a feature idea for ${appName} aligned with GOALS.md and PLAN.md (worktree+PR)`,
- 'plan-task': `Execute next PLAN.md item for ${appName} and archive it to DONE.md (worktree+PR)`,
+ 'plan-task': `Execute next PLAN.md item for ${appName}, remove it from PLAN.md, log to changelog (worktree+PR)`,
'release-check': `Verify release readiness for ${appName}`,
'jira-sprint-manager': `Triage and implement JIRA sprint tickets for ${appName} (worktree+PR)`,
'jira-status-report': `Generate JIRA weekly status report for ${appName}`,
- 'do-replan': `Replan: audit PLAN.md for ${appName}, archive done items, prune stale work (worktree+PR)`
+ 'do-replan': `Replan: audit PLAN.md for ${appName}, prune completed and stale work (worktree+PR)`
};
return descriptions[taskType] ?? null;
}
@@ -1168,7 +1165,7 @@ function getTaskDescription(taskType, appName) {
'test-coverage': 'Add missing tests for uncovered code paths',
'documentation': 'Update documentation, comments, and README files',
'feature-ideas': 'Implement a feature idea aligned with GOALS.md and PLAN.md (worktree+PR)',
- 'plan-task': 'Execute next PLAN.md item and archive it to DONE.md (worktree+PR)',
+ 'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
'accessibility': 'Audit and fix accessibility issues (ARIA, keyboard nav, contrast)',
'dependency-updates': 'Check for and safely update outdated dependencies',
'error-handling': 'Improve error handling patterns and recovery logic',
@@ -1176,7 +1173,7 @@ function getTaskDescription(taskType, appName) {
'release-check': 'Verify release readiness (changelog, version, tests)',
'jira-sprint-manager': 'Triage and implement JIRA sprint tickets (worktree+PR)',
'jira-status-report': 'Generate JIRA weekly status report',
- 'do-replan': 'Replan: audit PLAN.md, archive done items, prune stale work (worktree+PR)'
+ 'do-replan': 'Replan: audit PLAN.md, prune completed and stale work (worktree+PR)'
};
return descriptions[taskType] ?? null;
}
@@ -1603,9 +1600,9 @@ Use model: claude-opus-4-5-20251101 for comprehensive test design`,
Review and improve PortOS documentation:
-1. Update PLAN.md and DONE.md:
- - Move completed milestones from PLAN.md to DONE.md
- - Add any new features implemented to DONE.md
+1. Update PLAN.md:
+ - Remove completed milestones from PLAN.md outright (do NOT archive to a DONE.md — that file is retired; \`git log\` and \`.changelog/\` are the audit trail)
+ - Add any new features implemented as entries in \`.changelog/NEXT.md\` (mirror the prose style of recent entries)
- Keep PLAN.md focused on next actions and future work
2. Check docs/ folder:
@@ -1640,7 +1637,7 @@ Your goal is to implement ONE feature.
1. Read GOALS.md for context on user goals and priorities
2. Read PLAN.md for the current roadmap and planned work (next actions, audit findings, future ideas)
-3. Read DONE.md to understand what has already been implemented (avoid re-implementing existing features)
+3. Skim recent \`.changelog/\` entries and \`git log\` to understand what has already shipped (avoid re-implementing existing features)
4. Search for existing feature idea documents:
- Check .planning/research/FEATURES.md for planned features
- Check .planning/ directory for any feature specs or research docs
@@ -1652,7 +1649,7 @@ Your goal is to implement ONE feature.
7. Choose ONE feature to implement that:
- Aligns with GOALS.md priorities
- - Is NOT already completed in DONE.md (avoid re-implementing shipped features)
+ - Is NOT already shipped per recent \`.changelog/\` entries or \`git log\` (avoid re-implementing shipped features)
- Is NOT already planned in PLAN.md (avoid duplicating roadmap work)
- Is NOT already documented in existing feature idea files
- Is a small, self-contained improvement (completable in one session)
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 96a9eac216..e520e70db5 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -292,8 +292,9 @@ Repository: {repoPath}
- Is information current?
- Add missing guides if needed
-4. Update PLAN.md and DONE.md if present:
- - Move completed milestones from PLAN.md to DONE.md
+4. Update PLAN.md if present:
+ - Remove completed milestones from PLAN.md outright. Do NOT archive to a \`DONE.md\` — that file is retired; \`git log\` and \`.changelog/\` (or per-app equivalent) are the audit trail.
+ - If the repo has a \`.changelog/NEXT.md\` (or similar), log what shipped there in the project's existing prose style.
- Keep PLAN.md focused on next actions and future work
Commit documentation improvements.`,
@@ -335,7 +336,7 @@ Repository: {repoPath}
## Phase 1 — Find the Next Task
1. Read PLAN.md from {repoPath}
-2. Read DONE.md from {repoPath} (if it exists) to understand what has already been implemented
+2. Skim recent \`.changelog/\` entries and \`git log\` (last 50 commits) to understand what has already shipped — do NOT re-implement completed features
3. If the **Item Constraint** block above named a specific \`[plan-id]\`, find the matching \`- [ ]\` line and use that — do NOT pick a different one, do NOT brainstorm. If the line is missing, has been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.
4. Otherwise, if PLAN.md does not exist, is empty, or has no unchecked items (\`- [ ]\`), go to **Phase 4 — Brainstorm**.
5. Otherwise, find the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.
@@ -378,11 +379,11 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n
1. Read GOALS.md from {repoPath} for context on the app's goals and priorities.
If no GOALS.md exists, focus on general improvements.
-2. Read DONE.md from {repoPath} (if it exists) to avoid re-implementing completed features
+2. Skim recent \`.changelog/\` entries and the last 50 \`git log\` entries to avoid re-implementing completed features
3. Review the codebase structure, recent git log, and any README or docs to understand the app
4. Identify ONE small, high-impact feature that:
- Aligns with GOALS.md priorities (if available)
- - Is NOT already in DONE.md (avoid re-implementing shipped features)
+ - Is NOT already shipped per recent \`.changelog/\` entries or \`git log\` (avoid re-implementing shipped features)
- Saves user time, improves UX, or makes the app more useful
- Is self-contained and completable in one session
- Does NOT duplicate existing functionality
@@ -390,7 +391,7 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n
- Write clean, tested code following existing patterns
- Run tests to ensure nothing is broken
6. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.
-7. Add the feature as a checked item in PLAN.md (create the file if needed) **with a slug ID** derived from the feature title (lowercase kebab-case, ≤50 chars, unique against every existing \`[slug]\` in PLAN.md and DONE.md):
+7. Add the feature as a checked item in PLAN.md (create the file if needed) **with a slug ID** derived from the feature title (lowercase kebab-case, ≤50 chars, unique against every existing \`[slug]\` in PLAN.md):
\`\`\`
- [x] [<slug-of-feature>] <description of the feature you implemented>
\`\`\`
@@ -405,7 +406,7 @@ Pick the next unclaimed PLAN.md item by its \`[<slug>]\` ID, **create your own w
## Phase 1 — Pick
-1. Read PLAN.md and DONE.md from the repo root.
+1. Read PLAN.md from the repo root.
2. **If any \`- [ ]\` line lacks an \`[<slug>]\` ID, stop and exit cleanly** — \`do-replan\` populates IDs in one pass; without IDs, this task has nothing to claim.
3. Build the in-flight set. Collect every ref from these sources:
\`\`\`bash
@@ -426,7 +427,7 @@ Pick the next unclaimed PLAN.md item by its \`[<slug>]\` ID, **create your own w
- The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.
5. **If no eligible item exists**, exit cleanly — that's a healthy plan state, not a failure. Brainstorming is handled by the \`feature-ideas\` task; do NOT add new items here.
-Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — DONE.md will reuse both.
+Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — the changelog entry will reuse both.
## Phase 2 — Claim (worktree)
@@ -486,7 +487,7 @@ Write the code, tests, and any docs the item requires. Follow the repo conventio
Run the relevant test suite as you go.
-**Commit messages reference the slug** so the work is grep-able across DONE.md, branches, and PR titles:
+**Commit messages reference the slug** so the work is grep-able across the changelog, branches, and PR titles:
\`\`\`
<type>([<slug>]): <one-line description>
@@ -496,24 +497,31 @@ Run the relevant test suite as you go.
Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scope form \`([<slug>])\` is intentional and matches the project's existing convention — grep \`git log --oneline\` for prior examples. The brackets carry the PLAN.md \`[<slug>]\` ID syntax through to commits, branches, and PRs so a single slug grep finds the whole trail.)
-## Phase 5 — Update PLAN.md and DONE.md
+## Phase 5 — Update PLAN.md and the changelog
-**Move the item out of PLAN.md and into DONE.md.** Do NOT leave a checked \`- [x]\` behind in PLAN.md.
+**Remove the item from PLAN.md outright.** The audit trail for shipped work lives in \`git log\` and the project's changelog (e.g. \`.changelog/NEXT.md\`) — do NOT archive to a \`DONE.md\`, that file has been retired. Do NOT leave a checked \`- [x]\` behind in PLAN.md.
1. Remove the picked \`- [ ]\` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is \`do-replan\`'s job.
-2. Append to DONE.md under today's date heading (\`## YYYY-MM-DD\`). Insert today's heading directly below the top-of-file preamble if it doesn't exist yet.
-3. Entry format — **slug lifted verbatim from PLAN.md, never re-derived**:
+2. Detect the repo's changelog convention (in this order — pick the first match):
+ - \`.changelog/NEXT.md\` (PortOS-style staged-release file)
+ - \`CHANGELOG.md\` at repo root with an \`## Unreleased\` or \`## [Unreleased]\` heading
+ - any other \`changelog\`-shaped file the repo already maintains (look at recent \`git log\` for examples of where prior entries landed)
+
+ If exactly one is found, append an entry there. Mirror the prose style of recent entries; lead with the slug in brackets so \`git log --grep='<slug>'\` and changelog greps line up:
\`\`\`markdown
- **[<slug>] <Title from the PLAN.md line>** — <1–3 sentences on what shipped, key files touched, any caveats>
\`\`\`
-Stage both files and commit:
+ Remember the exact path you wrote to as \`CHANGELOG_FILE\` — you'll stage it in step 3. If no changelog convention exists, skip the changelog append and leave \`CHANGELOG_FILE\` unset; the commit message + \`git log\` becomes the audit trail.
-\`\`\`bash
-git add PLAN.md DONE.md
-git commit -m "docs([<slug>]): archive to DONE.md"
-\`\`\`
+3. Stage PLAN.md plus the changelog file you actually edited (if any) and commit. **Do NOT use a glob or a swallow-on-failure fallback** — staging the exact file you edited is what keeps the audit trail honest:
+
+ \`\`\`bash
+ git add PLAN.md
+ [ -n "$CHANGELOG_FILE" ] && git add "$CHANGELOG_FILE"
+ git commit -m "docs([<slug>]): remove from PLAN.md and log to changelog"
+ \`\`\`
## Phase 6 — Review and ship
@@ -559,14 +567,14 @@ Repository: {repoPath}
1. Read GOALS.md (if exists) for project goals and priorities
2. Read PLAN.md (if exists) to understand already-planned work — do NOT re-suggest items already planned
-3. Read DONE.md (if exists) to understand completed work — do NOT re-suggest items already done
+3. Skim recent \`.changelog/\` entries (or equivalent) and \`git log\` (last 50 commits) to understand completed work — do NOT re-suggest items already shipped
4. Read REJECTED.md (if exists) to understand previously rejected recommendations — do NOT re-suggest rejected items
5. Read CLAUDE.md for project conventions and architecture
6. Review the codebase structure, key files, recent git log (last 20 commits)
## Phase 2 — Deep Review
-Examine the codebase thoroughly across these dimensions. Skip any recommendations that overlap with PLAN.md, DONE.md, or REJECTED.md items:
+Examine the codebase thoroughly across these dimensions. Skip any recommendations that overlap with PLAN.md, the changelog/git history, or REJECTED.md items:
7. **Code Quality**: DRY violations, dead code, overly complex functions, missing error handling, inconsistent patterns, tech debt
8. **Architecture**: Component organization, separation of concerns, data flow issues, coupling problems, missing abstractions (or unnecessary abstractions)
@@ -612,21 +620,21 @@ Repository: {repoPath}
1. Read REVIEW.md from {repoPath} — this contains the recommendations from Stage 1
2. Read GOALS.md (if exists) for alignment context
3. Read PLAN.md (if exists) for current planned work
-4. Read DONE.md (if exists) for completed work
+4. Skim recent \`.changelog/\` entries and \`git log\` for completed work
5. Read CLAUDE.md for project conventions
## Phase 2 — Triage Each Recommendation
For each recommendation in REVIEW.md, evaluate:
- Does it align with GOALS.md?
-- Is it already in PLAN.md or DONE.md?
+- Is it already in PLAN.md, the changelog, or shipped per git log?
- What is the actual value vs effort?
Categorize into:
- **IMPLEMENT**: High value, achievable in this session (small/medium effort, clear scope)
- **PLAN**: High value but too large for this session — add to PLAN.md
- **REJECT**: Low value, misaligned with goals, or already addressed
-- **DONE**: Already implemented (found in DONE.md or codebase)
+- **DONE**: Already implemented (found in the changelog, git history, or codebase)
## Phase 3 — Implement
@@ -640,7 +648,7 @@ Categorize into:
## Phase 4 — Update Project Files
8. For PLAN items: Add as unchecked items (\`- [ ]\`) to PLAN.md (create if needed)
-9. For DONE items: Add as checked items (\`- [x]\`) to DONE.md (create if needed)
+9. For DONE items: skip — they're already in the changelog/git history; no PLAN.md or archive entry needed
10. For REJECT items: Append to REJECTED.md with brief rationale:
\`- <title> — <reason for rejection>\`
Create REJECTED.md if it doesn't exist
@@ -866,7 +874,7 @@ Repository: {repoPath}
The full \`/do:replan\` command body follows. Apply it to {repoPath} exactly as written, then commit any changes. Default mode is autonomous — do NOT prompt the user; run \`--interactive\` only if the user has explicitly asked for it (they have not).
-Scope: this task operates against the managed app's repository, NOT PortOS. All edits must land in {repoPath} (PLAN.md, DONE.md, GOALS.md, docs/) — never write to PortOS itself.
+Scope: this task operates against the managed app's repository, NOT PortOS. All edits must land in {repoPath} (PLAN.md, GOALS.md, docs/, the changelog) — never write to PortOS itself.
---
@@ -1176,8 +1184,8 @@ For each reference above:
// Prompt versions — bump when a default prompt changes so existing instances auto-upgrade.
// Only non-customized prompts (promptCustomized !== true) are upgraded.
const PROMPT_VERSIONS = {
- 'feature-ideas': 8, // v8: plan-item ID system — {planConstraint} placeholder, preserve [slug] on edits, brainstorm path generates a new slug
- 'plan-task': 5, // v5: /claim-style flow — agent creates its own claim/<slug> worktree, ships via gh pr merge, no local merge-back
+ 'feature-ideas': 9, // v9: drop DONE.md reads — use `.changelog/` + `git log` (last 50) as the completed-work signal
+ 'plan-task': 6, // v6: drop DONE.md reads/writes — agent removes the item from PLAN.md outright and logs to `.changelog/NEXT.md`; audit trail = git log + changelog
'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)
'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
@@ -1503,6 +1511,76 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n
\`\`\`
- [x] <description of the feature you implemented>
\`\`\`
+8. Commit with a clear description of the feature and rationale`,
+ // v8 default prompt (plan-item ID system — superseded by v9, which drops DONE.md reads in favor of `.changelog/` + `git log` lookups)
+ `[Improvement: {appName}] Implement Next Planned Feature
+
+Your goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.
+
+Repository: {repoPath}
+{planConstraint}
+## Phase 1 — Find the Next Task
+
+1. Read PLAN.md from {repoPath}
+2. Read DONE.md from {repoPath} (if it exists) to understand what has already been implemented
+3. If the **Item Constraint** block above named a specific \`[plan-id]\`, find the matching \`- [ ]\` line and use that — do NOT pick a different one, do NOT brainstorm. If the line is missing, has been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.
+4. Otherwise, if PLAN.md does not exist, is empty, or has no unchecked items (\`- [ ]\`), go to **Phase 4 — Brainstorm**.
+5. Otherwise, find the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.
+6. If all unchecked items have \`<!-- NEEDS_INPUT -->\`, go to **Phase 4 — Brainstorm**.
+
+## Phase 2 — Evaluate Feasibility
+
+7. Read relevant source files to understand the scope of the item
+8. Determine: can this be implemented without user clarification?
+ - Consider: are requirements clear? Are there ambiguous design choices? Does it depend on external decisions?
+
+## Phase 3a — Implement (if feasible)
+
+9. Implement the feature:
+ - Write clean, tested code following existing patterns
+ - Run tests to ensure nothing is broken
+10. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.
+11. Check the PLAN.md item: change \`- [ ]\` to \`- [x]\`. **Preserve the \`[plan-id]\` slug verbatim** — only the box character flips, never the ID. Reference the slug in the commit message (e.g. \`feat([plan-id]): …\`).
+12. Commit with a clear description referencing the PLAN.md item
+
+## Phase 3b — Request Clarification (if not feasible)
+
+9. Create a file named \`.plan-questions.md\` in the repository root with this format:
+ \`\`\`
+ # Plan Question: <short title summarizing the PLAN.md item>
+
+ ## PLAN.md Item
+ <the exact text of the unchecked item, including its [plan-id]>
+
+ ## Questions
+ - <question 1>
+ - <question 2>
+ \`\`\`
+10. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove the line from its current position and append it at the end of the file with the annotation, **preserving its \`[plan-id]\` slug**. This keeps the queue moving so the next \`feature-ideas\` run picks up a different actionable item instead of repeatedly tripping on this one.
+11. Commit both changes (the new \`.plan-questions.md\` file and the PLAN.md move) with message \`chore: flag PLAN.md item needing user input\`. Then proceed to the **Completion** section below so the clarification PR is opened for the user to review — do NOT leave the worktree orphaned.
+
+## Phase 4 — Brainstorm a New Feature
+
+When PLAN.md is missing, empty, or fully completed, brainstorm and implement a new feature:
+
+1. Read GOALS.md from {repoPath} for context on the app's goals and priorities.
+ If no GOALS.md exists, focus on general improvements.
+2. Read DONE.md from {repoPath} (if it exists) to avoid re-implementing completed features
+3. Review the codebase structure, recent git log, and any README or docs to understand the app
+4. Identify ONE small, high-impact feature that:
+ - Aligns with GOALS.md priorities (if available)
+ - Is NOT already in DONE.md (avoid re-implementing shipped features)
+ - Saves user time, improves UX, or makes the app more useful
+ - Is self-contained and completable in one session
+ - Does NOT duplicate existing functionality
+5. Implement the feature:
+ - Write clean, tested code following existing patterns
+ - Run tests to ensure nothing is broken
+6. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.
+7. Add the feature as a checked item in PLAN.md (create the file if needed) **with a slug ID** derived from the feature title (lowercase kebab-case, ≤50 chars, unique against every existing \`[slug]\` in PLAN.md and DONE.md):
+ \`\`\`
+ - [x] [<slug-of-feature>] <description of the feature you implemented>
+ \`\`\`
8. Commit with a clear description of the feature and rationale`
],
'plan-task': [
@@ -1584,7 +1662,158 @@ Read relevant source files. Can this be implemented without user clarification (
- <question 1>
- <question 2>
\`\`\`
-2. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove from its current position and append at the end with the annotation, **preserving the \`[plan-id]\` slug**. This keeps the queue moving so the next \`plan-task\` run picks up a different actionable item.`
+2. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove from its current position and append at the end with the annotation, **preserving the \`[plan-id]\` slug**. This keeps the queue moving so the next \`plan-task\` run picks up a different actionable item.`,
+ // v5 default prompt (/claim-style flow — superseded by v6, which drops DONE.md reads/writes in favor of `.changelog/` + `git log` lookups)
+ `[Plan Task: {appName}] Claim and ship next PLAN.md item
+
+Pick the next unclaimed PLAN.md item by its \`[<slug>]\` ID, **create your own worktree at \`claim/<slug>\`**, implement, ship a PR, and clean up. Mirrors the \`/claim\` slash command — same in-flight scan, same branch naming, same no-local-merge cleanup. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.
+{planConstraint}
+
+**How claiming works.** Every PLAN.md checkbox carries a \`[<slug>]\` ID. A slug is "in flight" when it appears as the slug-position segment in either a \`claim/<slug>\` ref (the human/TUI pattern) or a \`cos/<task>/<slug>/<agent>\` ref (the CoS sub-agent pattern) — across local branches, remote branches, or open PR head refs. Pick the first \`- [ ]\` whose slug is NOT in flight and create a \`claim/<slug>\` branch — that branch name IS the claim, visible to every other agent and to the human running \`/claim\` in a TUI.
+
+## Phase 1 — Pick
+
+1. Read PLAN.md and DONE.md from the repo root.
+2. **If any \`- [ ]\` line lacks an \`[<slug>]\` ID, stop and exit cleanly** — \`do-replan\` populates IDs in one pass; without IDs, this task has nothing to claim.
+3. Build the in-flight set. Collect every ref from these sources:
+ \`\`\`bash
+ git fetch --prune 2>/dev/null
+ git branch -a --no-color --format='%(refname:short)'
+ gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null
+ \`\`\`
+ For each ref, extract the slug **only when the ref matches one of these documented patterns** (after stripping any leading remote prefix like \`origin/\` or \`upstream/\`):
+ - \`claim/<slug>\` — the slug is everything after \`claim/\`.
+ - \`cos/<task>/<slug>/<agent>\` — the slug is the third \`/\`-separated segment.
+
+ A slug is "in flight" iff it appears in a ref matching one of those patterns AND is present in PLAN.md. **Do NOT** flag a slug just because the bare word appears as some other segment of a ref — that would falsely flag any slug literally named \`main\`, \`fix\`, \`feature\`, \`release\`, \`dev\`, etc. against virtually every branch in the repo.
+4. **Pick the target slug:**
+ - **If the Item Constraint above named a specific \`[plan-id]\`**: use that. If the line is missing, has been checked, carries \`<!-- NEEDS_INPUT -->\`, or its slug IS in the in-flight set, exit cleanly without commits or PR.
+ - **Otherwise**: walk PLAN.md top-to-bottom and pick the FIRST \`- [ ]\` line where ALL of the following are true:
+ - The slug is NOT in the in-flight set.
+ - The immediately-preceding line does NOT start with \`> ⚠️ DRIFT:\`.
+ - The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.
+5. **If no eligible item exists**, exit cleanly — that's a healthy plan state, not a failure. Brainstorming is handled by the \`feature-ideas\` task; do NOT add new items here.
+
+Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — DONE.md will reuse both.
+
+## Phase 2 — Claim (worktree)
+
+Create the worktree on a branch named \`claim/<slug>\`. This branch name is the claim — once created and pushed, no other agent or \`/claim\` session will pick the same slug. Do all editing inside the worktree, NEVER in the source repo's working tree (which may have the user's in-flight work).
+
+\`\`\`bash
+SLUG=<picked-slug>
+WORKTREE="data/cos/worktrees/claim-\${SLUG}"
+mkdir -p data/cos/worktrees
+git fetch origin main
+git worktree add -b "claim/\${SLUG}" "\${WORKTREE}" origin/main
+cd "\${WORKTREE}"
+\`\`\`
+
+Stash the worktree path; you'll need it for Phase 7 cleanup.
+
+## Phase 3 — Verify still valid
+
+Before writing any code, sanity-check that executing the item won't regress newer work. **If ANY of these are true, jump to Phase 3b** (clarification path, not implementation):
+
+- The picked line is preceded by a \`> ⚠️ DRIFT:\` blockquote (you should already have filtered it; double-check).
+- The item description references a function, file, or component that no longer exists. Run \`grep -rn\` for the named identifiers — if they're gone, the item is stale.
+- The item depends on a predecessor that hasn't shipped (e.g. "Phase B work" when Phase B isn't done).
+- The work would require touching files outside the inferred scope (>5 unrelated files), suggesting the item is bigger than originally estimated.
+
+Otherwise: can this be implemented without user clarification (requirements clear, no ambiguous design choices)? If NOT, jump to Phase 3b. If yes, proceed to Phase 4.
+
+## Phase 3b — Request Clarification (alternative exit from Phase 3)
+
+Done from INSIDE the worktree (you've already created \`claim/<slug>\` in Phase 2):
+
+1. Create \`.plan-questions.md\` in the worktree:
+ \`\`\`
+ # Plan Question: <short title summarizing the PLAN.md item>
+
+ ## PLAN.md Item
+ <the exact text of the unchecked item, including its [<slug>]>
+
+ ## Questions
+ - <question 1>
+ - <question 2>
+ \`\`\`
+2. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove from its current position and append at the end with the annotation, **preserving the \`[<slug>]\` ID**. This keeps the queue moving so the next \`plan-task\` run picks a different actionable item.
+3. Commit, push the branch (\`git push -u origin claim/<slug>\`), and open a PR with \`gh pr create\` so the user can see the questions. **Do NOT merge** — the user resolves \`.plan-questions.md\` first.
+4. Then run the **Phase 3b cleanup** (which differs from Phase 7 — the PR is intentionally unmerged here, so the local branch must NOT be deleted):
+ \`\`\`bash
+ cd {repoPath}
+ git worktree remove "\${WORKTREE}"
+ \`\`\`
+ Leave the local \`claim/<slug>\` branch alone — \`git branch -d\` will refuse (PR not merged) and \`-D\` would discard work that's still in flight. The branch lives on locally and remotely until the user resolves the questions and the PR merges; \`git branch -d "claim/<slug>"\` becomes safe only after that point.
+
+After Phase 3b runs, **exit** — do NOT proceed to Phase 4. The implementing path resumes only when the user reopens the slug post-clarification.
+
+## Phase 4 — Implement
+
+Write the code, tests, and any docs the item requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates).
+
+Run the relevant test suite as you go.
+
+**Commit messages reference the slug** so the work is grep-able across DONE.md, branches, and PR titles:
+
+\`\`\`
+<type>([<slug>]): <one-line description>
+
+<optional body>
+\`\`\`
+
+Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scope form \`([<slug>])\` is intentional and matches the project's existing convention — grep \`git log --oneline\` for prior examples. The brackets carry the PLAN.md \`[<slug>]\` ID syntax through to commits, branches, and PRs so a single slug grep finds the whole trail.)
+
+## Phase 5 — Update PLAN.md and DONE.md
+
+**Move the item out of PLAN.md and into DONE.md.** Do NOT leave a checked \`- [x]\` behind in PLAN.md.
+
+1. Remove the picked \`- [ ]\` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is \`do-replan\`'s job.
+2. Append to DONE.md under today's date heading (\`## YYYY-MM-DD\`). Insert today's heading directly below the top-of-file preamble if it doesn't exist yet.
+3. Entry format — **slug lifted verbatim from PLAN.md, never re-derived**:
+
+ \`\`\`markdown
+ - **[<slug>] <Title from the PLAN.md line>** — <1–3 sentences on what shipped, key files touched, any caveats>
+ \`\`\`
+
+Stage both files and commit:
+
+\`\`\`bash
+git add PLAN.md DONE.md
+git commit -m "docs([<slug>]): archive to DONE.md"
+\`\`\`
+
+## Phase 6 — Review and ship
+
+1. Run \`/simplify\` (three-agent reuse/quality/efficiency review) against your own diff and fix findings in the same diff. BEFORE opening the PR, not retroactively.
+2. Push the branch: \`git push -u origin claim/<slug>\`
+3. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.
+4. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\` into main or any other branch. The repo may allow only one of \`--merge\` / \`--squash\` / \`--rebase\`, so don't hardcode a method. Try in this order and use the first one that succeeds:
+ \`\`\`bash
+ gh pr merge <num> --auto --delete-branch \\
+ || gh pr merge <num> --squash --delete-branch \\
+ || gh pr merge <num> --merge --delete-branch \\
+ || gh pr merge <num> --rebase --delete-branch
+ \`\`\`
+ \`--auto\` lets GitHub apply the repo's configured default once required checks pass; the explicit-method fallbacks cover repos that disallow auto-merge or restrict to a single method. \`--delete-branch\` removes the remote branch atomically on merge.
+
+## Phase 7 — Clean up (post-merge ONLY)
+
+This phase runs only after the PR was merged via Phase 6. If you exited via Phase 3b instead, you already did the 3b-specific cleanup — do NOT also run Phase 7.
+
+From the **source repo** (cd back to {repoPath} first; you are currently inside the worktree):
+
+\`\`\`bash
+cd {repoPath}
+git worktree remove "\${WORKTREE}"
+git branch -d "claim/\${SLUG}"
+\`\`\`
+
+If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged via Phase 6, so the local branch is genuinely redundant.
+
+**Do NOT \`git pull\` from inside this phase** (no \`--rebase\`, no \`--autostash\`, no plain \`pull\`). The agent's work is already integrated on GitHub via \`gh pr merge\`; pulling locally provides no functional benefit and risks rebasing the user's in-progress branch / shuffling their uncommitted changes through stash if the source repo HEAD happens to be on a tracking feature branch when the agent runs. Leave the user's working tree alone.
+
+_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`
],
'pr-reviewer': [
// v1 default prompt (required global slash-do install)
@@ -1731,8 +1960,8 @@ const DEFAULT_TASK_INTERVALS = {
// that already accounts for any in-flight or unmerged work.
'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
// plan-task is a strict executor of PLAN.md items — no brainstorm fallback, no
- // runAfter deps. Picks the next unchecked item, implements it, and moves it
- // from PLAN.md to DONE.md in the same commit.
+ // runAfter deps. Picks the next unchecked item, implements it, and removes it
+ // from PLAN.md in the same commit (changelog + git log are the audit trail).
// plan-task (prompt v5+) drives the /claim flow itself — the agent creates its OWN `claim/<slug>` worktree, opens the PR, merges via `gh pr merge`, and cleans up.
// Both `useWorktree` and `openPR` are OFF on the CoS side:
// * `useWorktree: false` — CoS pre-creating a worktree under `cos/<task>/<agent>` would hide the slug from the in-flight branch scan AND trigger
@@ -2752,7 +2981,7 @@ function getTaskTypeDescription(taskType) {
'test-coverage': 'Improve test coverage',
'documentation': 'Update documentation',
'feature-ideas': 'Implement next planned feature or brainstorm new one',
- 'plan-task': 'Execute next PLAN.md item and archive it to DONE.md (worktree+PR)',
+ 'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
'accessibility': 'Accessibility audit',
'branch-cleanup': 'Clean up merged branches',
'dependency-updates': 'Update dependencies',