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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
docs: replan — migrate 18 PLAN.md items to plan-labeled issues #1318-#1335; empty PLAN.md
[._.]/ Adam Eivy4836056086d1
diff --git a/GOALS.md b/GOALS.mdindex 1f7b86e1db..087b27d5d0 100644--- a/GOALS.md+++ b/GOALS.md@@ -85,7 +85,10 @@ PortOS is built for Adam Eivy — a single developer managing active git repos,## Current State-See [PLAN.md](./PLAN.md) for detailed milestone tracking and roadmap.+The active roadmap lives in the GitHub issue tracker — open issues labeled+[`plan`](https://github.com/atomantic/PortOS/issues?q=is%3Aissue+is%3Aopen+label%3Aplan)+(claimable) and [`future`](https://github.com/atomantic/PortOS/issues?q=is%3Aissue+is%3Aopen+label%3Afuture)+(parked ideas). See [PLAN.md](./PLAN.md) for the pointer.| Goal | Status | Notes ||------|--------|-------|diff --git a/PLAN.md b/PLAN.mdindex cd8dbc85d2..e2157602a7 100644--- a/PLAN.md+++ b/PLAN.md@@ -15,49 +15,3 @@ This file no longer tracks individual tasks (so it stops generating mergeconflicts as work proceeds). Speculative ideas now live as `future`-labeledissues rather than a list here, so they can each be promoted, refined, or closedindependently.--## Next Up--<!-- reference-watch proposals: slug-tagged, picked up by /claim later -->--- [ ] [brain-memory-delete-hard-prune-vector] **Hard-delete the mapped pgvector row when a brain memory is deleted by the user (vs a peer-sync tombstone), instead of soft-archiving it forever.** Surfaced 2026-06-14 while wiring ChatGPT-import embeddings. Deleting a brain memory emits `{type}:deleted` → the bridge's `archiveMappedMemory` does `UPDATE memories SET status='archived'` (`brainMemoryBridge.js:373`). That correctly hides it from search (search filters `status='active'`), but the row + its 768-dim embedding **stay in Postgres forever** — nothing ever hard-prunes bridge-archived rows (`memoryDB.deleteMemory(id, hard=true)` exists but the bridge never calls it). For a 1482-record ChatGPT import that's later cleared, that's ~1482 dead vectors lingering. Fix: distinguish a **real local delete** (user action via `remove()` → genuine tombstone) from a **sync-driven archive** (peer delete, recoverable — must stay soft so resurrection works, see the reactivation path at `brainMemoryBridge.js:~193`). On a real local delete, hard-`DELETE` the mapped memory row + drop its bridge-map entry; keep soft-archive for the sync path. The signal is available: `handleEntityDeleted`/`resyncBrainRecord` know whether they're handling a local `:deleted` event vs a `sync:applied` resync. Add a test asserting a local delete removes the row (not just archives) while a synced delete still soft-archives. Note: the `*.db.test.js` real-Postgres guard applies. Estimated scope: small-medium.--- [ ] [media-jobs-survive-pm2-server-restart] **Isolate long media-job subprocesses (LoRA training, video gen) from pm2's restart SIGINT via spawn-side double-fork.** Surfaced 2026-06-14: a 9B LoRA training run died repeatedly with `SIGINT`/`KeyboardInterrupt` at the exact second of a `pm2 restart portos-server`. Root cause: pm2's `TreeKill.js` does `ps -e -o pid=,ppid=` and walks the **parent→child tree**, SIGINT-ing every descendant on restart/stop — and portos-server restarts routinely (was a hardcoded `max_memory_restart: 2G`, now raised + `PORTOS_SERVER_MAX_MEMORY`-configurable, default 4G). `detached: true` does NOT help (TreeKill keys on ppid, not process group); `treekill: false` on the app does NOT work either (pm2 then fails to reap the old node process → it lingers on :5555 → new instance EADDRINUSE crash-loops — tried and reverted). The correct fix is spawn-side: **double-fork the trainer/video-gen child so it reparents to launchd/init (ppid=1) and leaves pm2's tree**, while still streaming stdout for progress (e.g. an intermediate `setsid` launcher that pipes through a fifo/file the parent tails, or a tiny detached supervisor). Apply to BOTH `server/services/loraTraining/index.js:~501` AND `server/services/videoGen/local.js:~918` (same vulnerability). Validate: note the child pid, `pm2 restart portos-server`, confirm the SAME pid keeps running and the job completes. Until then, the raised memory ceiling minimizes restarts and checkpoint-resume recovers any that slip through. Estimated scope: medium.--- [ ] [lora-training-caption-strips-invariant-identity] **Character-LoRA captions must NOT describe invariant identity — warn/strip it, or the trigger token never learns the character.** Surfaced 2026-06-14 training Freydis (dataset `90043893`). The first 4B LoRA (run `d36562a0`) rendered a generic auburn-haired woman from the bare trigger `freydis_of_quaervarr portrait`, but rendered Freydis *correctly* when the full identity description was in the prompt — proving her identity (white hair, circlet, tooth necklace, leather armor) got bound to the caption PHRASES, not the trigger token. Every one of the 25 captions repeated her invariant features. Fix path that worked: rewrite captions to keep only the trigger + what VARIES (pose, framing, weapon, setting, style) and drop invariant identity, so the trigger absorbs it (retrain ~35 min). **Caption source matters:** Freydis's images were `source: upload` with `captionSource: manual` — i.e. **Codex authored the captions externally (from the character canon/lore — hence "Northwind Cairnblade") and they were submitted through PortOS's manual-caption path** (`loraDatasets.js:393`), NOT produced by PortOS's vision auto-captioner. Codex described *the character* (identity-first), which is backwards for trigger-binding. The root fix is the external Codex prompt that authors these captions (it must follow the character-LoRA recipe: describe only what varies); PortOS's role is a safety net (lint/strip) since it can't control external caption authors. Product improvements: (a) PortOS's own auto-captioner (`server/services/loraDatasetCaption.js`) already says "do not mention the character's name" and scopes to pose/clothing/accessories — that path is fine; the canon-generation path is the offender; (b) add a caption-lint/warn in the dataset workbench that flags when the SAME descriptive fragment (hair/eyes/skin/signature items) appears across most captions — that's identity that should move to the trigger; (c) optionally offer a one-click "strip shared identity fragments" that diffs captions and removes the common invariant block (the manual rewrite done for Freydis, generalized); (d) document the character-LoRA caption recipe in the workbench UI ("describe what changes shot-to-shot, not who she is"). Estimated scope: medium.--- [ ] [lora-training-default-base-tier-too-heavy] **Reconsider the LoRA-training memory tier + default steps — unquantized 9B is ~25× slower than 4B on a 128GB box for a character LoRA.** Surfaced 2026-06-14 training Freydis (dataset `90043893`). `deriveMfluxMemoryConfig` (`server/services/loraTraining/runtimes.js`) maps ≥96GB → `{quantize:null}` (full bf16). On the M5 Max 128GB, a `flux2-klein-9b` bf16 run at 768px/600 steps **failed to complete a single real training step in 14 min** (the 32GB base materialized for the fused `value_and_grad` forward+backward hits memory/swap pressure), whereas `flux2-klein-4b` ran steady at **~3.5s/step → ~35min total** (run `d36562a0`). The base-model size dominated; `TRAINING_DEFAULTS.steps` 600→400 was minor. Proposed: (a) for single-character LoRAs default to the 4B base (or 9B-8bit) rather than unquantized 9B even when RAM allows it — speed/fidelity tradeoff strongly favors the lighter base; (b) revisit `TRAINING_DEFAULTS.steps` (600 may be 1.5-2× more than needed for 25-image faces — the checkpoint picker lets the user grab an earlier checkpoint); (c) re-measure whether `low_ram:true` is still warranted on a 128GB box once the base is lighter (the in-RAM-cache rejection was decided during the swap-thrash that coincided with the panics). Expose base-quant/low_ram as request params (currently only steps/rank/lr/resolution/checkpointEvery/sampleEvery are in `loraTrainingParamsSchema`) so a run can opt into a heavier base without a code change. Validate fidelity: confirm a 4B Freydis LoRA is acceptable before changing the default. Estimated scope: medium.--- [ ] [lora-dataset-object-place-variation-chips] **Let the generate-batch dialog tune object/place variation axes — surface the kind axes so the "Lighting"/"Settings" chips actually render.** Deferred from PR #1267 review (claude, 2026-06-14): the object/place LoRA feature is functional (server-side `deriveVariationAxes` applies kind-appropriate lighting/setting defaults in `generateDatasetImages`), but `LoraDatasetDetail.jsx`'s `expressionOptions`/`outfitOptions` are hard-coded to `[]` for non-character kinds (`client/src/pages/LoraDatasetDetail.jsx:~355`), so `GenerateBatchDialog`'s `expressionOptions.length > 0` / `outfitOptions.length > 0` guards are always false and the per-kind relabeled chip lists ("Lighting"/"Settings", added in `GenerateBatchDialog.jsx`) never render — users can't override the object/place axes, only the server defaults are ever used, and the relabel logic is currently dead for non-characters. Fix: have the dataset/subject payload carry the kind axes (or expose `deriveVariationAxes` output via the dataset detail endpoint) so the client can seed `expressionOptions`/`outfitOptions` from the server vocab instead of mirroring it client-side (avoid duplicating the server axis vocab in the client — that's the cross-module-constants-by-copy anti-pattern). Then the "Lighting"/"Settings" chip lists render and overrides flow through the existing `views`/`expressions`/`outfits` generate params. Estimated scope: small.--- [ ] [lora-checkpoint-picker-dedupe-and-hide-untrained-step0] **LoRA checkpoint picker: dedupe by step and don't offer the untrained step-0 checkpoint as deployable.** Surfaced 2026-06-14 from run `90043893` showing 3 checkpoint cards all at "step 0" with identical previews. Two real bugs in `server/services/loraTraining/checkpoints.js#listRunCheckpoints` (NOT caused by the segmentation PR — pre-existing): (1) mflux saves a `0000000_checkpoint.zip` from its `num_iterations==0` monitoring block (the *untrained* initial adapter, identical base-model preview every time) and `listRunCheckpoints` lists it as a deployable "Use this" option — deploying it is a no-op; filter step 0 out of the deployable list (or clearly mark it non-deployable), since the LoRA has zero training at step 0. (2) `run.artifacts.checkpoints` accumulates duplicate entries across MANUAL resume attempts — each resume is a fresh job/wrapper/watcher with an empty `seen` set, so it re-emits the already-existing checkpoint(s), and `listRunCheckpoints` does no dedup → N identical cards. Dedupe by `step` (keep the entry with a non-null loss / latest). Add field-level tests on `listRunCheckpoints` output (dedup + step-0 exclusion). Note: the new segmented-training path does NOT add duplicates (one watcher with a persistent `seen` set spans all segments), so this is purely a manual-resume + step-0 artifact. Estimated scope: small.--- [ ] [ref-watch-phosphene-model-weights-integrity-repair] **Verify downloaded model weights (header/size + optional checksum) and offer one-click Repair.** From `reference-watch` review of Phosphene (commits `173d2fd5` + `80752a70`, 2026-06-12). Upstream proved that corrupt/partial safetensors (right size, *wrong bytes*) silently decode to garbled "mosaic" video output that a clean re-download fixes — a leading non-Metal cause of bad renders that hits some machines and not others, so it's cross-platform-relevant for PortOS (mac and windows). PortOS currently only sums file sizes: `server/lib/hfCache.js#inspectModelCache()` returns `{ cached, sizeBytes }` with no integrity check. Fix: add a `verifyModelCache(repoId)` to `server/lib/hfCache.js` that does a cheap structural check first (read each safetensors header length prefix and confirm the file is at least header+declared-tensor-bytes long — catches truncation without loading tensors), and an optional deep check that hashes each weight and compares against HuggingFace's published LFS sha256 (from the repo's `git lfs` pointer / `/api/models/<repo>` metadata). Surface results on `GET /api/video-gen/status` (and the imageGen status it mirrors) as a `modelIntegrity` field, add `POST /api/video-gen/models/verify` (force re-scan, threaded/on-demand) and `POST /api/video-gen/models/repair` (delete flagged files + re-download via the existing resumable HF fetch path), and show a dismissible "Repair model" banner in `client/src/pages/VideoGen.jsx` when integrity reports bad/missing files. Estimated scope: large.--- [ ] [ref-watch-phosphene-runtime-fingerprint-in-status] **Surface the video runtime fingerprint (ltx-2-mlx version, MLX/Metal version, chip, OS) in video-gen status + render logs.** From `reference-watch` review of Phosphene (commits `b069e2d2` P2 + `093a9f05`, 2026-06-12). Upstream found that garbled/"mosaic" output is often a per-chip/per-runtime numerical bug, not a crash, and healthy bug reports carried no version info — so it now logs a one-line runtime fingerprint and exposes `ltx_version`/`mlx_version`/`chip`/`os` on `/status`. PortOS already resolves BYOV runtimes (`server/services/videoGen/local.js#BYOV_RUNTIME_INFO`) but `GET /api/video-gen/status` (`server/routes/videoGen.js:180`) does not report the resolved interpreter/package versions. Fix: have `generate_ltx2.py` (and the wan22/hunyuan/win helpers) emit a single `runtime | ...` fingerprint line at startup (importlib.metadata version of the runtime package + platform/processor on mac, torch+CUDA on windows), capture it in `local.js`, persist it onto the render job/history record so each render log self-documents its environment, and add a `runtime` block to the `/status` payload for the client to show. Estimated scope: medium.--- [ ] [ref-watch-phosphene-i2v-snap-dims-to-source-aspect] **Auto-snap I2V default width×height to the uploaded source image's aspect ratio.** From `reference-watch` review of Phosphene (commit `0b98a5bd`, 2026-06-12). Upstream keeps custom W×H inputs editable for image flows but auto-snaps the *default* dimensions to the uploaded image via `snapAspectToImage()`, because the common case can't cover-crop a 16:9 photo into a 9:16 frame without losing content. PortOS already exposes editable W×H plus presets, but on I2V it ffmpeg cover-crops the source to the chosen size (`server/services/videoGen/local.js#resizeImage()` uses `force_original_aspect_ratio=increase,crop`), so a mismatched preset silently crops away the subject. Fix: when a source/keyframe image is selected in `client/src/pages/VideoGen.jsx`, read its natural dimensions and snap the width/height fields to the nearest 64-aligned preset that matches the image's aspect ratio (only when the user hasn't manually overridden), leaving the inputs editable for power users; keep the existing server-side 64-grid clamp. Estimated scope: small.--- [x] [authors-federation-sync-category] **Federate the `authors` table across peers.** SHIPPED via the **per-record peer-push** path (mirroring `mediaCollection`) rather than the 60s dataSync snapshot-category route originally sketched here — authors are low-churn standalone records with no `ephemeral` concept, so per-record push + auto-subscribe-on-create + backfill-on-toggle/peer:online converges them without the snapshot checksum-stability machinery. Delivered: `author` case in `server/lib/syncWire.js`; `authors:1` wire version + `RECORD_KIND_SCHEMA_CATEGORIES.author` in `schemaVersions.js`; `mergeAuthorsFromSync`/`pruneTombstonedAuthors`/`listAuthorIds`/`getAuthor({includeDeleted})` across `authors/{logic,db,file,index}.js` (shared `mergeAuthorRecord` LWW decision so both backends can't drift); recordEvents emit + `autoSubscribeRecordToAllPeers` on create/update/delete via the dispatcher; `author` branches in `peerSync.js` (push payload with headshot asset manifest, merge dispatch, relevantCategories gate, classifyLocalRecord, backfill lister, integrity manifest); conflict-journal `RESTORABLE_FIELDS.author` + base-hash seeding; `authors` sync category in `instances.js` defaults + `routes/instances.js` validation + `Instances.jsx` toggle (non-snapshot, like catalog); tombstone-GC author cutoff/prune/refused; `authors/db.test.js` data-safety round-trip (snapshot/restore + test-DB gate) + merge/prune tests, `logic.test.js` merge/headshot tests, `syncWire.test.js` author case.--- [ ] [authors-headshot-upload-asset-sync] **Make uploaded (non-gallery) author headshots transfer their bytes to peers.** The authors federation (above) syncs the headshot IMAGE BYTES only when `headshotImageUrl` points at `/data/images/<f>` (gallery-picked) — `headshotImageFilename()` in `authors/logic.js` maps that to an `image` asset the peer-sync pull worker fetches. But the Authors page's *upload* button (`client/src/pages/Authors.jsx` → `POST /api/uploads`) stores the file in `data/uploads/` and sets `headshotImageUrl = /api/uploads/<f>`, which is NOT one of the three pullable asset kinds (`image`→`/data/images`, `image-ref`, `video`), so on a peer the author record syncs but the headshot 404s. Two options: (a) route author-headshot uploads through the gallery (`/data/images/`) so they ride the existing `image` pull path (smaller change, recommended), or (b) add an `upload`/`/data/uploads` pullable asset kind end-to-end — new `ASSET_KIND_TO_URL_PREFIX` entry + `directoryForAssetKind` + `PATHS.uploads` + the `peerAssetManifestEntrySchema` kind enum in `peerSyncValidation.js`. External `http(s)`/`data:` URLs intentionally never transfer (the receiver resolves them itself). Estimated scope: small (a) / medium (b).--- [ ] [peer-sync-unknown-kind-as-schema-block] **Treat a pre-feature peer's generic 400 rejection of a brand-new record `kind` as a schema-version block (not a bare `http-400` retry).** From codex review of the authors-federation PR (#1263). `pushRecordToPeer`'s schema-block / SchemaGapBadge pause path keys on a **409 `SCHEMA_VERSION_AHEAD`** from `applyIncomingPush`'s version gate. But when a NEW record kind is introduced (authors now; `mediaCollection` had the same gap when it landed), a peer running an older PortOS whose `peerSyncPushSchema` discriminated union doesn't include that `kind` rejects the push at **Zod validation with a generic 400** — *before* `applyIncomingPush` (and its gate) ever runs. So the sub retries as a plain `http-400` and the UI never surfaces "peer needs to update PortOS." This is benign under the trust model (the push lands once the peer upgrades; no corruption), which is why it's deferred — but the proper fix is cross-cutting version-negotiation work that applies to EVERY kind, not just authors: in `pushRecordToPeer`, detect a 400 whose body indicates an unrecognized `kind` discriminator (mirror the existing `portosMeta`/`catalogBundle` 400-retry detection block) and route it into `persistSchemaVersionBlock` with an empty-gap/`peer-pre-feature` marker so the SchemaGapBadge shows and the edit-push cooldown engages, OR preflight the peer's advertised `schemaVersions`/capabilities before creating the sub. Needs its own tests for the unknown-kind-400 classification. Estimated scope: medium (cross-cutting peer-sync negotiation + tests).-- [ ] [lora-training-version-bisect-and-pin-validated-trio] **Bisect the mflux/mlx/mlx-metal stack on the M5 and pin a validated trio that survives a full LoRA run.** From `reference-watch` review of Phosphene (2026-06-14, `docs/plans/2026-06-14-lora-watchdog-phosphene-review.md`). The three macOS GPU watchdog kernel panics (`docs/research/2026-06-13-mflux-training-watchdog-panic.md`) all happen on the currently-installed stack: **mflux 0.17.5 · mlx 0.30.6 · mlx-metal 0.30.6 · mlx-lm 0.29.1**. PortOS installs `mflux>=0.17` (a floor) and lets pip resolve mlx under mflux's `mlx<0.32` constraint (`scripts/setup-image-video.sh`), so the stack can drift silently. Phosphene's discipline is to pin a *validated trio* ("every pin is a paid lesson") — but pinning to the *current* versions would lock in the known-bad set, so this is a **bisect, not a blind pin**: on the M5, try mlx/mlx-metal 0.30.6 ↔ 0.31.x (and a newer mflux if `mlx<0.32` is relaxed), run a full training to completion under each, find a trio that survives, then pin it in `setup-image-video.sh` with a comment recording the test that proved it. Also: emit a one-line runtime fingerprint (`mflux`/`mlx`/`mlx-metal` version + Apple chip + macOS) at trainer startup in `train_mflux_lora.py` so each run log + future paniclog self-documents its exact stack (mirrors the video-gen `ref-watch-phosphene-runtime-fingerprint-in-status` item). File an upstream mflux/MLX issue with the three paniclogs + the fingerprint. **Ready to run:** confirmed the dev box IS the panicking M5 Max (`Mac17,7`/`T6050`, macOS 26.5.1, no OS update available); telemetry now armed; a one-command bisect harness (reuses run `15cfeed1…`, bf16, segmentation OFF) + upstream-issue draft are in `docs/plans/2026-06-14-lora-watchdog-phosphene-review.md` + `docs/research/2026-06-14-upstream-issue-draft-m5-watchdog.md`. **Gated only on:** each failing candidate hard-reboots the box, so run when free to lose the session (not mid-other-work). Estimated scope: medium (mostly bench time).--- [ ] [lora-training-phase-aware-soft-hang-stall-watchdog] **Phase-aware stall watchdog that SIGKILLs a wedged-but-not-rebooted mflux child and auto-resumes from the newest checkpoint.** From `reference-watch` review of Phosphene (2026-06-14). Phosphene proved an in-process daemon-thread watchdog can't fire during a Metal hang (the completion-handler dealloc chain holds the GIL — `docs/STATE.md:436`); the rescue must be out-of-process. PortOS's Node orchestrator is already out-of-process but its training idle watchdog is 30 min (`WATCHDOG_TRAINING_MS`). Add a **phase-aware** stall detector keyed off the wrapper's existing stage lines (`STAGE:load-model`, `STAGE:training`, `STEP:n:m:loss`, `STAGE:cooldown:heartbeat`): a tight budget during `STAGE:training` (consecutive `STEP:` lines should arrive within a few × the observed per-step time), and a generous/disabled budget during model load, dataset encode, preview generation, and cooldown — then SIGKILL + auto-resume from the newest checkpoint via the existing `--resume-checkpoint` path. **Important caveat / scope:** this does NOT address the observed *hard-reboot* kernel panics (the machine is gone before any userspace watchdog runs — checkpoint-resume already covers that); it only recovers *soft* GPU hangs faster, so it's defensive hygiene, not a fix for the incident. Must avoid false-killing a legitimately slow load/encode (derive the training budget from the first few observed step intervals, not a hardcoded 45s). Unit-test by feeding synthetic line streams. Estimated scope: medium.---- [ ] [chatgpt-import-stream-assets-to-disk] **Stream ChatGPT-export `.dat` assets directly to disk instead of buffering them all in memory.** From claude review of the ChatGPT-ZIP-import PR (#1264). `extractChatgptZip` (`server/services/chatgptZipImport.js`) buffers every `.dat` asset into `pendingAssets` (a `Map<assetId, {buffer}>`) and holds them until the ZIP stream closes, then resolves extensions + writes them in a second loop — because the `conversation_asset_file_names.json` map can arrive *after* the `.dat` members, so the friendly-name fallback isn't known per-asset mid-stream. Peak RAM ≈ sum of all asset bytes; an aggregate `MAX_TOTAL_BUFFERED_BYTES` (1 GB) guard now fails fast rather than OOMing, but a legitimately large export (the route allows up to 2 GB) would be rejected. Proper fix: write each asset to a temp/served path as it streams (sniff the extension from the first chunk, which is enough for all current magic-byte types), recording `{assetId → tempPath}`; after the stream closes, rename/finalize using the now-complete name map (extension is already known from the sniff; the friendly NAME is metadata only, not part of the served filename). This removes the aggregate ceiling and bounds peak RAM to one chunk. Keep the magic-byte sniff (the `.dat` files have no extension). Estimated scope: medium.--- [ ] [lora-trainer-reattach-detached-child-on-boot] **Re-attach (or explicitly resume) a detached LoRA trainer that outlived a hard server restart instead of marking the run failed while its child still runs.** From claude review of the v2.21.0 release (PR #1270). `server/services/loraTraining/index.js` spawns the trainer with `detached: true` so a pm2 *group* SIGINT can't kill it mid-run — good. But if pm2 kills the server *process* (not just the group), the detached child keeps training while boot reconcile (`initLoraTraining`/`initMediaJobQueue`) marks the run `failed`; nothing reaps the child's `RESULT:` line, so a run that finishes post-restart registers no LoRA and silently discards hours of GPU work. Fix: on boot, probe whether the recorded child PID is still alive (`process.kill(pid, 0)`); if so, re-attach to its output (or at minimum leave the run `running` and let the existing checkpoint-resume path pick it up) rather than force-failing it. Edge-case (requires a process kill, not the common group SIGINT) but high cost when it hits. Estimated scope: medium.--- [ ] [db-write-guard-broaden-cte-copy-merge] **Broaden the test-DB row-write guard to catch data-modifying CTEs, COPY, MERGE, and multi-statement writes.** From claude review of the v2.21.0 release (PR #1270). `server/lib/db.js`'s row-write backstop (the hard defense against the 2026-06-13 data-loss class) is `^`-anchored on `INSERT|UPDATE|DELETE|TRUNCATE`, so `WITH … DELETE …`, `COPY … FROM`, `MERGE INTO`, and `SELECT 1; DELETE …` slip past it. Verified that no current store uses those forms, so it is **latent, not exploitable today** — but the guard is billed as the absolute backstop, so it should match those verbs anywhere after stripping a leading comment block. Add matching cases to `server/lib/db.guards.test.js` pinning the intent. Estimated scope: small.--- [ ] [videogen-close-handler-wrap-unhandled-rejection] **Wrap the `videoGen/local.js` child-process `close` handler so a `finalizeGeneratedVideo()` throw can't leak as an unhandled rejection (job stuck `running`).** From claude review of the v2.21.0 release (PR #1270); pre-existing, not introduced by the PR, but new LoRA-fused renders now flow through it. `server/services/videoGen/local.js` (~lines 1041, 1096) does `proc.on('close', async () => { … await finalizeGeneratedVideo() … })` with no try/catch; a throw there is an unhandled rejection (process-killing on Node ≥15 per the `nodejs-async-event-listener-unhandled-rejection` skill) that leaves the media job wedged `running` with no terminal SSE. Fix: wrap the handler body in try/catch and route failures through the job's `failed`/error finalizer + emoji-prefixed `console.error`. Estimated scope: small.--### Trigger-gated (waiting for a precondition)--- [ ] [ref-watch-phosphene-spaced-lora-id-decode-validate] **Harden trained-character/LoRA id handling for spaced filenames + percent-encoded path segments.** From `reference-watch` review of Phosphene (commit `ce031395`, 2026-06-12). Upstream's character-id validation regex was a hard gate that ran *before* the sidecar was read, so a LoRA whose trigger/filename contained a space (e.g. `Annie Phosphene_v2.safetensors`) was misclassified as style-only and vanished from the Characters tab; the fix widened the id class to allow spaces and made the route `unquote()`-then-validate (staying traversal-safe because an encoded `../` or `/` decodes to chars the class still rejects). PortOS's equivalent is `server/services/loras.js#assertSafeLoraFilename()` plus the trained-LoRA `character` classification it surfaces. Fix (if applicable): audit whether any PortOS LoRA/character id route 404s or misclassifies spaced filenames and whether percent-encoded id segments are decoded before validation; if so, widen the allowed id class to permit spaces and decode-then-validate in the route. **Decision needed:** confirm PortOS actually exposes id-addressed character/LoRA routes (not just filename-addressed ones) and reproduces the spaced-name misclassification before investing — it may already be covered by `assertSafeLoraFilename`'s filename-only model. Estimated scope: small.--- [ ] [importer-ai-reformat-prose-excerpts] **Reuse the manuscript AI-reformat at import time to clean seeded prose excerpts.** The importer (`server/services/importer.js`, commit path ~line 1320) seeds `proposal.proseExcerpt` **verbatim** into `stages[seedStageFor(contentType)].output` — which is exactly the PDF-mangled text that needs the new `reformatManuscriptText()` (`server/services/pipeline/manuscriptFix.js`, already exported for this purpose). Wire it in so imported manuscripts arrive already-clean instead of needing a per-section Reformat pass afterward. **Design to settle first:** (a) opt-in — a "Clean up formatting with AI" checkbox in the import Review UI, default off — because reformatting is one LLM call per issue and a large import (20+ issues) would add minutes to commit; (b) best-effort — on reformat failure OR the integrity-guard 400, fall back to the verbatim excerpt so import never breaks; (c) emit importer progress events per reformatted issue; (d) gate to prose-like content types (route comic-script/screenplay through too, since `reformatManuscriptText` already takes a stageId). Estimated scope: medium.