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
Merge remote-tracking branch 'origin/main' into claim/v2-1-0-residue-batch
[._.]/ Adam Eivy4b304ed603e4
diff --cc DONE.mdindex b03268faf6,8839532e4f..d5d91f2f86--- a/DONE.md+++ b/DONE.md@@@ -10,7 -10,10 +10,11 @@@ For active roadmap see [PLAN.md](./PLAN### 2026-05-19+ - **[move-usenextevalcountdown-to-hooks] Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** Relocated `client/src/components/cos/useNextEvalCountdown.js` (1s-tick countdown to the next CoS evaluation) to `client/src/hooks/useNextEvalCountdown.js` to conform to the CLAUDE.md "Module Organization" rule that `useX` hooks live exclusively under `client/src/hooks/`. Dropped the re-export from `components/cos/index.js`, added the catalog row to `client/src/hooks/README.md` (Apps / Sessions / Domain), and added the barrel re-export to `client/src/hooks/index.js`. Only consumer (`client/src/pages/ChiefOfStaff.jsx`) now imports the hook directly from `../hooks/useNextEvalCountdown`, matching the existing direct-import pattern it already uses for `useSocket` and `useLocalStorageBool`. Pure relocation — no behavioral changes. All 154 client tests pass (the `hooks/index.test.js` barrel-shape invariant test confirms the move is correctly wired).+ - **[sharing-annotationssync-cache-bucket-asset-keys] Cache `listBucketAssetKeys` per (bucket, manifests-dir mtime).** `server/services/sharing/annotationsSync.js#listBucketAssetKeys` previously re-scanned every manifest in every auto-merge bucket on every 2s-debounced annotation flush. Manifests are the only source of truth post-v2 (content-addressed `assets/blobs/<hash>` paths don't carry filenames), so per-flush fan-out scaled O(buckets × manifests). The function now stats `<bucket>/manifests/` on each call and reuses the previously-parsed `Set<assetKey>` whenever the directory mtime matches — every manifest write/archive goes through `atomicWrite` (temp + rename) or `rename`, both of which bump the dir mtime, so the mtime is a complete invalidation signal. The legacy v1 `assets/{images,videos}/` dir scan stays uncached (small + rare fall-through). The annotation manifest emitted by `exportAnnotationsToBucket` rolls the cached mtime forward so the post-write bump doesn't immediately invalidate the same bucket's cache on the next flush. New `__resetBucketAssetKeysCache` test hook + 7 new vitest cases in `annotationsSync.test.js` covering hit, mtime-advance miss, per-bucket isolation, legacy-dir-scan-still-runs, ENOENT-on-manifests-dir as a stable cache key, non-ENOENT stat error bypasses caching, and post-write mtime-roll-forward keeps the next flush hot.+ - **[export-isplainobject-helper-from-server-lib-objects] Export `isPlainObject` from `server/lib/objects.js`.** Promoted the previously-private `isPlainObject(v) = !!v && typeof v === 'object' && !Array.isArray(v)` helper to a named export of `server/lib/objects.js` (surfaces automatically through the `server/lib/index.js` barrel) and migrated 18 inline call sites onto it — every site that exactly matched the 3-part check pattern. Sites: the previously-private declarations in `server/lib/objects.js` + `server/lib/mediaModels.js` (which now imports from objects.js), the 12 sites enumerated in PLAN (`services/calendarAccounts.js`, `messageAccounts.js`, `messagePlaywrightSync.js`, `loras.js`, `mortalLoomStore.js`, `updateChecker.js`, `meatspacePost.js`, `dataSync.js`, `featureAgents.js`, `taskSchedule.js` — also dropped its single-use local `const isPlainObject`, `pipeline/issues.js`, `sharing/exporter.js`), and 4 additional matching sites that landed between when the PLAN entry was authored and now (`routes/loras.js#DELETE /auth/civitai`, `services/universeBuilderExpand.js#sanitizeCategory`, `server/scripts/moltbook-probe.mjs`, and `scripts/check-themes.js` ×2 — the last two caught by codex review after the initial grep missed `.mjs` files and the top-level `scripts/` dir). Sites with a partial-shape second predicate (`mortalLoomStore.js`'s `current[k] && typeof current[k] === 'object'` and the symmetric block in `featureAgents.js`) kept their second predicate intact — only the full 3-part check was migrated, keeping the PR a pure refactor. Helper retains the loose "non-null, non-array `object`" semantics that match every call site's behavior (Date / Map / class instances still return true — documented in the JSDoc and locked in by 3 new vitest cases). `server/lib/README.md` row updated to name both `deepMerge` and `isPlainObject`. No behavioral changes. All 5832 server tests + 154 client tests pass.+ - **[unify-videogen-resolutions-with-shared-image-gen] Unify VideoGen `RESOLUTIONS` with shared image-gen list.** New `client/src/lib/videoGenResolutions.js` holding `VIDEO_RESOLUTIONS` as the companion to `imageGenResolutions.js`, registered in the lib barrel + README so future image+video work finds it via the catalog. New `resolveResolutionLabel(list, w, h) → { matched, label }` helper in `imageGenResolutions.js` collapses the duplicate "find matching preset OR fall back to `${w}×${h}` for the custom-fallback dropdown option" pattern that lived inline in both `client/src/pages/VideoGen.jsx` and `client/src/components/imageGen/ImageGenControls.jsx`. Both consumers now import the helper; image side's prior `(width && height ? ... : '')` empty-string-when-unset guard is preserved in the helper (returns `label: ''` when either dimension is falsy). Picked a distinct constant name (`VIDEO_RESOLUTIONS` vs the image side's `RESOLUTIONS`) to avoid a flat-barrel name collision in the lib `index.js` `export *` chain. All 154 client tests pass (barrel-shape test confirms the new module is wired correctly into both `index.js` and `README.md`).+- **[med-universe-builder-server-routes-universebuilder] [med-pipeline-server-routes-pipeline-js-145-149] [med-pipeline-server-services-pipeline-volumepdf-js] [med-pipeline-server-services-pipeline] [med-canon-server-services-pipeline-series-js-210] [low-ai-dispatch-server-lib-promptrunner-js-146] [low-ai-dispatch-server-services-loops-js-181-fire] [low-canon-server-services-pipeline-textstages-js] [low-canon-server-services-pipeline] [low-importer-server-services-importer-js-444-446] [low-ai-dispatch-server-lib-ansistrip-js-14-pattern] v2.1.0 pre-release review residue — small isolated fixes bundle.** Eleven items from the v2.1.0 main→release multi-agent review shipped together because each is a 1–10 line isolated fix and most touch independent files. (1) `server/routes/universeBuilder.js` — `registerUniverseBuilderRun(...)` moved BEFORE the enqueue loop using `compiled.length` as the authoritative job count, so the worker can no longer pick up the first job and emit `completed` before the run is registered (which would lose the per-image emit coalescing the hook depends on). (2) `server/routes/pipeline.js` — `seasonCoverSchema` gained `.passthrough()` so a "save full series" round-trip echoing the server-built `proofImage` / `finalImage` render fields no longer 400s; matches the parent `seasonSchema`'s shape. (3) `server/services/pipeline/volumePdf.js` — issue sort in `assembleVolumePdf` now uses `(a.arcPosition ?? Infinity) - (b.arcPosition ?? Infinity) || (a.number ?? 0) - (b.number ?? 0) || a.id.localeCompare(b.id)`, sinking arcPosition-null items to the end instead of letting `number`-fallback interleave them with positioned ones. (4) `server/services/pipeline/seasonCoverFilenameHook.js` — verified the empty-patch short-circuit is already in `updateSeasonOnSeries` (`series.js:335-344` returns `cur` unchanged when `patchFn` returns `{}`); item archived as already-done. (5) `server/services/pipeline/series.js` — `updateSeries` emits `console.warn` when the incoming patch carries `characters` / `settings` / `objects` (post-B.4 those live on the universe), so a stale browser tab POSTing legacy canon is observable in logs instead of vanishing silently with 200 OK. (6) `server/lib/promptRunner.js` — `effectiveCwd` now uses `(typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd()` matching `tuiPromptRunner.js:103`'s pattern; an empty-string override no longer leaks through `??` to spawn(). (7) `server/services/loops.js` — `onComplete({success:true})` is wrapped in `Promise.resolve().then().catch()` so a throw in the success branch is no longer misclassified as iteration-failed by the trailing `.catch` and falsely emits `iteration:error`. (8) `server/services/pipeline/textStages.js` — dropped the dead `|| series.characters` middle clause from the canon-fallback (post-B.4 `series.characters` is always undefined). (9) `server/services/pipeline/migrateSeriesCanon.js` — orphan-series link write (`updateSeries({ universeId })`) is deferred until AFTER the universe canon patch lands; a crash between create-universe and patch-universe now leaves the legacy series fields intact for retry, instead of stripped + empty. (10) `server/services/importer.js` — emits `console.warn` when the arc-extract LLM returns empty `summary` AND empty `logline` (the synthetic fallback `${name} — ${type}` still fires; the warning makes the silent regression observable). (11) `server/lib/ansiStrip.js` — both the streaming stripper and the one-shot `stripAnsi` gained a `.replace(/\x1B(?![@-_\[\]])/g, '')` second pass so a chunk like `\x1B\x1B[31m` no longer leaks the leading orphan escape byte after the trailing CSI is consumed. All 5829 server tests pass.- **[med-sharing-server-services-sharing] [med-sharing-server-services-mediaannotations-js-38] [low-sharing-server-services-mediaannotations-js] [low-sharing-server-services-mediaannotations-js-2] [low-sharing-server-services-sharing] Sharing/annotation-merge hardening bundle.** Five v2.1.0 pre-release residue items shipped together because they all touch the same annotation-sync + LWW-merge surface. (1) `annotationsSync.flushAll` no longer resolves one `sourceName` for all buckets — `exportAnnotationsToBucket` now resolves its own per-bucket name, so per-bucket `displayNameOverride` is honored in outgoing annotation manifest envelopes the same way it already was for series/universe/media manifests. The bucket-effective resolver lives in `sharing/annotationIdentity.js` as a new `resolveBucketSourceName(bucket)` export consumed by both the exporter and the annotation flush (the exporter's local copy in `sharing/exporter.js` was deleted in favor of the shared helper). (2) `mediaAnnotations.mergePeerAnnotations` now pre-rejects peer payloads with missing/invalid `updatedAt` before they reach `sanitizeAuthorEntry`'s `now`-fallback — previously a malformed peer record would always win LWW. The pre-check disambiguates "empty tombstone" (still applies as a delete) from "malformed payload" (now ignored entirely, instead of silently deleting the prior peer entry through the tombstone branch). (3) `sanitizeAuthorEntry` gained an opt-in `clampUpdatedAtTo` option used by the merge path so a peer whose clock is years ahead can't ratchet every subsequent LWW round on the same key — its `updatedAt` is clamped to local-now on import without disturbing reasonable timestamps. (4) `mergePeerAnnotations` rejects `peerInstanceId === 'unknown'` (and empty/non-string) on import — the outgoing path already guarded but a hand-crafted manifest or inconsistent peer could otherwise alias every record into the same "unknown" bucket and clobber each other on every merge. (5) `exportAnnotationsToBucket` now has a cheap early-out before `listBucketAssetKeys`: if local has zero annotations AND no prior record exists on disk for this `(bucket, instance)`, skip the manifest+asset-dir scan entirely (the common fresh-install fan-out case). A late-stage skip (both filtered AND prior empty) still covers the case where the bucket has assets but none overlap local. Coverage: 11 new vitest cases across `mediaAnnotations.test.js` (refuses `'unknown'` / empty peer id, drops missing+invalid updatedAt without nuking prior, clamps future-skewed peer ts) and new sibling `sharing/annotationsSync.test.js` (per-bucket displayNameOverride honored in record, cheap early-out skips `listManifestFilenames`, late skip when no local matches + no prior, asset-less bucket short-circuit, inbox-mode short-circuit, tombstone synthesis preserved for prior keys still in bucket). `/simplify` follow-up deferred to `[promote-unknown-instance-id-constant]` — promote the existing `UNKNOWN_INSTANCE_ID` constant from `importer.js` to a shared module + replace the bare `'unknown'` literal at the four remaining sites. All 5775 server tests pass.- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.