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

fix v2.1.0 review residue — 11 small isolated fixes bundle

[._.]/ Adam Eivy322f1f20085a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fc567bf425..c0ad797eed 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,8 @@
## Fixed
+- **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.
+
- **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.
## Removed
diff --git a/DONE.md b/DONE.md
index e312706fbb..b03268faf6 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-19
+- **[med-universe-builder-server-routes-universebuilder] [med-pipeline-server-routes-pipeline-js-145-149] [med-pipeline-server-services-pipeline-volumepdf-js] [med-pipeline-server-services-pipeline] [med-canon-server-services-pipeline-series-js-210] [low-ai-dispatch-server-lib-promptrunner-js-146] [low-ai-dispatch-server-services-loops-js-181-fire] [low-canon-server-services-pipeline-textstages-js] [low-canon-server-services-pipeline] [low-importer-server-services-importer-js-444-446] [low-ai-dispatch-server-lib-ansistrip-js-14-pattern] v2.1.0 pre-release review residue — small isolated fixes bundle.** Eleven items from the v2.1.0 main→release multi-agent review shipped together because each is a 1–10 line isolated fix and most touch independent files. (1) `server/routes/universeBuilder.js` — `registerUniverseBuilderRun(...)` moved BEFORE the enqueue loop using `compiled.length` as the authoritative job count, so the worker can no longer pick up the first job and emit `completed` before the run is registered (which would lose the per-image emit coalescing the hook depends on). (2) `server/routes/pipeline.js` — `seasonCoverSchema` gained `.passthrough()` so a "save full series" round-trip echoing the server-built `proofImage` / `finalImage` render fields no longer 400s; matches the parent `seasonSchema`'s shape. (3) `server/services/pipeline/volumePdf.js` — issue sort in `assembleVolumePdf` now uses `(a.arcPosition ?? Infinity) - (b.arcPosition ?? Infinity) || (a.number ?? 0) - (b.number ?? 0) || a.id.localeCompare(b.id)`, sinking arcPosition-null items to the end instead of letting `number`-fallback interleave them with positioned ones. (4) `server/services/pipeline/seasonCoverFilenameHook.js` — verified the empty-patch short-circuit is already in `updateSeasonOnSeries` (`series.js:335-344` returns `cur` unchanged when `patchFn` returns `{}`); item archived as already-done. (5) `server/services/pipeline/series.js` — `updateSeries` emits `console.warn` when the incoming patch carries `characters` / `settings` / `objects` (post-B.4 those live on the universe), so a stale browser tab POSTing legacy canon is observable in logs instead of vanishing silently with 200 OK. (6) `server/lib/promptRunner.js` — `effectiveCwd` now uses `(typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd()` matching `tuiPromptRunner.js:103`'s pattern; an empty-string override no longer leaks through `??` to spawn(). (7) `server/services/loops.js` — `onComplete({success:true})` is wrapped in `Promise.resolve().then().catch()` so a throw in the success branch is no longer misclassified as iteration-failed by the trailing `.catch` and falsely emits `iteration:error`. (8) `server/services/pipeline/textStages.js` — dropped the dead `|| series.characters` middle clause from the canon-fallback (post-B.4 `series.characters` is always undefined). (9) `server/services/pipeline/migrateSeriesCanon.js` — orphan-series link write (`updateSeries({ universeId })`) is deferred until AFTER the universe canon patch lands; a crash between create-universe and patch-universe now leaves the legacy series fields intact for retry, instead of stripped + empty. (10) `server/services/importer.js` — emits `console.warn` when the arc-extract LLM returns empty `summary` AND empty `logline` (the synthetic fallback `${name} — ${type}` still fires; the warning makes the silent regression observable). (11) `server/lib/ansiStrip.js` — both the streaming stripper and the one-shot `stripAnsi` gained a `.replace(/\x1B(?![@-_\[\]])/g, '')` second pass so a chunk like `\x1B\x1B[31m` no longer leaks the leading orphan escape byte after the trailing CSI is consumed. All 5829 server tests pass.
- **[med-sharing-server-services-sharing] [med-sharing-server-services-mediaannotations-js-38] [low-sharing-server-services-mediaannotations-js] [low-sharing-server-services-mediaannotations-js-2] [low-sharing-server-services-sharing] Sharing/annotation-merge hardening bundle.** Five v2.1.0 pre-release residue items shipped together because they all touch the same annotation-sync + LWW-merge surface. (1) `annotationsSync.flushAll` no longer resolves one `sourceName` for all buckets — `exportAnnotationsToBucket` now resolves its own per-bucket name, so per-bucket `displayNameOverride` is honored in outgoing annotation manifest envelopes the same way it already was for series/universe/media manifests. The bucket-effective resolver lives in `sharing/annotationIdentity.js` as a new `resolveBucketSourceName(bucket)` export consumed by both the exporter and the annotation flush (the exporter's local copy in `sharing/exporter.js` was deleted in favor of the shared helper). (2) `mediaAnnotations.mergePeerAnnotations` now pre-rejects peer payloads with missing/invalid `updatedAt` before they reach `sanitizeAuthorEntry`'s `now`-fallback — previously a malformed peer record would always win LWW. The pre-check disambiguates "empty tombstone" (still applies as a delete) from "malformed payload" (now ignored entirely, instead of silently deleting the prior peer entry through the tombstone branch). (3) `sanitizeAuthorEntry` gained an opt-in `clampUpdatedAtTo` option used by the merge path so a peer whose clock is years ahead can't ratchet every subsequent LWW round on the same key — its `updatedAt` is clamped to local-now on import without disturbing reasonable timestamps. (4) `mergePeerAnnotations` rejects `peerInstanceId === 'unknown'` (and empty/non-string) on import — the outgoing path already guarded but a hand-crafted manifest or inconsistent peer could otherwise alias every record into the same "unknown" bucket and clobber each other on every merge. (5) `exportAnnotationsToBucket` now has a cheap early-out before `listBucketAssetKeys`: if local has zero annotations AND no prior record exists on disk for this `(bucket, instance)`, skip the manifest+asset-dir scan entirely (the common fresh-install fan-out case). A late-stage skip (both filtered AND prior empty) still covers the case where the bucket has assets but none overlap local. Coverage: 11 new vitest cases across `mediaAnnotations.test.js` (refuses `'unknown'` / empty peer id, drops missing+invalid updatedAt without nuking prior, clamps future-skewed peer ts) and new sibling `sharing/annotationsSync.test.js` (per-bucket displayNameOverride honored in record, cheap early-out skips `listManifestFilenames`, late skip when no local matches + no prior, asset-less bucket short-circuit, inbox-mode short-circuit, tombstone synthesis preserved for prior keys still in bucket). `/simplify` follow-up deferred to `[promote-unknown-instance-id-constant]` — promote the existing `UNKNOWN_INSTANCE_ID` constant from `importer.js` to a shared module + replace the bare `'unknown'` literal at the four remaining sites. All 5775 server tests pass.
- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.
- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.
diff --git a/PLAN.md b/PLAN.md
index fa95c25c2e..a6ebb35082 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -44,15 +44,10 @@ _Nothing currently parked — pick the next item from the Backlog._
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
-- [ ] [med-universe-builder-server-routes-universebuilder] **[MED][UNIVERSE-BUILDER]** `server/routes/universeBuilder.js:407-435` — `registerUniverseBuilderRun(...)` is called AFTER `await svc.recordRun(...)`; worker can pick up the first job and emit `completed` before registration, losing coalescing. Move `registerUniverseBuilderRun` before the enqueue loop.
- [ ] [med-migration-scripts-migrations-014-attribute] **[MED][MIGRATION]** `scripts/migrations/014-attribute-existing-annotations.js:43` — if migrations run before first server boot, `instances?.self?.instanceId || 'unknown'` writes the literal `'unknown'` as a phantom peer forever. Defer the migration to first server boot via `ensureSelf()`, or reconcile `unknown`→real id on read.
- [ ] [med-pipeline-server-services-pipeline-arcplanner] **[MED][PIPELINE]** `server/services/pipeline/arcPlanner.js:863-866` — `sanitizeSeasonList` dedupes by id (LWW); two LLM-emitted seasons with the same id silently drop one before persist while child issues stay attached to the still-present id. Add a duplicate-id detector that fails loud or warns.
- [ ] [med-pipeline-server-services-pipeline-arcplanner-2] **[MED][PIPELINE]** `server/services/pipeline/arcPlanner.js:929-942` — `buildSeasonRemap` Pass 3 (positional fallback) silently invents wrong mappings when the LLM structurally reshapes the arc. Log a warning when Pass 3 fires; consider only firing when unmatched count ≤ 1.
-- [ ] [med-pipeline-server-routes-pipeline-js-145-149] **[MED][PIPELINE]** `server/routes/pipeline.js:145-149` — `seasonCoverSchema` is strict but `seasonSchema` is `.passthrough()`. A future "save full series" round-trip with `cover.proofImage`/`finalImage` will 400. Add `.passthrough()` to `seasonCoverSchema`.
- [ ] [med-pipeline-server-routes-pipeline-js-1416-1452] **[MED][PIPELINE]** `server/routes/pipeline.js:1416, 1452, 470-472, 498-500` — cover render routes always overwrite `script` with the resolved value (treats absent vs empty-string identically). Only update `script` from render when the request body actually carried the field, OR drop script writes from render routes entirely (blur-save owns the field).
-- [ ] [med-pipeline-server-services-pipeline-volumepdf-js] **[MED][PIPELINE]** `server/services/pipeline/volumePdf.js:60` — `arcPosition`-only sort lacks a tiebreaker; null arcPosition with `number:5` sorts BEFORE `arcPosition:6, number:1`. Use `(a.arcPosition ?? Infinity) - (b.arcPosition ?? Infinity) || (a.number||0) - (b.number||0) || a.id.localeCompare(b.id)`.
-- [ ] [med-pipeline-server-services-pipeline] **[MED][PIPELINE]** `server/services/pipeline/seasonCoverFilenameHook.js:42` — returning `{}` from the patch callback still bumps `season.updatedAt` + triggers re-export. Add a no-op short-circuit mirroring `issues.js:601-603`.
-- [ ] [med-canon-server-services-pipeline-series-js-210] **[MED][CANON]** `server/services/pipeline/series.js:210` — series PATCH silently strips `characters/settings/objects` with zero logging. Stale browser tab POSTing legacy canon gets 200 OK and the canon vanishes. Emit `console.warn` once per request when legacy fields are stripped so the failure is observable.
- [ ] [med-sharing-server-services-sharing-version-js] **[MED][SHARING]** `server/services/sharing/version.js` — `SHARING_SCHEMA_VERSION` not bumped despite series-schema canon-field removal. Cross-peer share-bucket import from a pre-B.4 install silently loses series-side canon. Either bump the version (force refusal) or mirror migration logic in the importer for legacy canon fields.
- [ ] [med-ai-dispatch-server-services-aidetect-js-242] **[MED][AI-DISPATCH]** `server/services/aiDetect.js:242-250` — still has legacy `if (provider.type === 'cli') ... else if (api) ... else 'Unknown provider type'`. TUI providers fail on Settings → Detect App. Migrate to `runPromptThroughProvider`.
- [ ] [med-ai-dispatch-server-services-digital-twin] **[MED][AI-DISPATCH]** `server/services/digital-twin-helpers.js:56-130` — `callProviderAI` still has ad-hoc CLI/API split with TUI falling into the CLI branch (will hang or render banner into pipe). Migrate to `runPromptThroughProvider`.
@@ -62,12 +57,6 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [med-importer-server-routes-importer-test-js-no] **[MED][IMPORTER]** `server/routes/importer.test.js` — no test pins `ERR_PARTIAL_COMMIT_ISSUES → 207` status mapping. Future refactor that drops the entry from `SERVICE_ERROR_STATUS` would 500 on partial commits and trigger pager alerts (the in-code comment's stated regression).
- [ ] [med-importer-server-services-importer-test-js-no] **[MED][IMPORTER]** `server/services/importer.test.js` — no test exercises `existingCanonBlock` dedupe wiring. A regression that wires `null` would silently degrade second-pass imports. Assert `mockRunStagedLLM.mock.calls[0][1].existingCanonBlock` contains a seeded character name.
- [ ] [med-canon-server-services-canonusage-js-zero-test] **[MED][CANON]** `server/services/canonUsage.js` — zero test coverage for `getUniverseCanonUsage`. The "Appears-in sort: issueCount desc + alpha tiebreaker" invariant lives at line ~101 with no test. Add a `canonUsage.test.js`.
-- [ ] [low-ai-dispatch-server-lib-promptrunner-js-146] **[LOW][AI-DISPATCH]** `server/lib/promptRunner.js:146` — `effectiveCwd = cwdOverride ?? process.cwd()` doesn't catch empty string. Match `tuiPromptRunner.js:103`'s pattern: `(typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd()`.
-- [ ] [low-ai-dispatch-server-services-loops-js-181-fire] **[LOW][AI-DISPATCH]** `server/services/loops.js:181` — fire-and-forget `.then(...).catch(err => ...)` chain causes a throw in `onComplete({success:true})` to be misclassified as iteration-failed and emit `iteration:error`. Split into separate `.then` or wrap onComplete with its own catch.
-- [ ] [low-canon-server-services-pipeline-textstages-js] **[LOW][CANON]** `server/services/pipeline/textStages.js:156` — dead-code fallback `|| series.characters` (always `undefined` post-B.4). Drop the middle clause.
-- [ ] [low-canon-server-services-pipeline] **[LOW][CANON]** `server/services/pipeline/migrateSeriesCanon.js:61` — `updateSeries({ universeId })` writes mid-loop with the universe still empty. Crash between line 61 and the universe patch leaves series stripped + universe empty. Build the universe patch first, then write both.
-- [ ] [low-importer-server-services-importer-js-444-446] **[LOW][IMPORTER]** `server/services/importer.js:444-446` — `arcSummary = arcContent.summary || arcContent.logline || \`${name} — ${type}\``silently swallows a successful arc-extract that returned empty fields. Log a warning or surface`arcExtractFallback: true`.
-- [ ] [low-ai-dispatch-server-lib-ansistrip-js-14-pattern] **[LOW][AI-DISPATCH]** `server/lib/ansiStrip.js:14` — pattern doesn't strip lone `\x1B` bytes; chunk `\x1B\x1B[31m` leaks a raw escape. Add `.replace(/\x1B(?![@-_\[\]])/g, '')` second pass.
- [ ] [promote-unknown-instance-id-constant] **[LOW][SHARING]** Promote `UNKNOWN_INSTANCE_ID` from `server/services/sharing/importer.js:41` to a shared module (likely `server/services/instances.js`) and replace the bare string `'unknown'` literal at the four other sites that compare against it: `server/services/sharing/manifest.js` (multiple), `server/services/sharing/annotationsSync.js` (`flushAll` early-return), `server/services/mediaAnnotations.js` (`mergePeerAnnotations` peer-id guard), and `server/services/sharing/importer.js` (additional `manifest.producedByVersion || 'unknown'` etc.). Surfaced by /simplify during the sharing-merge-hardening bundle; deferred to keep that PR scoped to behavior fixes.
### Better-audit residue
diff --git a/server/lib/ansiStrip.js b/server/lib/ansiStrip.js
index 3b60b15e4c..8863683549 100644
--- a/server/lib/ansiStrip.js
+++ b/server/lib/ansiStrip.js
@@ -17,9 +17,18 @@ const INCOMPLETE_CSI = /^\x1B\[[0-?]*[ -/]*$/;
const INCOMPLETE_OSC = /^\x1B\][^\x07\x1B]*$/;
const INCOMPLETE_ESC_2BYTE = /^\x1B$/;
+// `[@-_]` (0x40-0x5F) is the byte range that legitimately follows an `\x1B`
+// in a complete sequence: covers `[` (0x5B) for CSI, `]` (0x5D) for OSC, plus
+// the single-byte escape forms (`\x1B@` ... `\x1B_`) caught by the main
+// pattern's first branch. The lookahead spares those starts so the main
+// pattern can match them on the current or next chunk.
+const STRIP = (s) => s
+ .replace(ANSI_PATTERN, '')
+ .replace(/\x1B(?![@-_])/g, '')
+ .replace(/\x00/g, '');
+
export function createStreamingAnsiStripper() {
let tail = '';
- const strip = (s) => s.replace(ANSI_PATTERN, '').replace(/\x00/g, '');
return (text) => {
const combined = tail + text;
tail = '';
@@ -35,10 +44,10 @@ export function createStreamingAnsiStripper() {
|| INCOMPLETE_CSI.test(candidate)
|| INCOMPLETE_OSC.test(candidate)) {
tail = candidate;
- return strip(combined.slice(0, lastEsc));
+ return STRIP(combined.slice(0, lastEsc));
}
}
- return strip(combined);
+ return STRIP(combined);
};
}
@@ -48,5 +57,5 @@ export function createStreamingAnsiStripper() {
*/
export function stripAnsi(text) {
if (typeof text !== 'string') return '';
- return text.replace(ANSI_PATTERN, '').replace(/\x00/g, '');
+ return STRIP(text);
}
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index fbbd21132f..5530ed6d5f 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -191,7 +191,10 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
// (extract the args-pinned model id rather than logging defaultModel).
let effectiveProvider = provider;
let effectiveModel = resolveEffectiveModel(effectiveProvider, model);
- const effectiveCwd = cwdOverride ?? process.cwd();
+ // `??` only catches null/undefined; an empty-string override would leak
+ // through to spawn() and resolve to `/`. Match tuiPromptRunner.js's
+ // string-truthy gate so an empty override falls back to process.cwd().
+ const effectiveCwd = (typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd();
// Some call sites (stageRunner, loops) create the run themselves so
// they can log the runId before the LLM call starts. When provided,
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 573d2d37d0..30a5e64343 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -144,13 +144,15 @@ const arcSchema = z.object({
// pre-split legacy fields. Render-slot details (`proofImage`, `finalImage`)
// arrive only from the render route's PATCH path, which builds them
// server-side; PATCHes of the season metadata only carry the user-editable
-// `script`. Explicit shape (not `.passthrough()`) so the "all inputs
-// validated" CLAUDE.md convention holds for new fields.
+// `script`. `.passthrough()` keeps the door open for a "save full series"
+// round-trip echoing back server-built render fields (proofImage /
+// finalImage) without 400'ing — the parent seasonSchema is already
+// passthrough for the same reason.
const seasonCoverSchema = z.object({
script: z.string().max(8000).optional(),
imageJobId: z.string().trim().max(200).nullable().optional(),
prompt: z.string().max(16_000).nullable().optional(),
-});
+}).passthrough();
const seasonSchema = z.object({
id: z.string().trim().min(1).max(64).optional(),
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index ae9f8f205a..7c6938a499 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -525,6 +525,12 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
// entryRef in `compiled` (the sanitizer mints ids on every write now, so
// legacy id-less records are the only gap).
const entryJobs = [];
+ // Register the run BEFORE enqueueing any jobs — the queue may dispatch and
+ // emit `completed` synchronously for the first job, and without prior
+ // registration the completion hook can't coalesce the run's
+ // emitRecordUpdated calls. `compiled.length` is the authoritative expected
+ // count (each compiled item produces exactly one job below).
+ registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: compiled.length });
for (const item of compiled) {
const params = {
...baseParams,
@@ -575,10 +581,6 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
createdAt: new Date().toISOString(),
});
- // Tell the completion hook how many jobs to expect so per-image
- // emitRecordUpdated calls can be coalesced into one re-export at run end.
- registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: jobIds.length });
-
console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);
res.json({
diff --git a/server/services/importer.js b/server/services/importer.js
index d900f7bac4..ba398410a3 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -491,6 +491,13 @@ export async function analyzeImport({
const arcContent = (typeof arcRun.content === 'object' && arcRun.content !== null)
? arcRun.content
: {};
+ // Warn when the LLM returned a structurally-successful arc with empty
+ // summary AND empty logline — a regression silently dropping both fields
+ // would otherwise present as a healthy import with a synthetic placeholder
+ // arc summary downstream.
+ if (!arcContent.summary && !arcContent.logline) {
+ console.warn(`⚠️ importer arc extract returned empty summary+logline for "${promptSeriesName}" — using synthetic fallback`);
+ }
const arcSummary = arcContent.summary || arcContent.logline || `${promptSeriesName} — ${contentType}`;
const issuesRun = await runStagedLLM('importer-issue-proposal', {
diff --git a/server/services/loops.js b/server/services/loops.js
index 9f568a7472..071a61d45c 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -173,7 +173,14 @@ async function executeIteration(loop) {
// the directory the user picked.
cwd: loop.cwd || PATHS.root,
}).then(({ model: executedModel }) => {
- onComplete({ exitCode: 0, success: true, duration: Date.now() - startedAt, model: executedModel });
+ // Wrap `onComplete` so a throw inside the success branch doesn't fall
+ // through to the chained `.catch` below and get misclassified as
+ // `iteration:error`. History/persistence side is best-effort anyway.
+ return Promise.resolve()
+ .then(() => onComplete({ exitCode: 0, success: true, duration: Date.now() - startedAt, model: executedModel }))
+ .catch((err) => {
+ console.error(`❌ Loop ${id} onComplete (success branch) threw: ${err?.message || err}`);
+ });
}).catch(err => {
// Pre-migration `executeCliRun` always invoked `onComplete` — even on
// non-zero exit — so loop history / persistence / `iteration:complete`
diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.js
index 50b147f75d..f680f95655 100644
--- a/server/services/pipeline/migrateSeriesCanon.js
+++ b/server/services/pipeline/migrateSeriesCanon.js
@@ -46,10 +46,14 @@ export async function migrateSeriesCanon({ dryRun = false, log = console.log } =
};
if (counts.characters + counts.settings + counts.objects === 0) continue;
- // Auto-create a universe for orphan series so the migration completes
- // without manual linking. Named after the series so the user can find it
- // and merge later if desired.
+ // For orphan series, defer the link-to-universe write until AFTER the
+ // canon has landed in the universe. The link write strips the series'
+ // legacy `characters/settings/objects` (sanitizeSeries no longer
+ // round-trips them post-B.4), so a crash between linking and merging
+ // would leave the series stripped + the new universe empty. Holding the
+ // orphan-link variables here lets us flip the order at write time.
let universeId = s.universeId;
+ let pendingOrphanUniverse = null;
if (!universeId) {
if (dryRun) {
log(`📋 [dry-run] Would create universe for orphan series "${s.name}" (${s.id})`);
@@ -58,8 +62,11 @@ export async function migrateSeriesCanon({ dryRun = false, log = console.log } =
name: `${s.name} (auto-migrated)`,
starterPrompt: s.logline || s.premise?.slice(0, 500) || '',
});
- await updateSeries(s.id, { universeId: newUniverse.id });
+ pendingOrphanUniverse = newUniverse;
universeId = newUniverse.id;
+ // Count the universe at create-time so the trailing "created N
+ // universe(s)" log stays accurate — even when a crash later strands
+ // the link write, the universe really was created on disk.
summary.universesCreated += 1;
log(`🌌 Created universe "${newUniverse.name}" (${newUniverse.id}) for orphan series "${s.name}"`);
}
@@ -107,6 +114,14 @@ export async function migrateSeriesCanon({ dryRun = false, log = console.log } =
log(`✅ Migrated series "${s.name}" → universe "${universe.name}": ${Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ')}`);
}
}
+
+ // Now that the universe carries the canon (or we've at least attempted
+ // the write), link the orphan series. A crash earlier in the loop leaves
+ // the universe in place to retry against; the series still carries its
+ // legacy fields until this write lands.
+ if (pendingOrphanUniverse && !dryRun) {
+ await updateSeries(s.id, { universeId: pendingOrphanUniverse.id });
+ }
}
log(`📊 Migration complete: scanned ${summary.seriesScanned} series, migrated ${summary.seriesMigrated}, created ${summary.universesCreated} universe(s)`);
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index d0371e85ae..433dd3b355 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -230,6 +230,14 @@ export async function insertSeriesWithId(input = {}) {
}
export async function updateSeries(id, patch = {}) {
+ // Pre-B.4 canon (characters/settings/objects) lives on the universe, not the
+ // series — but a stale browser tab can still POST a legacy series shape and
+ // see a silent 200. Warn so a regression that re-introduces the legacy
+ // payload is observable in logs instead of vanishing canon.
+ const legacyFields = ['characters', 'settings', 'objects'].filter((k) => k in patch);
+ if (legacyFields.length > 0) {
+ console.warn(`⚠️ series PATCH ${id.slice(0, 8)} stripped legacy canon fields: ${legacyFields.join(', ')}`);
+ }
const { merged, nameChanged } = await queueSeriesWrite(async () => {
const state = await readState();
const idx = state.series.findIndex((s) => s.id === id);
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 1a1cd6646e..ea2c069081 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -163,7 +163,7 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput })
premise: series.premise,
styleNotes: series.styleNotes,
universeId: series.universeId || '',
- characters: canon?.characters || series.characters || [],
+ characters: canon?.characters || [],
},
issue: {
number: issue.number,
diff --git a/server/services/pipeline/volumePdf.js b/server/services/pipeline/volumePdf.js
index 969c1cf49c..b04fab0916 100644
--- a/server/services/pipeline/volumePdf.js
+++ b/server/services/pipeline/volumePdf.js
@@ -51,13 +51,19 @@ export async function buildVolumePdf(seriesId, seasonId, opts = {}) {
}
const volBackFilename = pickRenderedFilename(season.backCover);
- // All issues in this volume, sorted by arcPosition (with `??` fallback to
- // `number`). `||` would silently demote `arcPosition === 0` — a legitimate
- // first-position value — so use nullish coalescing.
+ // All issues in this volume, sorted by arcPosition first, then number, then
+ // id. Items with no arcPosition sink to the end (`?? Infinity`) so they
+ // don't interleave with positioned ones via a `number`-fallback. `||` chain
+ // collapses to zero-comparisons for the secondary keys so `arcPosition === 0`
+ // stays a legitimate first-position value.
const all = await listIssues({ seriesId });
const issuesInVolume = all
.filter((iss) => iss.seasonId === seasonId)
- .sort((a, b) => (a.arcPosition ?? a.number ?? 0) - (b.arcPosition ?? b.number ?? 0));
+ .sort((a, b) => (
+ (a.arcPosition ?? Infinity) - (b.arcPosition ?? Infinity)
+ || (a.number ?? 0) - (b.number ?? 0)
+ || a.id.localeCompare(b.id)
+ ));
// Build the ordered filename list + a parallel manifest for the colophon.
// The manifest tracks how many pages each issue contributed so the