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

tighten release-note style: claim.md guidance + NEXT.md rewrite

[._.]/ Adam Eivyd6313834adec
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bc6fcd46c7..1920036102 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,135 +1,73 @@
# Unreleased Changes
-## Changed
-
-- **[med-canon-server-services-canonusage-js-zero-test] `getUniverseCanonUsage` heavy-endpoint contract now pinned.** `server/services/canonUsage.test.js` previously only covered `seriesNameMap`/`seriesCount` and the thin `listLinkedSeriesNames` variant. The per-entry usage rows the comic-panel / canon-card UI consumes — produced by the multi-stage corpus scan + per-(kind, entryId, seriesId) tally + sort at `canonUsage.js:99-132` — had no tests, so the JSDoc-pinned "Appears-in sort: issueCount desc + alpha tiebreaker on seriesName" invariant could regress silently. New `getUniverseCanonUsage entry rows` describe block adds six tests: 404 on missing universe (separate from `listLinkedSeriesNames`' 404 because that variant only translates `ERR_NOT_FOUND` while `getUniverseCanonUsage` re-throws any `getUniverse` error as 404), sort by `issueCount` desc with alpha tiebreaker (seeded as Zeta Tales (1) / Alpha Tales (1) / Beta Tales (2); expected output Beta → Alpha → Zeta — the equal-count pair Alpha/Zeta exercises the alpha-ascending tiebreaker, the Beta/(Alpha|Zeta) pair exercises issueCount-desc), bucket wiring for the three kinds (matches for `characters` / `places` / `objects` each land under their canonically-named `usage[kind]` key — does not pin matcher *behavior*, which lives in `scenePrompt.test.js`), the empty/whitespace-corpus contract (issues still count toward `issueCount` but produce no entry rows), the multi-stage corpus aggregation (idea / comicScript / teleplay), and the empty-bucket return for kinds the universe defines no entries for (also exercises the `Array.isArray(universe[kind])` guard). 11/11 tests in the file pass; 6169/6169 server tests pass. `[cover-prose-input-idea-input-in-canonusage-corpus]` captured as a follow-up — across the new block + sibling tests, 4 of the 6 fields `corpusForIssue` aggregates are covered (`prose.output` via sibling tests; `idea.output` / `comicScript.output` / `teleplay.output` via the multi-stage corpus test). `prose.input` and `idea.input` aren't seeded by any test, so a regression that drops either from the corpus list would still slip past the suite.
-
-- **[add-emitrunstarted-hook-shape-test-to-runner] Pin `emitRunStarted` payload-flattening contract in `server/services/runner.test.js`.** The `provider?.name || provider?.id` and `model ?? provider?.defaultModel` fallbacks in `runner.js:198-204` previously had zero direct coverage — `tuiPromptRunner.js`'s PTY tests mock `emitRunStarted` itself, so a regression that dropped the `name` preference or flipped the model fallback from `??` to `||` (silently rewriting an intentionally-empty model to `defaultModel`) would have slipped past every test. New `describe('emitRunStarted — payload-flattening contract')` block in `runner.test.js` exports `emitRunStarted` from the module under test, registers a `runnerConfig.hooks.onRunStarted` mock via `setAIToolkit(fakeToolkit(), { hooks })`, and asserts the hook payload across 8 cases: `name`-preferred-over-`id`, `id` fallback when `name` is absent, explicit `model` overriding `defaultModel`, `defaultModel` fallback when `model` is `undefined`, `defaultModel` fallback when `model` is `null` (`??` semantics), empty-string `model` preserved (guards against a `||` regression), `provider: undefined` → both fields `undefined`, and the no-op path when no hook is registered. 43/43 runner tests pass (35 prior + 8 new).
-
-- **[med-importer-server-services-importer-test-js-no] Pin `existingCanonBlock` dedupe wiring in importer service tests.** `server/services/importer.test.js` had no coverage for the `existingCanonBlock` argument that `analyzeImport` passes into the `importer-canon-extract` LLM call at `importer.js:472-479` — a refactor that dropped the arg or wired it to `null`/`''` would leave the canon-extract LLM blind to already-seeded characters / places / objects, and every second-pass import would silently re-extract duplicates. New `'wires existingCanonBlock into the canon-extract prompt for dedup on a second-pass import'` test in `analyzeImport`'s describe block seeds a universe with one character via `universeSvc.createUniverse` + `updateUniverse`, runs `analyzeImport` against the seeded universe name, looks up the `importer-canon-extract` call by stage name (defensive against future `Promise.all` scheduling changes vs. the brittle `calls[0]` shape from the PLAN ask), and asserts the seeded character name reaches `existingCanonBlock`. The lookup-by-stage-name is the only deviation from the PLAN ask's literal `calls[0][1]` shape — `analyzeImport` fires canon + arc via `Promise.all` and any future deferral / reorder would silently break the test. 46/46 importer tests pass.
-
-- **[audit-remaining-getissue-prechecks-in-pipeline-routes] Audit of remaining `getIssue` prechecks in `pipeline.js`; music attach/delete routes drop the redundant read.** Followed up on the comic-cover consolidation by tracing each of the 10 sites cited in PLAN.md plus `:1427` found during the audit, so 11 sites total in `server/routes/pipeline.js`. Verdict: **8 stay, 2 drop, 1 keep-but-unbind**. **Drop** at `/issues/:id/stages/audio/music/attach` and `DELETE /issues/:id/stages/audio/music` — the only consumer was `audioStatusAfterMusicChange(issue)` (reads `issue.stages.audio.lines.length`), which now derives from `currentStage` inside `updateStageWithLatest`'s `computeFn` instead. Helper signature changed from `(issue) => …` to `(stage) => …`. **Keep-but-unbind** at `/issues/:id/stages/audio/music/upload` — the precheck must gate `importUploadedTrack` (a filesystem write) so a bad id doesn't orphan an imported file when the subsequent write 404s; the binding is dropped because the status computation now uses the freshest stage too. **Keep** at the other 8 sites because each route consumes issue data the called service can't supply: `extract-audio-lines` / `audio/lines/:lineIdx/render` / `storyboards/extract-scenes` / `comicPages/extract-pages` / `:stageId/extract-canon` all need `issue.seriesId` (or stage-locked guard against a sibling stage); `GET /issues/:id` IS the read; `comicPages/pages/:pageIndex/render` keeps the precheck-only-error-shape pageIndex bounds check (the inline comment explicitly justifies it as "avoids loading the bible context just to error out"); and `auto-run-text` keeps the precheck-only-error-shape sync 404 (the runner's IIFE is fire-and-forget, so without the precheck a bad id returns 200 with a runId that immediately errors out via SSE). Net: per-request `data/issues.json` reads on attach/delete music drop from 2 → 1, and the status computation moves from a stale snapshot to the freshest persisted state (eliminates a small TOCTOU window vs. a concurrent line edit). New tests pin the 404 status AND `PIPELINE_ISSUE_NOT_FOUND` error code for both refactored routes (the precheck-removal equivalence depends on the downstream not changing the error shape). 87/87 pipeline route tests pass; 6152/6152 server tests pass.
-
-- **[med-tests-no-direct-tests-for-executetuirun-pty] `executeTuiRun` PTY mechanics now have direct test coverage.** The existing `server/lib/tuiPromptRunner.test.js` only covered the two pure helpers (`cleanTuiResponse`, `resolveTuiResponseText`); the PTY-driven core that orchestrates spawn → ready-watch → paste → completion was entirely unverified. New `describe('executeTuiRun')` block mocks `node-pty` and the runner-service hooks so each completion path can be triggered deterministically from the test: input validation (3 cases), spawn failure wrapping, `registerActiveRun` + `emitRunStarted` shape, provider `envVars` merge + `CLAUDECODE` stripping, and the six completion paths — `idle-complete` (after first response chunk + idle window), `timeout` (exitCode 124), `command-not-found` early-fail probe (exitCode 127), clean `exit` (exitCode 0), `killed` (signal in error message), and non-zero exit with tail-bearing error. `fileUtils` stays real except for `ensureDir` (mocked no-op) so the existing `resolveTuiResponseText` tests keep using real `tryReadFile`. 12 new tests; 29/29 file-level tests pass; 6162/6162 server tests pass. PLAN.md drops the self-deferred `[cover-render-factory-target-binding]` entry alongside — it explicitly read "pick this up when a fifth cover-render variant appears," that trigger hasn't fired, and the entry was confusing `/claim`.
-
-- **[med-importer-server-routes-importer-test-js-no] Pin `ERR_PARTIAL_COMMIT_ISSUES → 422` status mapping in importer route tests.** `server/routes/importer.test.js` previously covered the `ERR_VALIDATION → 400`, `ERR_LOCKED → 409`, and `universeSvc.ERR_NOT_FOUND → 404` entries in `SERVICE_ERROR_STATUS` but not the partial-commit entry that maps `IMPORTER_PARTIAL_COMMIT_ISSUES → 422`. A refactor that dropped the entry would fall through to `asyncHandler`'s generic 500 path, pager-alert on a user-action-recoverable state (universe + series already persisted, only the issue loop rolled back), and strip the `arcAlreadyPersisted` / `skipArcOnRetry` retry signals the client gates the retry-without-arc-overwrite path on — the exact regression `server/routes/importer.js:28-37`'s long comment warns against. New `commit` suite test mocks `commitImport` to reject with `{ code: ERR_PARTIAL_COMMIT_ISSUES, context: { universeId, seriesId, arcAlreadyPersisted, skipArcOnRetry } }`, asserts status 422, asserts `body.code === ERR_PARTIAL_COMMIT_ISSUES`, and asserts the full context object survives `sanitizeContext` and reaches the client. PLAN cited the historical status (`→ 207`); test pins the current implementation (`→ 422`) per the same in-code rationale (207 trips the client `request()` helper's `response.ok === true` branch and mis-toasts the partial commit as a success). 11/11 route tests pass.
-
-- **[med-ai-dispatch-server-lib-tuipromptrunner-js-198] TUI prompt-runner output buffer raised 1MB → 8MB and overflow no longer silent.** `server/lib/tuiHandshake.js` `OUTPUT_BUFFER_CAP` / `OUTPUT_BUFFER_HEADROOM` bumped from 1MB / 1.25MB to 8MB / 10MB so realistic full-context LLM replies (~600KB UTF-8 from a 200K-token window plus screen chrome) no longer head-truncate mid-token when the TUI fails to write its response file and the central handler falls back to the cleaned PTY scrape. `server/lib/tuiPromptRunner.js#executeTuiRun` now tracks an `outputBufferTruncated` flag, logs a one-time warning the first time the new cap is exceeded, and surfaces the flag in the run record's `extras` (`outputTruncated`) so /runs can flag responses where the start may have been lost. The pinned-constants test in `tuiHandshake.test.js` was updated with the new sizes; nothing else moved. 1537/1537 server lib tests pass.
-
-- **[agent-tui-spawn-truncation-warn-parity] Agent TUI spawner mirrors the prompt-runner's overflow visibility.** `server/services/agentTuiSpawning.js` previously sliced the head off both `outputBuffer` (parsed-line, `appendLine` path) and `rawBuffer` (raw PTY stream, fed to `analyzeAgentFailure`) when they crossed `OUTPUT_BUFFER_HEADROOM` / `RAW_BUFFER_HEADROOM` with no signal — a long-running CoS agent whose failure tail got buried behind a long banner-redraw chatter could land in error analysis with the actual symptom already gone. The spawner now tracks `outputBufferTruncated` + `rawBufferTruncated` flags symmetric to `tuiPromptRunner.js`: warns once per buffer (`console.warn` with the agent id + headroom MB) and writes the flag to the agent record via `updateAgent(agentId, { metadata: { [flag]: true } })` so consumers can distinguish a long-run-with-overflow from a clean short run. The companion runner's flag flow stayed in place; this closes the parity gap deferred from `[med-ai-dispatch-server-lib-tuipromptrunner-js-198]`. Three new tests in `agentTuiSpawning.test.js` cover the warn-once + metadata-write for both buffers (via a `vi.mock` of `../lib/tuiHandshake.js` that shrinks the thresholds to ~200 bytes so the wiring is exercisable without pushing millions of bytes through the spawner) and the under-threshold negative case. 6154/6154 server tests pass.
-
-- **[drop-redundant-getissue-precheck-comic-cover-render] Comic-cover render routes drop their redundant `getIssue` precheck.** The two comic-issue cover-render routes in `server/routes/pipeline.js` (`/issues/:id/stages/comicPages/cover/render` and `…/back-cover/render`) carried a `prepare: (req) => issuesSvc.getIssue(req.params.id)` callback that ran an extra `data/issues.json` read on every render request — `enqueueComicCover` / `enqueueComicBackCover` already call `loadBibleContext(issueId)` (`server/services/pipeline/visualStages.js:401`), whose first step at `loadBibleContext`:141 is the same `getIssue(issueId)` raising `PIPELINE_ISSUE_NOT_FOUND` with the same `mapServiceError` → 404 mapping. The precheck was a duplicate read with no behavior difference. Dropped the `prepare` callback at both routes and dropped the `prepare` knob from `makeCoverRenderHandler` entirely — there were no other callers. The route comment block now points at the real upstream source of the 404 instead of the misleading "before we spend the bible-context load" framing. Per-request `data/issues.json` reads on the affected routes drop from 2 to 1. 85/85 pipeline route tests pass (including the unchanged `404s for an unknown issue` case, now serviced from `loadBibleContext`). Captured `[audit-remaining-getissue-prechecks-in-pipeline-routes]` as a follow-up to sweep the same precheck pattern at ~10 other sites in pipeline.js where the called service may already raise the same error.
-
-- **[med-ai-dispatch-server-services-digital-twin] `callProviderAI` migrated to `runPromptThroughProvider` — TUI providers now work for Digital Twin AI calls.** `server/services/digital-twin-helpers.js#callProviderAI` previously had a hand-rolled `if (provider.type === 'api') fetch(...) else spawn(provider.command, ...)` split that silently routed TUI providers (claude-code, etc.) into the CLI spawn branch. That branch piped the prompt into stdin against a process expecting a PTY — depending on the binary either it hung until the per-call timeout or scraped its interactive banner chrome into the returned text, so every Digital Twin AI feature was unusable when the user's active provider was a TUI. Migrated to the shared `runPromptThroughProvider` from `server/lib/promptRunner.js` (`source: 'digital-twin'`) so dispatch goes through `executeCliRun` / `executeApiRun` / `executeTuiRun` per `provider.type`, with the same TUI-chrome stripping the rest of the codebase relies on. Return shape (`{ text }` / `{ error }`) is preserved so the 12 call sites across `digital-twin-testing.js`, `digital-twin-import.js`, `digital-twin-enrichment.js`, and `digital-twin-analysis.js` don't change behavior on the parse-and-fallback paths. The legacy `temperature` / `max_tokens` named options were dropped from both the function signature and all 12 call sites — the toolkit's `executeApiRun` doesn't forward them, matching every other unified-runner caller in the repo, so keeping them at call sites would have been cargo-culted. `server/services/digital-twin.test.js` switched from mocking `global.fetch` to mocking `../lib/promptRunner.js` for the goodreads-CSV provider-call test. 87/87 digital-twin tests pass; 6150/6150 server tests pass.
-
-- **[extract-cover-render-handler-factory] Four cover-render route handlers collapsed into one config-driven factory.** The volume front/back + comic-issue front/back cover-render routes in `server/routes/pipeline.js` were 95% identical — differing only in { Zod schema, slot field (`cover` vs `backCover`), script body field (`coverScript` vs `backCoverScript`), optional precheck (issue routes ran `getIssue` for an early 404), enqueue fn (`enqueueVolumeCover` / `enqueueVolumeBackCover` / `enqueueComicCover` / `enqueueComicBackCover`), write fn (`seriesSvc.updateSeasonOnSeries` vs `issuesSvc.updateStageWithLatest`), and response shape (`{ season, series }` vs `{ cover|backCover, issue, stage }`) }. Extracted `makeCoverRenderHandler({ schema, slotField, scriptField, prepare, enqueue, applyWrite, buildResponse })` factory + a pure `buildCoverPatchFn` helper that owns the shared `compute` closure — same `typeof body[scriptField] === 'string'` script-gate semantics (absent preserves, empty-string clears) on all four routes, just defined once. Two named helpers (`updateVolumeSeason`, `updateComicPagesStage`) capture the per-record write signature so the route definitions only declare what's actually different. Net ~80 LOC → ~25 LOC across the four routes; 85/85 pipeline route tests pass (preserves the script-gate invariants pinned by `[med-pipeline-server-routes-pipeline-js-1416-1452]`); 6150/6150 server tests pass.
-
-- **[med-sharing-server-services-sharing-version-js] Sharing importer salvages pre-B.4 series-side canon instead of dropping it.** Cross-peer share-bucket imports from a pre-B.4 install previously lost any `series.{characters, settings|places, objects}` arrays silently — `sanitizeSeries` (post-B.4) strips those fields on insert, and the importer fed records straight into `insertSeriesWithId`. The B.4 schema teardown intentionally moved canon onto the linked universe, so the recovery shape was the existing `migrateSeriesCanon` CLI helper; the gap was that nothing ran it for peer-authored records. `server/services/pipeline/migrateSeriesCanon.js` now exposes a per-record helper `applyLegacySeriesCanonToUniverse(series, { dryRun, log })` (extracted from the CLI batch's loop body) that folds legacy canon into the linked or freshly-created universe with the same `SERIES_EXTRACT` + `autoLock` + `sourceSeriesId` provenance the live extract path uses. `server/services/sharing/importer.js` calls this helper for every incoming series record carrying a non-empty `characters / settings / places / objects` array — between the universes merge loop and the series merge loop, so the universe (existing or newly minted for orphan series) holds the canon by the time `sanitizeSeries` runs. The pre-022 `settings[]` wire name is coalesced onto `places[]` inside the helper so peers shipping either rename-era survive. Two new integration tests in `services/sharing/integration.test.js` lock in the linked-universe and orphan-universe paths; 5904 server tests pass. `SHARING_SCHEMA_VERSION` is intentionally NOT bumped — the version bump would only help if paired with a hard refusal, and salvaging the data is the kinder outcome.
-
-- **[med-pipeline-server-routes-pipeline-js-1416-1452] Cover render routes no longer overwrite `script` when the body omits it.** The four cover render handlers in `server/routes/pipeline.js` (issue front, issue back, volume front, volume back) previously wrote `script: result.coverScript || ''` (or `result.backCoverScript || ''`) on every render, where `result.<script>` is the *resolved* value from the service (body override OR persisted record fallback). That collapsed two distinct cases — "body omitted the field" and "body explicitly cleared it to empty string" — into the same overwrite, and races against blur-save (PATCH `stages.comicPages.cover.script`) because the render path's resolved value can be stale by the time `updateStageWithLatest` / `updateSeasonOnSeries` writes. Switched all four routes to gate the `script` write on `typeof body.<scriptField> === 'string'` — absent leaves the persisted script untouched, empty string is honored as an intentional clear, present text writes through. Added the missing `enqueueComicBackCover` / `enqueueVolumeCover` / `enqueueVolumeBackCover` mocks to `pipeline.test.js` (only the front-cover mock existed before) and added 5 new tests covering absent-preserves / empty-clears semantics across all four routes. 85/85 pipeline route tests pass; 6089/6089 server tests pass.
-
-- **[med-pipeline-server-services-pipeline-arcplanner-2] Tighten `buildSeasonRemap` Pass 3 — fire only on forced 1↔1 pairings.** `server/services/pipeline/arcPlanner.js#buildSeasonRemap` previously ran its positional fallback whenever the unmatched-old and unmatched-new counts matched (any positive equal length). With 2+ unmatched on each side that's a guess: the LLM may have reshuffled or renamed everything, and number-sorted positional pairing silently invents wrong `oldSeasonId → newSeasonId` mappings — child issues land under the wrong season instead of the visible "ungrouped" bucket. New guard fires Pass 3 only when exactly one unmatched on each side (a forced 1↔1 pairing with no ambiguity) and logs the pairing it made. When the guard suppresses a 2+×2+ fallback, a warning logs the cardinality and the orphans correctly route to `seasonId: null`. Title labels are sanitized via the shared `stripAnsi` helper (`server/lib/ansiStrip.js`) plus a C0/C1-control sweep + whitespace collapse + 60-char cap before interpolation to keep logging single-line. Five new tests cover the 1↔1 firing path, the 2+×2+ suppression path, the newline-collapse sanitizer, the full-CSI-sequence sanitizer, and a pinned regression for the 2-old × 2-new matching-numbers case (Pass 2 unique-number handles it; no warning fires). 70/70 arcPlanner tests pass; 518/518 pipeline tests pass.
-
-- **[strip-stray-tryreadfile-from-instances-mocks] Drop dead `tryReadFile: vi.fn().mockResolvedValue(null)` entries from two `instances.js` mock factories.** `server/services/sharing/subscriptions.test.js:25` and `server/services/sharing/integration.test.js:44` were a leftover copy-paste from when these tests used to mock `lib/fileUtils.js`; `instances.js` doesn't export `tryReadFile`, so the keys are no-ops that only confuse the next reader. Removed and reformatted both factories onto the project's standard multi-line `vi.mock(..., () => ({ ... }))` shape. The third site PLAN.md referenced — `server/services/mediaAnnotations.test.js` — turned out to be a false positive: its `tryReadFile` lives inside the legitimate `lib/fileUtils.js` mock, and its `instances.js` mock at line 15 is already clean. The 45 tests across the two edited files pass; nothing else changes.
-
-- **[hoist-certmeta-to-top-level-lib] `readCertMeta()` hoisted to top-level `lib/certMeta.js` so `scripts/` and managed apps can share it.** The previous `server/lib/certMeta.js` baked `PATHS.data` at module load, so `scripts/print-access-url.js` couldn't reach it without crossing the scripts/server boundary and instead carried its own inline `try { JSON.parse(readFileSync(...)).mode } catch {}` block. Moved the module next to `lib/certPaths.js` (zero-dep, side-effect-free — same constraint set as the existing sibling) and changed the signature to `readCertMeta(metaPath)` so each caller passes the path it already resolved via `certPaths(PATHS.data).meta`. Four callers updated: `server/lib/peerSelfHost.js`, `server/lib/networkExposure.js`, `server/services/certRenewer.js` (two call sites), and `scripts/print-access-url.js` (drops the inline try/catch in favor of `readCertMeta(META_PATH)?.mode || ''`). The test file moved too and gained cases for the `metaPath` argument, `statSync`/`readFileSync` throwing (EACCES/EIO), and primitive JSON (parsed value gated on `typeof === 'object' && !Array.isArray`). The `JSON.parse` + try/catch is inlined rather than reusing `server/lib/fileUtils.js#safeJSONParse` — the JSDoc notes this is the cost of the zero-dep boundary that lets `scripts/` import the helper. `server/lib/{index.js, README.md}` barrel + catalog rows removed per the maintenance rule. All 6133 server tests + 270 client tests pass.
-
-- **[image-gen-mode-enum-unify] Unify the image-gen mode enum across server + client.** The bare `'codex'` / `'local'` / `'external'` string literals that lived at ~25 dispatch sites across `server/services/imageGen/{index,codex,local,external}.js`, `server/services/mediaJobQueue/index.js`, `server/services/pipeline/visualStages.js`, `server/services/universeCharacterSheet.js`, `server/routes/{imageGen,universeBuilder,sdapi,pipeline}.js`, `server/services/pipeline/issues.js`, `server/services/voice/tools.js`, and the matching client surfaces (`ImageGen.jsx`, `ImageGenTab.jsx`, `VisualGenSettings.jsx`, `ImageGenControls.jsx`, `MediaJobsQueue.jsx`, `MediaLightbox.jsx`, `PromptRefineModal.jsx`, `normalize.js`, `imageGenResolutions.js`, `wrImageDefaults.js`, `ComicScriptStage.jsx`, `UniverseBuilder.jsx`) now flow through a typed enum. Server adds `IMAGE_GEN_MODE = Object.freeze({ EXTERNAL, LOCAL, CODEX })` in a new `server/services/imageGen/modes.js` (standalone so the dispatcher and the provider modules can both import without a cycle), re-exported from `imageGen/index.js`; `IMAGE_GEN_MODES` (the Zod-validator alphabet) is now derived from `Object.values(IMAGE_GEN_MODE)` so the two can't drift. Client `IMAGE_GEN_MODE` in `client/src/lib/imageGenBackends.js` is `Object.freeze`d to match. Zod schemas in `pipeline.js` and `universeBuilder.js` now consume the constants too so a future mode addition is one edit. Provider binary names (`DEFAULT_BIN = 'codex'`) and model-fallback strings stay as bare literals — they're not modes. Three test mocks (`imageGen.test.js`, `sdapi.test.js`, `voice/tools.test.js`) updated to export the new constant. Codex review caught five additional dispatch sites the first pass missed; second pass is CLEAN. 6096/6096 server tests + 240/240 client tests pass.
-
-- **[extract-readcertmeta-helper] Shared `readCertMeta()` reader extracted from three call sites.** `server/lib/peerSelfHost.js`, `server/services/certRenewer.js`, and `server/lib/networkExposure.js` each open-coded their own `data/certs/meta.json` reader — three slightly different shapes (`statSync({throwIfNoEntry:false}) + safeJSONParse` in the first two, brittle `existsSync + JSON.parse` in the renewer that would throw on a partial mid-`setup:cert` write). Consolidated into `server/lib/certMeta.js` exporting `readCertMeta() → { mode, hostname?, ips? } | null`, standardized on the safe-JSON pattern so the renewer no longer logs noise on partial writes. New `certMeta.test.js` covers missing/malformed/tailscale/self-signed; barrel + README catalog rows added per the `server/lib/` maintenance rule. `/simplify` also cleaned out two dead `tryReadFile: vi.fn()` mock entries in `peerSelfHost.test.js` and `networkExposure.test.js` (leftover from earlier iterations, neither file imports `tryReadFile`). All 6100 server tests pass. Captured `[hoist-certmeta-to-top-level-lib]` as a follow-up to share the helper with `scripts/print-access-url.js` (a fourth bespoke reader) once the path is parameterized.
-
-- **[unknown-instance-id-sentinel-extract] Promote `UNKNOWN_INSTANCE_ID = 'unknown'` to a shared export of `server/services/instances.js`.** The literal `'unknown'` instance-id sentinel was duplicated at ~10 sites — `getInstanceId()`'s default, `sharing/importer.js`'s local `const UNKNOWN_INSTANCE_ID`, plus comparisons / fallbacks in `mediaAnnotations.js` (readAll heal check, `instanceId === 'unknown'` skip, `mergePeerAnnotations` peer-id guard, `setAnnotation` precondition), `sharing/manifest.js` (`annotationManifestFilename`, `buildManifest` senderInstanceId, `subscriptionFilename`, `manifestFilename` slug fallback, `pruneBucketManifests` guard), and `sharing/annotationsSync.js#flushAll`. All instance-id usages now reach for the named constant from `instances.js`. Different sentinels that happen to share the same string value — peer health-status `status: 'unknown'`, `producedByVersion || 'unknown'`, `source || 'unknown'` display-name — are intentionally left as bare literals because they're not instance ids. Codex review flagged that the new transitive import chain through `manifest.js → instances.js → peerSelfHost.js` pulled in a module-load `certPaths(PATHS.data)` read in `peerSelfHost.js`, making tests that proxy `PATHS.data` after import brittle. Moved that read into the `getSelfHost()` body — `PATHS.data` is now resolved at call time. Closes both `[unknown-instance-id-sentinel-extract]` and `[promote-unknown-instance-id-constant]` — the two PLAN entries were duplicate framings of the same refactor. 6136/6136 server tests + 242/242 client tests pass.
-
-- **[cleanplateprompt-migrate-to-rich-canon-fragments] Clean-plate descriptor body now flows through `richCanonDescriptorFragments('place', setting)`.** `composeCleanPlatePrompt` (`client/src/lib/cleanPlatePrompt.js`) was hand-rolling `description + Palette + recurringDetails` extraction at lines 26–30 and silently dropped `era` / `weather` — the same gap `[pipeline-visual-stages-setting-field-injection]` closed for storyboard + comic-panel renders. Migrated the descriptor body to `mapCanonDescriptorFragments(richCanonDescriptorFragments('place', setting), { trailingPeriod: true })`, matching the existing place-side helper call in `scenePrompt.js:104`. Output is byte-identical for the legacy three-field case (verified via the existing populated test) and now surfaces era + weather when populated. Two new tests in `cleanPlatePrompt.test.js` lock in both halves — the era/weather positive case and the blank/whitespace-only negative case. 242/242 client tests pass.
-
-- **[hoist-loopback-host-helper-to-client-lib] Loopback / secure-context helpers hoisted to `client/src/lib/loopbackHost.js`.** `client/src/components/NetworkExposureWidget.jsx` previously re-declared `LOOPBACK_HOSTS` + `isLoopbackOrigin` + `describeMicAvailability` inline (the server's `isLoopbackHost` in `server/lib/networkExposure.js` isn't reachable from the browser). New shared client module exports `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` so future secure-context callers (mic, voice, clipboard heuristics) reuse one rule. The hoisted `isLoopbackHost` broadens the IPv4 check from the single literal `127.0.0.1` to the full `127.0.0.0/8` range (`/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/`) to match browser Secure Context behavior — the kernel routes the whole block to lo0, so `127.5.6.7` over plain HTTP is also a secure context in the browser. Widget swaps its three inline helpers for two imports. `/simplify` reuse pass picked up a third inline loopback check in `client/src/components/settings/ImageGenTab.jsx#advertisedA1111Url` (`h === 'localhost' || h === '127.0.0.1' || h === '::1'`); migrated to `isLoopbackHost(h)` in the same diff so the advertised-A1111 hint now also rejects the browser-bracketed `[::1]` form and the full 127.x range. Barrel + README row added per the `client/src/lib/` maintenance rule; 30 new tests in `loopbackHost.test.js` cover the IPv4 range expansion, IPv6 bracketed form, case-insensitivity, and the three branches of `describeMicAvailability`. 270/270 client tests pass; lint clean.
-
-- **[imagegen-local-defer-module-load-side-effects] Drop the module-load `IMAGE_MODELS` snapshot in `server/services/imageGen/local.js`.** The `export const IMAGE_MODELS = Object.fromEntries(getImageModels().map(...))` line ran `loadMediaModels()` at import time — which `mkdirSync`s the registry dir and `writeFileSync`s a default registry on first run. Any importer reaching `imageGen/local.js` via a test that mocks `PATHS.data` to a non-writable path (e.g. `routes/pipeline.test.js → routes/pipeline.js → universeBuilderCollectionHook.js`) failed on `mkdirSync('/mock/data')`. The export was dead (zero callers — grep confirmed) and `generateImage()` already reads the live registry via `getImageModels()`. Removed the export, reverted the 2026-05-19 lazy-import workaround in `services/universeBuilderCollectionHook.js` (now a normal static `import { readImageSidecar }`). Also tightened `enrichSidecar` to use `atomicWrite` (temp+rename) instead of `writeFile` — the prior plain write had a flaky race in tests where five-at-a-time batch enrichment let concurrent readers observe a mid-truncate empty file. 6090/6090 server tests + 234/234 client tests pass; the previously-flaky `enriches every sidecar in a batch` test now passes 10/10 runs.
-
-- **[promote-provider-type-constants-to-shared-module] Promote provider-type literals to a shared `PROVIDER_TYPES` enum.** `server/lib/aiToolkit/constants.js#PROVIDER_TYPES` grows `TUI: 'tui'` alongside the existing `CLI`/`API`, and the object is now `Object.freeze`d so callers can't mutate the shared enum. Server-side `LIGHT_CONTEXT_PROVIDER_TYPES` set + the `isTui` / `providerType` default in `server/services/agentPromptBuilder.js` now read from `PROVIDER_TYPES.{CLI,TUI,API}` instead of bare string literals. A mirror `PROVIDER_TYPES` is exported from `client/src/utils/providers.js` (the toolkit dir is intentionally kept self-contained per CLAUDE.md, so the client can't import the server copy directly), and the four client helpers (`isTuiProvider`, `isCliProvider`, `isProcessProvider`, `providerTypeClass`) now read from it. A new `providers.test.js` case statically imports the server enum and asserts the two enums stay in lockstep, so a future divergence fails CI instead of silently drifting. 13/13 provider helper tests pass; 25/25 agentPromptBuilder tests pass.
-
-- **[sweep-provider-type-api-inline-checks-in-client] Adopt `isApiProvider` + new `enabledApiProviderFilter` at saved-provider sites.** Sibling sweep of `[sweep-provider-type-tui-inline-checks-in-client]`. `client/src/utils/providers.js` gains `isApiProvider(provider)` so the predicate set (`isTuiProvider`/`isCliProvider`/`isApiProvider`/`isProcessProvider`) is now complete, plus an `enabledApiProviderFilter` export — a stable, module-scoped filter for `useProviderModels({ filter })`. Six saved-provider sites migrated: `AIProviders.jsx:265, :399` (endpoint chips), `GoalsTreeView.jsx` + `GoalsListView.jsx` (the two byte-identical `API_PROVIDER_FILTER` consts now both consume the shared helper — surfaced by /simplify reuse agent on this diff), `TasteTab.jsx#loadProviders`, and the two MeatSpace `Post*` effect-time filters (`PostDrillConfig.jsx:117`, `PostSessionLauncher.jsx:13`). `formData.type === 'api'` in the AIProviders edit form stays inline (form-draft state, same exclusion convention as the TUI sweep). `providers.test.js` adds 2 new tests for `isApiProvider` plus 2 for the hoisted filter. 237/237 client tests pass.
-
-- **[sweep-provider-type-tui-inline-checks-in-client] Adopt `isTuiProvider` + new `isCliProvider` / `isProcessProvider` helpers at the saved-provider chip sites.** Three inline `provider.type === 'tui'` / compound `'cli' || 'tui'` checks in `client/src/pages/AIProviders.jsx` (lines 262, 310, 396) and two in `client/src/components/cos/TaskAddForm.jsx` (lines 86, 88) now flow through `client/src/utils/providers.js`. Two new one-liner exports added there: `isCliProvider(provider)` and `isProcessProvider(provider)` (`isCliProvider || isTuiProvider` — the predicate for "shows a Command + args" config). `formData.type === ...` checks inside the AIProviders provider-edit form intentionally stay inline (PLAN scoped to saved-provider chips). New `client/src/utils/providers.test.js` covers all five helpers (10 assertions, including nullish edge cases). Two deferred follow-ups captured in PLAN.md: `[sweep-provider-type-api-inline-checks-in-client]` (sibling sweep across AIProviders, goals views, digital-twin tabs) and `[promote-provider-type-constants-to-shared-module]` (unify the partial `PROVIDER_TYPES` constant in `server/lib/aiToolkit/constants.js` and have the helpers read from it). 201/201 client tests pass.
-
-- **[extract-usependinglistrows-hook] Unify pending-row buffers in `WardrobeSection` + `CharacterDetailEditor` behind a shared hook.** New `client/src/hooks/usePendingListRows.js` collapses the "list-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`" pattern that was inlined in `CanonCard.jsx#WardrobeSection` and `CharacterDetailEditor.jsx`'s per-LIST_SECTION block (each had grown slightly different id-handling: `wd-<uuid>` ids that round-trip verbatim vs `pending-<key>-<uuid>` client-only ids stripped at promotion). The hook accepts `idPrefix` + `stripIdOnPromote` so both conventions survive intact, and a new `ListSectionEditor` subcomponent inside `CharacterDetailEditor` owns one hook instance per section (hooks can't be called inside `LIST_SECTIONS.map`). Skipping the stale `[route-medialightbox-settings-drawer-through]` PLAN entry along the way — the drawer was removed in commit ed0e4859 so no migration target exists. Net 77 LOC removed across the two call sites; 11 new tests cover add/promote/remove/required-column gating and the `crypto.randomUUID` fallback path. 202/202 client tests pass; lint clean.
-
-- **[consolidate-cert-path-constants] cert/key/meta path constants extracted to `lib/certPaths.js`.** The `data/certs/{cert,key,meta}` path layout had been hand-rebuilt at ten sites — four flagged in PLAN.md (`scripts/setup-cert.js`, `scripts/open-ui-in-browser.js`, `server/services/certProvisioner.js`, `server/services/certRenewer.js`) plus six the audit picked up (`scripts/print-access-url.js`, `server/index.js`, `server/lib/peerSelfHost.js`, `server/lib/networkExposure.js`, `server/routes/apps.js`, `server/services/apps.js`). New zero-dep helper `lib/certPaths.js` exports `certPaths(dataDir) → { dir, cert, key, meta }`; placed at the repo-root `lib/` alongside `lib/tailscale-https.js` so both bootstrap scripts and the server can import it without crossing into `server/lib/`. All ten callsites destructure what they need; `server/vitest.config.js` extended to discover `../lib/**/*.test.js` so the new `certPaths.test.js` runs in the project's single test entrypoint. No behavior change.
-
-- **[apicore-request-arraybuffer-response-type] `apiCore.request()` grows an `arraybuffer` `responseType` escape hatch; two TTS audition helpers stop bypassing the shared client.** `client/src/services/apiCore.js#request` now accepts `{ responseType: 'arraybuffer' }` — when set, the helper returns `response.arrayBuffer()` instead of parsing JSON, while still funneling the error path (server-shaped 4xx/5xx, network-unreachable toast, `err.code` / `err.status` / `err.context` forwarding) through the same code. `apiVoice.js#testTts` and `apiPipeline.js#previewPipelineTtsVoice` dropped their raw `fetch` paths and now call `request()` with `responseType: 'arraybuffer'` + `silent: true` (all three callers — `VoiceTab.handleTest`, `VoiceTab.handlePreviewVoice`, `VoicePicker.handleAudition` — already own their own catch-block toasts, so silent avoids double-toasting per the CLAUDE.md convention). Drops ~25 LOC of duplicated `if (!res.ok) parse + throw` shaping. Also pruned a stale PLAN.md entry ([extract-useswipenav-hook-lib-clipboard-js]) — both halves of that item already shipped (clipboard helpers in `client/src/lib/clipboard.js`, swipe in `client/src/hooks/useSwipeNav.js`; `MediaLightbox.jsx:122` has been calling `useSwipeNav` since PR #261). 163/163 client tests pass; lint clean.
-
-- **[extract-mergeexpandintodraft-draft-result-from] `mergeExpandIntoDraft` extracted from `UniverseBuilder.jsx#handleExpand`.** The merge block — lock-honoring scalar pick, locked-variation/sheet preservation, category `kind` precedence, canon dedupe by name/slugline/alias, addedCanonCount + pendingAdditions partitioning — moved to a pure `client/src/lib/universeBuilderExpand.js` so the I/O shell of `handleExpand` (validation, `expandUniverse()` call, `setDraft`, auto-save, toast) is no longer tangled with merge semantics. `handleExpand` shrinks from ~260 lines to ~120; the new module exports `mergeExpandIntoDraft`, `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` (the locked-items extractor used by both the API-call site and the merge so they can't drift). 27 new unit tests pin the lock semantics (absent vs intentional `""` clear), category-kind precedence ("other" upgradable; user-curated kinds preserved), composite-sheet dedupe, place-slugline normalization, within-batch alias dedupe, and `pendingAdditions` partitioning by trunk. Existing 10-test `UniverseBuilder.test.jsx` still passes; full client suite at 190/190.
+## Added
-- **[datasync-bundle] `dataSync.js` write-pattern + checksum-cache cleanup (2 items).** (1) [datasync-migrate-categories-to-atomicwrite] Replace seven inlined `ensureDir + writeFile(JSON.stringify(...))` triples across the goals/character/digitalTwin/meatspace categories with single `atomicWrite(path, data)` calls — temp+rename atomicity protects readers from seeing a partial write, which matters for the larger pipeline/universe JSON files that other services write concurrently. Pre-loop `ensureDir` calls dropped because each `atomicWrite` ensures its own dirname. (2) [datasync-checksum-only-fast-path] Add a per-category mtime-keyed cache in front of `getChecksum()`. The orchestrator hits this every cycle and previously materialized the full snapshot just to discard `data`; now a `stat`-only path returns the cached checksum when no underlying file changed since the last computation, falling through to `getSnapshot()` on a cache miss. Same checksum value as before — pure optimization, no protocol break. Three new tests cover cache consistency across consecutive calls, invalidation after `applyRemote`, and invalidation on out-of-band file mutations (16/16 dataSync tests pass; 5973/5973 full server suite).
+- **Network Exposure dashboard widget.** Shows how PortOS is exposed on the network — HTTP vs HTTPS, bind address (loopback / all-interfaces / specific), cert mode (Tailscale-trusted hostname vs self-signed), the loopback HTTP mirror port when HTTPS is on, and whether the current browser origin allows mic/voice. A red banner appears when PortOS is bound on all interfaces over plain HTTP. Seeded into the default "Everything" and "Ops" dashboard layouts.
-- **[med-ai-dispatch-server-services-aidetect-js-242] `aiDetect.js` migrated to `runPromptThroughProvider` — TUI providers now work on Settings → Detect App.** `server/services/aiDetect.js` had a legacy `if (provider.type === 'cli') … else if ('api') … else 'Unknown provider type'` dispatch that rejected TUI providers outright and duplicated spawn/fetch logic the central handler already covers. The two inline functions (`executeCliDetection`, `executeApiDetection`) and the local `spawn`/`fetch` machinery are gone; detection now flows through `runPromptThroughProvider` from `server/lib/promptRunner.js` with `source: 'ai-app-detect'`, `cwd: dirPath` (so a spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd), and a 60s default timeout. `parseAiResponse` also moved to the shared `extractJson` helper from `server/lib/jsonExtract.js`, which strips CLI banner text and repairs trailing-comma JSON — relevant for TUI providers that emit banner output around the JSON payload. New `server/services/aiDetect.test.js` locks in the dispatch behavior (regression test ensures TUI no longer fails with "Unknown provider type") plus directory + provider-disabled error paths and the banner-stripping JSON case.
+- **CoS task form: pick a reviewer for the Review Loop.** A compact dropdown next to the Review Loop checkbox lets you pick the post-PR reviewer (Copilot / Claude / Gemini / Codex; default Copilot). Non-Copilot choices skip the Copilot pre-request and tell the follow-up agent to drive an iterative CLI-based review against the PR diff instead. Agent cards show the selected reviewer when it isn't the default.
-- **[imagegen-autoclean-bundle] Image-gen auto-clean code-quality cleanup (4 items).** Bundled deferrals from the per-render auto-clean PR's `/simplify` pass. (1) [imagegen-autoclean-double-resolution] Extract `resolveAutoClean(body, settings, mode)` from `server/services/imageGen/index.js` and share it with `server/routes/imageGen.js` so the precedence resolution lives in one place — the route stamps the resolved value onto the request body and the dispatcher still resolves as a safety net for direct callers like `generateAvatar`. (2) [imagegentab-triplicate-autoclean-state-collapse] Collapse three `autoCleanCodex/Local/External` state vars in `client/src/components/settings/ImageGenTab.jsx` into one `autoCleanByMode` object with a curried `setAutoCleanFor(mode)` setter, dropping ~15 LOC of triplicated isDirty / saved-snapshot / patch / reload code. (3) [imagegen-savedautocleanbymode-derive] Drop the re-seed `useEffect` in `client/src/pages/ImageGen.jsx` and re-seed `autoClean` explicitly at the two mode-change points (`reloadBackends` + new `handleSelectMode`); `selectedModeRef` mirrors the latest value so `reloadBackends`'s `useCallback` stays stable. (4) [autoclean-sidecar-read-parallelize] Kick off the sidecar `tryReadFile` immediately after `cleanImageBuffer` returns so the disk read overlaps the PNG atomic-write window in `server/lib/imageClean.js#autoCleanGeneratedImage`. Added a `resolveAutoClean` shim to the imageGen-route test mock to mirror real precedence. All 5958 server + 163 client tests pass.
+- **Deep-linkable image preview modals.** Every page hosting an image gallery (Media History, Media Collections, Image Gen, Video Gen, Universe Builder variations + cast, Comic Script Stage, Nouns Stage) now drives its lightbox via a `?preview=<filename>` URL parameter — so a previewed image is shareable and survives reload. The browser back button closes the modal; prev/next navigation keeps history clean.
-- **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.
+- **Auto-clean after image generation — per-provider opt-in.** New checkboxes in Settings → Image Gen turn auto-cleaning on independently for the Codex, Local, and External providers. When on, every generated image is denoised and stripped of C2PA provenance metadata before it shows up in the gallery — what you see is already cleaned, no extra click. Clean failures fall back to the original image and never break the generation.
-## Added
+- **Per-render "Auto-clean this render" checkbox on the Image Gen form.** A checkbox under the Generate button lets you override the saved auto-clean default for a single render; the label flips to "(overrides saved default)" when it differs from the saved value. Quietly fixes a latent bug along the way: the saved auto-clean toggle previously had no effect for Codex or Local renders — only External worked. All three providers now honor the saved setting.
-- **[client-tests-for-deep-routing-drag-smoke-tests-for] Client tests for deep routing + chip drag-reorder.** Two new smoke-test surfaces. (1) `client/src/hooks/useUniverseNav.test.jsx` — extracts `goToWorld` from `UniverseBuilder.jsx` (~14 lines + an unused `useNavigate` import) into a new `client/src/hooks/useUniverseNav.js` hook so URL transitions can be exercised via `renderHook` + `MemoryRouter` + a sibling `useLocation()` probe. 12 tests pin id encoding (reserved characters), `location.search` preservation across both forward and back-to-index navigation, prefixed mounts (`/media/universe-builder/...`), id-for-id swap, and the basePath regex (a `universeBuilderBasePath` named export). The hook gets a barrel entry + README row per the `client/src/hooks/` maintenance rule. (2) `client/src/components/universeBuilder/InfluenceChipsInput.test.jsx` — `vi.mock`s `@dnd-kit/core`'s `DndContext` so the test captures `onDragEnd` via a hoisted ref and fires it directly, and stubs `useSortable` to a no-op while keeping `arrayMove` real. 8 tests cover forward + backward chip reorder ordering, three no-op drag guards (same chip, drop off-list, stale active id), the X-button remove path, and readOnly-mode chrome. 211/211 client tests pass.
+- **Lightbox: original ↔ cleaned variant toggle.** When the previewed image has a manually-cleaned sibling (or is itself a cleaned sibling), a "View: Original | Cleaned" segmented control appears at the top of the lightbox details panel so you can flip between variants without closing the modal. The toggle is also a deep-linkable URL change. Auto-cleaned images replace the original in place, so the toggle correctly doesn't appear for them.
-- **[med-tests-no-tests-for-server-lib-ansistrip-js] Tests for `server/lib/ansiStrip.js` and `server/lib/tuiHandshake.js`.** New `ansiStrip.test.js` covers `stripAnsi` one-shot behavior and the `createStreamingAnsiStripper` chunk-boundary buffering (CSI/OSC split across chunks, bare `\x1B` at chunk end resolved as either single-byte or CSI on the next chunk, OSC body leak when terminator never arrives within the 4096-byte window, older unterminated bytes past the window). New `tuiHandshake.test.js` pins every paste-timing constant both production paths (`tuiPromptRunner.js`, `agentTuiSpawning.js`) depend on, plus `PASTE_MARKER_PATTERN`, `inferTuiCommand`, `applyCommandDefaults` (codex `--ask-for-approval never` injection), `buildTuiInvocation` (model-flag baked-in suppression for `--model X`, `--model=X`, `-m X`, `-m=X`, and the codex sentinel), and `detectMissingTuiBinary`. A latent OSC-stripping bug surfaced during the write — `ANSI_PATTERN`'s OSC alternative is dead code because the single-byte alternative `[@-Z\\-_]` matches `\x1B]` first, so OSC bodies leak into the cleaned stream; tests document the current behavior and the issue is logged as [ansistrip-osc-alternative-unreachable] in PLAN.md for a separate fix.
+- **Manual clean auto-files into the source's collections.** Cleaning an image via the lightbox Clean button used to leave the cleaned copy out of every collection the source belonged to. The cleaned image is now automatically added to every collection that contained the source, so you don't have to re-add it everywhere.
-- **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`.
+- **Per-bucket exporter hash cache.** Subscription re-exports of large series are dramatically faster — assets are no longer re-hashed on every export. A 200MB re-export drops from roughly 200MB of disk reads to a single index load plus one stat per file.
-- **CoS task form: pick the reviewer for the Review Loop (`--review-with`).** A new compact dropdown appears next to the Review Loop checkbox in `TaskAddForm.jsx` (copilot / claude / gemini / codex; default copilot). The choice is persisted on the task as `metadata.reviewer` and flows through the agent prompt, the follow-up agent's prompt (`/do:rpr --review-with <reviewer>`), and the worktree cleanup hook — for non-copilot reviewers, PortOS skips the GitHub Copilot reviewer-API pre-request and instructs the follow-up to invoke the chosen CLI against the PR diff instead. AgentCard chips show the selected reviewer when it isn't the default.
-
-- **Deep-linkable image preview modals via `?preview=<filename>`.** Every page hosting `<MediaPreview>` (Media History, Media Collections, Image Gen, Video Gen, Universe Builder variations + cast, Comic Script Stage, Nouns Stage) now drives the lightbox through a `?preview=<filename>` query param, so `/media/history?preview=foo.png` or `/universe-builder/:id?tab=cast&preview=foo.png` re-opens the same image on reload and is shareable. New `usePreviewRoute(items)` hook (`client/src/hooks/usePreviewRoute.js`) owns the URL round-trip — first open pushes a history entry so the browser back button closes the modal; prev/next nav and close replace so the history stack stays clean.
+## Changed
-- **Per-bucket exporter hash cache.** Subscription re-exports of large series no longer re-hash every referenced asset to confirm "blob already there." A new `<bucket>/assets/blobs/.index.json` sidecar maps `<sourcePath>:<mtimeMs>:<size> → <hash>` so `server/services/sharing/exporter.js#copyAssetIfPresent` skips both `sha256File` (multi-GB stream read) and the redundant `copyFile` when the cache hit's blob is still on disk. mtime change invalidates automatically because it's part of the key. A 200MB re-export drops from ~200MB of disk reads to a single JSON load + stat per asset.
+- **Honest SynthID copy in the Image Cleaner.** The Clean tooltip, the auto-clean settings descriptions, the per-render Image Gen checkbox, the Image Clean dev page, the success toast, and the palette keywords now all explicitly say the cleaner removes C2PA provenance metadata but does **not** defeat Google's SynthID watermark. The prior copy ("strips C2PA + reduces AI artifacts") was technically accurate but implicitly over-promised against SynthID-bearing renders (gpt-image / Imagen / Gemini). The Image Clean dev page now links to openai.com/synthid for verification.
-- **Auto-clean after generation — per-provider opt-in (codex / local / external).** New `settings.imageGen.{codex,local,external}.autoClean` flag wires the existing image-clean pipeline into the post-generation success path for each backend independently. When on for a provider, every generated PNG is run through `cleanImageBuffer` (sharp `median(3).sharpen()` + C2PA strip) and the cleaned bytes replace the original in place via atomic temp+rename — fires BEFORE the SSE `complete` event so subscribers see the cleaned image on first fetch. The sidecar gets `autoCleaned: true`, `cleanLevel: 'aggressive'`, `c2paStripped: <bool>`. A clean failure never fails the generation (logs + falls back to the un-cleaned PNG). Three new checkboxes in Settings → Image Gen (one per mode section); the manual Clean button on existing gallery images still produces a separate `_clean-aggressive.png` sidecar copy. Reachable from the lightbox: the metadata panel now shows a "Cleaned" row when the sidecar carries either `autoCleaned` (in-place) or `cleanedFrom` (manual copy) lineage. The clean primitives moved from `server/routes/imageClean.js` to `server/lib/imageClean.js` so the new `autoCleanGeneratedImage` helper is callable from services without crossing the routes→services dep direction; the HTTP route is now a thin wrapper.
+- **Image cleaning collapsed to a single button.** The light/aggressive split is gone — "light" mode proved unreliable in practice (visible C2PA-adjacent noise remained). The lightbox Clean affordance is one button with a clear tooltip; the Image Clean dev page dropped its level picker. Existing cleaned files on disk round-trip unchanged.
-- **Manual clean now auto-files into the source's collections.** Previously cleaning an image via the lightbox Clean button created `<filename>_clean-aggressive.png` in the gallery, but the cleaned copy didn't appear in any collection the source was part of — users had to manually re-add it everywhere. `POST /api/image-gen/:filename/clean` now scans every collection (`listCollections()`), finds the ones containing the source `image:<filename>` key, and calls `addItem()` for the cleaned filename on each. Idempotent across re-cleans (`ERR_DUPLICATE` is swallowed); best-effort overall (collection-write failures log a warning but don't fail the clean).
+- **First-run no longer silently flips port 5555 from HTTP to self-signed HTTPS.** PortOS used to auto-generate a self-signed cert on every start when Tailscale was unavailable, which broke the documented `http://localhost:5555` URL and forced a browser click-through. Fresh installs without Tailscale now stay on plain HTTP at the documented URL. The setup banner is cert-aware — when HTTPS is provisioned, it prints the loopback HTTP mirror (`http://localhost:5553`) and the Tailscale hostname instead of the now-broken localhost URL.
-- **Lightbox: original ↔ cleaned variant toggle.** When the previewed image has a manually-cleaned sibling in the same items list (or IS a cleaned sibling), a small segmented control appears at the top of the SettingsPane labeled "View: Original | Cleaned (aggressive)" — click flips the lightbox to the other variant without closing the modal. Drives the swap through the host page's existing `setPreview` URL machinery, so the toggle is also a deep-linkable URL change. New `client/src/components/media/variants.js` houses the pure `computeImageVariantGroup(item, items)` helper (unit-tested in `variants.test.js`); `MediaPreview.jsx` computes the group from its `items` prop and threads `variantGroup` + `onSelectVariant` into `MediaLightbox`. Auto-cleaned images replace the original in place (only one file exists) so the toggle correctly does not appear for them.
+- **Universe Builder cast preview now matches Media History exactly.** Clicking a cast/canon image used to open a stripped-down modal showing the character description instead of the prompt, with missing controls (no negative prompt, no notes, no Remix / Send to Video / Clean / Favorite). Canon clicks now open the same full-featured lightbox as the rest of the app, hydrated from the gallery sidecar so prompt, negative prompt, model, seed, and resolution all show up. The character descriptor falls back as a label only for legacy renders with no sidecar.
-- **Per-render "Auto-clean this render" checkbox on the Image Gen form** + a quiet fix to make saved auto-clean actually work for codex/local. The Image Gen page (`/media/image`) now exposes a checkbox under the Generate button that lets the user override the saved per-mode `imageGen.{mode}.autoClean` setting for a single render — toggles label changes to "(overrides saved default)" when the value differs from the saved one. The checkbox is seeded on mount + every mode switch from the active mode's saved setting, so the default-off case stays unsurprising. Wired through a new `autoClean: z.boolean().optional()` field on the generate route's schema, with multipart string→bool coercion in `coerceFormFields`. Same fix uncovered a latent bug: codex + local enqueue through `mediaJobQueue` and bypass the dispatcher's autoClean resolution, so the saved settings flag previously had no effect for those modes (only external mode worked, and nobody had caught it yet). The route is now the single resolution point — `data.autoClean = body.autoClean ?? settings.imageGen[mode].autoClean` runs once and the value flows through all three dispatch paths verbatim. The dispatcher still resolves autoClean as a safety net for direct callers (avatar route, voice tool). 6 new tests in `imageGen.test.js` cover the precedence matrix (body wins / saved inherited / default false / all three modes).
+- **Canon entries inline-edit their description.** The main description on each canon card (characters / places / objects) was previously a static paragraph with no edit affordance. Unlocked rows now render a buffered textarea — type, blur, save. Pre-migration characters that used the older `description` field migrate to the new field on first save. The pipeline series view stays read-only on purpose.
-## Changed
+- **Universe Canon — Render All per kind, compact single-kind view, deduped lock indicator.** A new "Render all (N)" button in each canon kind's toolbar fires reference renders in parallel for every entry that has a description but no image. When the canon section is already scoped to a single kind (deep-linked via `?kind=places` or a sidebar entry), the redundant inner card chrome is dropped so the page no longer shows a nested card-in-card. The redundant "🔒 LOCKED" chip on locked entries was removed because the lock toggle button on the right already conveys that state.
-- **SynthID-defeat backlog entry refined.** PLAN.md `Future Ideas` entry for the generative regen path narrowed: post-hoc / history-only (second button on the image-settings/lightbox modal, never wired into the active gen flow or as a per-render checkbox), `short-step` framing added next to the existing denoise-strength range, and explicitly hardware-gated on the user's incoming 128GB unified-memory machine. Also documents the 2026-05-20 detection-tool result (`C2PA removed, SynthID detected` on a cleaned codex render) and the heatmap-vs-template distinction — OpenAI's verifier renders the one-way correlation map `∫ image · template`, not the watermark template itself, which rules out deterministic image-processing approaches (heatmap subtraction, secondary-watermark overlay, frequency-band cancellation). Future-me doesn't have to relitigate why median/sharpen can't defeat SynthID.
+- **[med-sharing-server-services-sharing-version-js] Cross-peer share imports salvage older universe canon instead of silently dropping it.** Share-bucket imports from pre-B.4 PortOS installs used to lose any series-side canon (characters, places, objects) silently because the post-B.4 series sanitizer strips those fields. The importer now folds that legacy canon into the linked universe (creating a placeholder universe for orphaned series) so the data survives the migration.
-- **Image Cleaner copy: honest about SynthID.** The lightbox Clean tooltip, both auto-clean settings descriptions (Settings → Image Gen, and per-render Image Gen form checkbox), the `/devtools/image-clean` page subtitle, the success toast, the file-header comment in `server/lib/imageClean.js`, and the palette nav-manifest keywords (dropped `watermark`) now all explicitly say the cleaner removes the C2PA metadata chunk (verified: confirmed by openai.com/synthid showing "Content Credentials not detected" after a clean of a gpt-image render) but does NOT defeat SynthID. SynthID is embedded in pixel values and Google's published claims state it survives median+sharpen+re-encode by design; gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers after a clean. The prior copy ("strips C2PA provenance + reduces AI artifacts") was technically accurate per-step but implicitly framed the cleaner as a provenance-stripper, which over-promised against SynthID-bearing output. Devtools page also adds a yellow-tagged Note paragraph linking to openai.com/synthid.
+- **[med-ai-dispatch-server-lib-tuipromptrunner-js-198] TUI prompt-runner buffer raised from 1MB to 8MB; overflow is now visible.** Realistic full-context LLM replies (~600KB UTF-8 from a 200K-token window plus screen chrome) no longer head-truncate mid-token. When the buffer is exceeded, a one-time warning fires and the run record now carries an `outputTruncated` flag so the Runs page can flag responses where the start may have been lost.
-- **`isPlainObject` promoted to a named export of `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` check was previously inlined at 16 sites across `server/lib/`, `server/services/`, and `server/routes/`. The helper is now a named export of `objects.js` (surfaces through the `server/lib/index.js` barrel automatically) and all 16 sites import it. Pure refactor — no behavioral changes; the helper retains the "non-null, non-array `object`" semantics that match every existing call site (Date / Map / class instances still return true).
+- **[agent-tui-spawn-truncation-warn-parity] Agent TUI spawner surfaces output-buffer overflow.** Long-running CoS agents whose failure tail was previously buried behind banner-redraw chatter (and silently dropped on truncation) now record an overflow flag on the agent record with a one-time warning. Distinguishes "long run with overflow" from "clean short run" in error analysis.
-- **AI Toolkit "not initialized" errors now carry a typed code + 503 status across runner + promptService.** `server/services/runner.js` (13 sites) and `server/services/promptService.js` (12 sites) previously each inlined `if (!aiToolkitInstance) throw new Error(…)` checks that surfaced as untyped 500s with string-matched messages. Both now go through a private `requireToolkit()` helper that throws `ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — the same shape `providers.js` already throws. Callers (e.g. `visionTest.js`) can gate on `err.code === 'AI_TOOLKIT_NOT_INITIALIZED'` uniformly regardless of which service raised, and routes that hit any of the three services during toolkit warm-up now return 503 (service-unavailable) rather than a generic 500. No behavior change for the warmed path.
+- **[med-ai-dispatch-server-services-digital-twin] TUI providers now work for Digital Twin AI features.** Settings → Digital Twin previously hung or returned banner garbage when the active provider was a TUI (claude-code, etc.) — the dispatcher was piping stdin to a process expecting a PTY. Twin import, enrichment, testing, and analysis now flow through the shared runner with proper TUI handshaking.
-- **Universe Builder cast preview now matches Media History exactly.** Clicking a cast/canon image used to open a stripped-down modal: only Refine Prompt / Add to Collection / Download, no negative prompt, no notes, and the "prompt" field showed the character description rather than the actual prompt that produced the image. The canon section's local `<MediaPreview>` is gone — canon clicks now bubble up to the page-level lightbox, which hydrates from the gallery sidecar (real prompt, negative prompt, model, seed, resolution, …) and exposes the full action set (Refine Prompt, Remix, Send to Video, Clean, Add to Collection, Download, notes, favorite). The descriptor string is kept as a fallback label only when no sidecar exists (legacy canon renders). Character reference sheets still route through `/data/image-refs/` via a `canon-sheet:<filename>` key so a basename collision with a gallery image can't misroute the preview.
+- **[med-ai-dispatch-server-services-aidetect-js-242] TUI providers now work for Settings → Detect App.** The "Unknown provider type" error path is gone; TUI dispatch goes through the shared runner with the analyzed directory as the working directory, and JSON parsing is more forgiving of TUI banner output.
-- **First-run no longer silently flips :5555 from HTTP to self-signed HTTPS.** `scripts/setup-cert.js` ran on every `npm start` and, when Tailscale was unavailable, auto-generated a self-signed cert — breaking the documented `http://localhost:5555` URL and forcing a browser click-through. It now only auto-generates a self-signed cert when (a) the user explicitly passes `--self-signed`, or (b) a self-signed cert is already present (renewal path). Fresh installs without Tailscale stay HTTP-only on :5555 so the URL in the README and in `setup.sh`'s final banner just works. `setup.sh`'s "Access at:" banner is now cert-aware — when HTTPS got provisioned it prints the loopback HTTP mirror (`http://localhost:5553`) and the Tailscale hostname instead of the broken `http://localhost:5555`.
+- **[cleanplateprompt-migrate-to-rich-canon-fragments] Clean-plate prompts include era and weather.** Composing a clean-plate (background-only) image prompt used to drop the `era` and `weather` fields from place canon. The full descriptor now flows through, matching how storyboard and comic-panel renders already handle it.
-- **PLAN.md — CODEX 5.5 review residue folded in.** Triaged the 2026-04-25 CODEX 5.5 product/engineering review: confirmed the six concrete bugs (Brain Feeds + Time Capsule nav coverage, `/cos/scripts` dead target, `/ask` full-height workaround, client lint, route/nav contract tests) are all shipped, and added 15 unaddressed strategic items to PLAN.md under a new `### CODEX 5.5 review residue` Backlog section (perf/bundle, polling consolidation, client error reporter, network exposure UI, unified Review Queue, health provenance chips, dashboard intent layouts, autonomy guardrails, onboarding capability map, mobile task flows, operating-loop dashboard, sidebar IA collapse, visual modes, decision/provenance pattern, teaching empty states). Enriched the existing Knowledge Legacy Future Idea with the bundle scope from the review.
+- **[med-pipeline-server-routes-pipeline-js-1416-1452] Cover render no longer overwrites the cover script when the request omits it.** Triggering a cover render previously rewrote the persisted script field on every render, racing against any in-flight blur-save of the script. Now: an absent script field preserves the saved script, an explicit empty string clears it, and present text writes through.
-- **Canon entries (characters / places / objects) now inline-edit their description.** The card body's main description (`physicalDescription` for characters, `description` for places & objects) was previously a static `<p>` with no edit affordance — locked or not. Unlocked rows now render a buffered-on-blur `<textarea>` next to the existing per-row controls; the legacy `description` field on pre-migration characters pre-fills the editor and migrates to `physicalDescription` on first save. The pipeline series view (`NounsStage`) intentionally stays read-only because its `KINDS` config omits `descField`.
+- **[med-pipeline-server-services-pipeline-arcplanner-2] Arc-planner no longer guesses wrong on ambiguous season pairings.** When an arc-resolve LLM call left more than one season unmatched on each side, the positional-pairing fallback used to silently invent season-id mappings — child issues landed under the wrong season instead of the visible "ungrouped" bucket. The fallback now only fires for the unambiguous 1-on-1 case; multi-side ambiguity correctly routes orphans to ungrouped and logs the cardinality.
-- **Universe Canon section: Render All per kind + compact single-kind view + lock-indicator dedupe.** New "Render all (N)" button in each canon kind's toolbar that fires reference renders in parallel for every entry with a description and no existing image (the per-entry `renderingJobs` map already handles concurrent settle independently). When the canon section is already scoped to one kind (`?kind=places`, sidebar deep-links), the inner `<section>` wrapper + duplicate icon + "Places 25" header are dropped so the page no longer shows a nested card; the controls strip (count, Render all, bulk lock) stays as a slim toolbar above the list. The multi-kind view keeps its current chrome. Removed the redundant "🔒 LOCKED" chip from the card title — the lock toggle button on the right already conveys locked state via icon + accent color.
+- **AI Toolkit warm-up errors return 503 with a typed code.** Requests that hit the runner, prompt service, or provider service during toolkit warm-up used to surface as untyped 500s with string-matched messages. They now return `503 AI_TOOLKIT_NOT_INITIALIZED` so clients can distinguish "service still initializing" from genuine errors.
-- **PLAN.md cleanup.** Removed 9 already-completed `[x]` items (Universe-as-Canon Phase 2, Pipeline continuity / approval, scattered Code quality / Better-audit / Deferred-from-better entries) — those sections went away or shrunk since DONE.md is the canonical archive. Reorganized the Backlog: 32 items requiring decision/design or waiting on a precondition moved to a new `## Blocked on decision / design (skip for \`/claim\`)` section at the bottom, split into Audio/Video/Image gen, Voice/agents, Large product/UX redesigns, and Trigger-gated subsections. The remaining Backlog is now items an agent can pick up cold via `/claim` — concrete file:line bugs, scoped refactors, and well-specified small features. 218 → 200 lines.
+- **Mic-availability hint recognizes the full loopback range.** The secure-context predicate that decides whether mic / voice features are available now matches the entire `127.0.0.0/8` block and the bracketed IPv6 `[::1]` form, matching how browsers actually decide a context is "secure."
-- **Image cleaning collapsed to a single button.** The light/aggressive split is gone — `light` (median(1) only) was tested in production and proved unreliable, leaving visible C2PA-adjacent noise patterns. The `MediaLightbox` Clean affordance is now a single Eraser-icon button with a `title` tooltip ("Re-encode and denoise to strip embedded provenance metadata (C2PA) and reduce AI-generation artifacts. Saves a new image alongside the original."), and the `/devtools/image-clean` page dropped its level picker. The `POST /api/image-clean` and `POST /api/image-gen/:filename/clean` request bodies no longer accept `level`; the gallery clean filename suffix (`_clean-aggressive.png`) and sidecar `cleanLevel: 'aggressive'` field are kept unchanged so existing on-disk cleaned files round-trip correctly. `cleanGalleryImage(filename)` and `cleanImage(base64)` API helpers + the shared `useImagePreviewActions` `handleClean(img)` dropped their `level` argument across all five call sites (ImageGen, MediaHistory, MediaCollectionDetail, UniverseBuilder, lightbox).
+- **Retire `DONE.md`.** The audit trail for completed PLAN.md items is now `git log` + `.changelog/` — `/claim` removes the picked item from PLAN.md outright and appends to `NEXT.md` instead of archiving to DONE.md. Existing repos with a DONE.md on disk are left untouched. The slashdo submodule was bumped to v2.18.0 to match.
## Fixed
-- **`update.sh` / `update.ps1` now start PortOS when it wasn't already running.** Both scripts `pm2 kill` the daemon early to clear stale fork paths, then previously called `npm run pm2:restart` to bring the app back. `pm2 restart <ecosystem>` against a torn-down daemon doesn't reliably (re)start processes that aren't currently managed, so users who ran the updater while PortOS was stopped ended an "update complete" cycle with no server running and the auto-open script timing out against a dead port. The restart step now mirrors the `npm start` pattern — `pm2 delete --silent` → `pm2 start ecosystem.config.cjs` → `pm2 save` — which boots a fresh daemon, starts the apps, and persists the process list so they come back on reboot. The `STEP:restart:…` markers are preserved so the UI progress panel (`UpdateTab.jsx`) continues to render correctly.
+- **`update.sh` / `update.ps1` start PortOS when it wasn't already running.** Both updaters tear down PM2 early to clear stale fork paths, then previously called `pm2 restart` to bring the app back — which doesn't reliably restart processes that aren't currently managed. Running the updater while PortOS was stopped ended an "update complete" cycle with no server running and the browser auto-open timing out against a dead port. The restart step now boots a fresh daemon and starts the apps, matching the normal start flow.
-- **[med-pipeline-server-services-pipeline-arcplanner] `sanitizeSeasonList` now warns when LLM-emitted seasons collide on id.** `server/lib/storyArc.js#sanitizeSeasonList` dedupes by id with last-write-wins (Map.set overwrite) on every series persist. Two LLM-emitted seasons sharing an id were silently dropped before persist while child issues kept their `seasonId` pointers — leaving the issues attached to the surviving season under the colliding id, which is rarely what an arc-resolve LLM rewrite intended. The helper now tracks colliding ids during the loop and emits a single `console.warn` listing the offending ids (counting both total overwrites and distinct colliding ids) so the responsible run is grep-able in logs. Behavior is preserved (LWW still wins, no throw); the warning is the new signal. Four tests added to `storyArc.test.js` cover the warn, the unique no-warn baseline, the multi-id collision listing, and the same-id-3+-times listing (deduped via Set).
+- **[med-migration-scripts-migrations-014-attribute] Migration 014 no longer writes `'unknown'` as a phantom annotation author.** On a fresh install, the migration runner used to fire before local-identity initialization, so legacy annotations got stamped with the literal string `'unknown'` — and from then on, those notes couldn't be re-saved or exported (the annotation pipeline refuses to write under `'unknown'`). The migration now lazy-creates the identity inline, and the annotation reader heals any pre-existing `'unknown'` bucket by re-keying it to the real local instance id.
-- **[med-migration-scripts-migrations-014-attribute] Migration 014 no longer writes `'unknown'` as a phantom annotation author.** When the migration runner fires before `ensureSelf()` on a fresh install (the order in `server/index.js` — migrations at startup, identity later), `instances.json` is absent and the old fallback `instances?.self?.instanceId || 'unknown'` stamped the literal string `'unknown'` into every legacy annotation entry forever (`setAnnotation` refuses to write under `'unknown'` and `annotationsSync.flushAll` refuses to export it, so those notes became unrecoverable / unexportable). `scripts/migrations/014-attribute-existing-annotations.js` now lazy-creates the local identity inline (same shape as `ensureSelf()` — `randomUUID()` + `os.hostname()`) and writes it to `data/instances.json` before reading. Read-side belt-and-suspenders: `mediaAnnotations.readAll()` heals any pre-existing `authors.unknown` bucket by re-keying it to the real `localInstanceId` (in-memory only; the first subsequent `setAnnotation` persists the clean shape via the normal write path). When a real local entry already exists alongside an unknown phantom, the real entry wins and the phantom is dropped. Tests in `scripts/migrations/014-attribute-existing-annotations.test.js` and `server/services/mediaAnnotations.test.js`.
+- **HF token banner no longer surfaces in Codex / External mode.** Picking a gated FLUX model and then switching the backend chip to Codex used to leave the "paste your HuggingFace token" banner stuck over the Codex form, even though Codex never touches HuggingFace. The gate now requires Local mode first.
-- **HF token banner no longer surfaces in Codex / External mode.** The `needsHfTokenGate` predicate in `client/src/pages/ImageGen.jsx` checked `currentModel?.requiresHfToken && !isFlux2Model` but forgot to also require `isLocalMode`. A user who'd selected a gated mflux model (e.g. FLUX.1-dev) and later switched the backend chip to Codex saw the "Flux 1 Dev is a gated model — paste your HF token" banner over the Codex form, even though Codex uses gpt-image-2 and never touches HuggingFace. The gate now requires `isLocalMode` first, matching the FLUX.2 install/status block right below it.
+- **[med-pipeline-server-services-pipeline-arcplanner] Arc-planner warns when an LLM emits duplicate season ids.** Two seasons sharing an id were silently dropped on persist (last-write-wins by id) while child issues kept their season pointers — leaving issues attached to the surviving season under the colliding id, which was rarely what an arc-resolve was supposed to do. A warning now flags the offending ids so the responsible run is grep-able. Behavior is preserved; the warning is the new signal.
-- **v2.1.0 review residue — small-fixes bundle (11 items).** Universe Builder render registration moves before the enqueue loop so the worker can't race past run registration and lose per-image emit coalescing; `seasonCoverSchema` gained `.passthrough()` so a full-series round-trip echoing server-built render fields no longer 400s; `volumePdf.js` sort now uses `arcPosition || number || id` with `?? Infinity` so null-arcPosition issues sink to the end instead of interleaving via the `number` fallback; series PATCH `console.warn`s when legacy `characters` / `settings` / `objects` are stripped so stale-tab POSTs are observable; `promptRunner.js` cwd guard now treats empty-string overrides as absent (matches `tuiPromptRunner`); `loops.js` no longer misclassifies an `onComplete({success:true})` throw as `iteration:error`; dead `|| series.characters` fallback removed from `textStages.js`; `migrateSeriesCanon.js` defers the orphan-series universe-link write until after the canon patch lands so a crash window doesn't leave the series stripped + universe empty; importer warns when arc-extract returns empty `summary` + `logline` before falling back to a synthetic value; `ansiStrip.js` adds a `\x1B(?![@-_\[\]])` second-pass strip so chunks like `\x1B\x1B[31m` no longer leak an orphan escape byte.
+- **v2.1.0 review residue — small-fixes bundle.** Eleven small fixes batched: Universe Builder render registration moves before the enqueue loop so the worker can't race past run registration; volume PDF sort puts null-arcPosition issues at the end instead of interleaving via the number fallback; series PATCH warns when legacy canon fields are stripped so stale-tab POSTs are observable; prompt runner cwd guard treats empty-string overrides as absent; loop runner no longer misclassifies a successful `onComplete` throw as `iteration:error`; sharing migration defers the orphan-series universe-link write until after the canon patch lands so a crash window can't leave the series stripped and the universe empty; importer warns when arc-extract returns empty summary + logline before falling back; ANSI stripper handles `\x1B\x1B[31m`-style chunks that previously leaked an orphan escape byte.
-- **Sharing/annotation-merge hardening — 5 v2.1.0 residue items.** Outgoing annotation manifests now honor per-bucket `displayNameOverride` (previously all buckets got the global name); peer payloads with missing/invalid `updatedAt` are dropped on import instead of winning LWW via a `now`-fallback; future-skewed peer timestamps are clamped to local-now to stop one bad clock from ratcheting every subsequent merge; `peerInstanceId === 'unknown'` (or empty) is refused on import to match the existing outgoing-path guard; and `exportAnnotationsToBucket` now skips both the asset-dir scan AND the record write when local has no annotations and no prior record exists, so a fresh-install annotation edit doesn't fan an empty manifest into every auto-merge bucket.
+- **Sharing / annotation-merge hardening.** Five sharing fixes: outgoing annotation manifests honor per-bucket display-name overrides (previously all buckets got the global name); peer payloads with missing or invalid timestamps are dropped on import instead of winning last-write-wins via a `now` fallback; future-skewed peer timestamps are clamped to local-now so one bad clock can't ratchet every subsequent merge; peer payloads with an unknown instance id are refused on import to match the outgoing-path guard; and exporting annotations to a bucket no longer writes an empty manifest into every auto-merge bucket on a fresh install with no annotations.
## Removed
-- **[route-medialightbox-settings-drawer-through] Stale PLAN item removed** — the media lightbox's settings panel is no longer a drawer, so there is no drawer migration left to track.
-
-- **`CODEX5.5_REVIEW.md`** at repo root — obsolete now that the concrete bugs are shipped and the strategic items are tracked in PLAN.md.
+- **`CODEX5.5_REVIEW.md`** at the repo root — the concrete bugs from that review have all shipped, and the strategic items live in PLAN.md.
diff --git a/.claude/commands/claim.md b/.claude/commands/claim.md
index ddefe9af48..ece54d9af4 100644
--- a/.claude/commands/claim.md
+++ b/.claude/commands/claim.md
@@ -103,12 +103,14 @@ Use `feat:` / `fix:` / `refactor:` / `chore:` / etc. per conventional commit pre
**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. **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:
+2. **Add an entry to `.changelog/NEXT.md`** capturing what shipped. **Read `.changelog/README.md`'s "Style Rules" section first and follow it** — these entries become public release notes, not a developer journal. Do NOT mirror the prose style of existing dev-heavy entries in `NEXT.md`; many predate the style rules. 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>
+ - **[<slug>] <Short, user-facing title>** — <one sentence on the user-visible effect, two if a meaningful "why" needs to land>
```
+ **Write for a user of the app, not for a coder inside it.** No file paths, no module names, no function/class names, no route paths, no test counts ("85/85 tests pass"), no internal data shapes, no "Touched:" footers, no line numbers. If the change has no user-visible effect (internal refactor, test-only addition, dependency cleanup), keep the entry to one terse sentence under **Changed** describing the maintenance value — don't pad with implementation detail.
+
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 .changelog/NEXT.md`) and commit: