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([sharing-exporter-cache-sourcefile-hash-by-mtime]): archive to DONE.md
[._.]/ Adam Eivy397966c3af4e
diff --git a/DONE.md b/DONE.mdindex 8b75af581f..e312706fbb 100644--- a/DONE.md+++ b/DONE.md@@ -13,6 +13,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./- **[med-sharing-server-services-sharing] [med-sharing-server-services-mediaannotations-js-38] [low-sharing-server-services-mediaannotations-js] [low-sharing-server-services-mediaannotations-js-2] [low-sharing-server-services-sharing] Sharing/annotation-merge hardening bundle.** Five v2.1.0 pre-release residue items shipped together because they all touch the same annotation-sync + LWW-merge surface. (1) `annotationsSync.flushAll` no longer resolves one `sourceName` for all buckets — `exportAnnotationsToBucket` now resolves its own per-bucket name, so per-bucket `displayNameOverride` is honored in outgoing annotation manifest envelopes the same way it already was for series/universe/media manifests. The bucket-effective resolver lives in `sharing/annotationIdentity.js` as a new `resolveBucketSourceName(bucket)` export consumed by both the exporter and the annotation flush (the exporter's local copy in `sharing/exporter.js` was deleted in favor of the shared helper). (2) `mediaAnnotations.mergePeerAnnotations` now pre-rejects peer payloads with missing/invalid `updatedAt` before they reach `sanitizeAuthorEntry`'s `now`-fallback — previously a malformed peer record would always win LWW. The pre-check disambiguates "empty tombstone" (still applies as a delete) from "malformed payload" (now ignored entirely, instead of silently deleting the prior peer entry through the tombstone branch). (3) `sanitizeAuthorEntry` gained an opt-in `clampUpdatedAtTo` option used by the merge path so a peer whose clock is years ahead can't ratchet every subsequent LWW round on the same key — its `updatedAt` is clamped to local-now on import without disturbing reasonable timestamps. (4) `mergePeerAnnotations` rejects `peerInstanceId === 'unknown'` (and empty/non-string) on import — the outgoing path already guarded but a hand-crafted manifest or inconsistent peer could otherwise alias every record into the same "unknown" bucket and clobber each other on every merge. (5) `exportAnnotationsToBucket` now has a cheap early-out before `listBucketAssetKeys`: if local has zero annotations AND no prior record exists on disk for this `(bucket, instance)`, skip the manifest+asset-dir scan entirely (the common fresh-install fan-out case). A late-stage skip (both filtered AND prior empty) still covers the case where the bucket has assets but none overlap local. Coverage: 11 new vitest cases across `mediaAnnotations.test.js` (refuses `'unknown'` / empty peer id, drops missing+invalid updatedAt without nuking prior, clamps future-skewed peer ts) and new sibling `sharing/annotationsSync.test.js` (per-bucket displayNameOverride honored in record, cheap early-out skips `listManifestFilenames`, late skip when no local matches + no prior, asset-less bucket short-circuit, inbox-mode short-circuit, tombstone synthesis preserved for prior keys still in bucket). `/simplify` follow-up deferred to `[promote-unknown-instance-id-constant]` — promote the existing `UNKNOWN_INSTANCE_ID` constant from `importer.js` to a shared module + replace the bare `'unknown'` literal at the four remaining sites. All 5775 server tests pass.- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.+- **[sharing-exporter-cache-sourcefile-hash-by-mtime] Cache `sha256File` results in the exporter by `(sourcePath, mtime, size)`.** `server/services/sharing/exporter.js#copyAssetIfPresent` no longer re-hashes every referenced asset on every export — a subscription re-export of a 200MB series previously re-read 200MB of bytes just to confirm "blob already there." Added a per-bucket sidecar `<bucket>/assets/blobs/.index.json` mapping `<sourcePath>:<mtimeMs>:<size> → <hash>` (the size is part of the key as defense-in-depth alongside mtime). New `loadAssetHashCache(bucketPath)` reads the JSON once at the start of each top-level exporter (`exportSeries`, `exportUniverse`, `exportMedia`); `copyAssetIfPresent(filename, kind, bucketPath, cache)` reads the cache before computing the hash and only falls through to `sha256File` + `copyFile` when the cache key is missing OR the recorded blob no longer exists in `assets/blobs/`. New cache entries accumulate in the shared object across all parallel `Promise.all` branches (jobs + image + video + image-ref) and `saveAssetHashCache` atomically writes once after the `Promise.all` resolves. Cache key includes the absolute source path so unrelated buckets pointing at the same asset still benefit independently. mtime change automatically invalidates because it's part of the key. The threaded cache also flows through `exportMediaJobAndAsset` so media-job-driven asset copies share the same cache. `isHexHash` validates cached values before trusting them so a hand-edited or torn `.index.json` can't poison `bucketBlobPath` (the existing hostile-hash guard already throws on bad shapes; the read-side filter just makes the cache fall back to recompute instead of throwing). The existing content-addressed-dedup test (`readdirSync(blobs/)`) now filters dotfiles so the `.index.json` sidecar isn't counted as a blob. New integration test pins all four behaviors: the index file is created, the key format matches the documented contract, an unchanged re-export keeps the cache file byte-identical, an mtime-only bump (same bytes) records a new key with the unchanged hash, and a content mutation records a fresh hash + lands a new blob under the new content-addressed path. All 5756 server tests + 121 client tests pass.- **[wardroberow-migrate-to-userowdraft] Migrate `WardrobeRow` to consume `useRowDraft`.** `client/src/components/pipeline/CanonCard.jsx` no longer runs two `useFieldDraft` calls per outfit row — a single `useRowDraft(wardrobe, onCommit)` call covers both columns, so wardrobe entries pick up the same sibling-draft ride-along race protection that landed for `ListRow` in `[characterdetaileditor-listrow-row-draft-hook]`. `WardrobeSection.commit` reshapes from `(idx, field, value)` to `(idx, nextRow)`; the pending-row promotion trigger moves from "per-field `name` commit with non-empty value" to "any commit where `nextRow.name.trim()` is non-empty" — same end state, and the rewrite fires earlier for the ride-along case (description blur with a pending name draft now promotes the row instead of stranding it in `pendingNew`). The deferred concern from PLAN ("promotion semantics need their own design pass") resolved by following the existing `CharacterDetailEditor.updateRow` pattern, which already runs the same required-column check against `nextRow`. Removed the now-unused `useFieldDraft` import from `CanonCard.jsx`. +1 ride-along regression test in `CanonCard.test.jsx` (description blurs first with a pending name draft → row promotes with both fields intact). All 121 client tests pass.- **[code-quality-dedup-batch] Code quality / dedup batch — 8 items shipped together.** (1) `[extract-optionalbooleanmap-zod-helper]` — new `optionalBooleanMap(keys)` helper in `server/lib/validation.js` collapsing the `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))` pattern at 3 sites (`server/routes/universeBuilder.js`, `server/routes/pipeline.js` ×2). (2) `[extract-a-tryreadfile-helper]` — new `tryReadFile(path, encoding='utf8')` in `server/lib/fileUtils.js` replacing the `readFile(...).catch(() => null)` pattern at ~60 sites across `server/`; `readFile` import removed from 22 files where all uses migrated. Auto-injected `tryReadFile` mock into ~80 test files' `vi.mock('../lib/fileUtils.js')` bodies to keep partial mocks working. (3) `[aitoolkit-loadproviders-corrupt-fallback]` — `loadProviders` in `server/lib/aiToolkit/providers.js` now wraps `JSON.parse` in a `parseOrRescue(content, source)` helper that renames the corrupt user file to `<path>.corrupt.<timestamp>` + logs + returns `{ activeProvider: null, providers: {} }` so a garbled providers.json can't crash server boot. The shipped-sample path parses BEFORE persisting so a malformed sample can't seed user-side providers.json with garbage (per codex review). (4) `[more-resolveproviderandmodel-migration-candidates]` — migrated 3 sites onto the existing `resolveProviderAndModel` helper (`server/services/agentContentGenerator.js#runAIGeneration`, `server/services/agentPersonalityGenerator.js`, `server/services/loops.js#runIteration`); loops.js wraps with `.catch(() => ({ provider: null }))` to preserve the original "swallow all" semantics across both `getProviderById` and `getActiveProvider` failures. (5) `[extract-assertprovider-helper]` — new `assertProvider(provider, { message, code, status = 503 })` helper in `server/lib/promptRunner.js`; throws `ServerError` with code+status when `code` is provided, plain `Error` otherwise (preserves each caller's original error shape). Migrated 7 `if (!provider) throw …` sites (`universeBuilderAutoSort.js`, `universeBuilderRefine.js`, `universeBuilderExpand.js` ×2, `universeBuilderPromote.js`, `agentContentGenerator.js`, `agentPersonalityGenerator.js`). Auto-injected `assertProvider` mock into 6 test files mocking `promptRunner.js`. (6) `[extract-uselocktoggle-hook]` — new `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage })` returning `{ busy, toggle }` in `client/src/hooks/useLockToggle.js` collapsing the optimistic-PATCH lock toggle pattern at 4 sites: `toggleArcLock`/`FieldLockToggle#toggle`/`toggleSeasonLock` in `client/src/components/pipeline/ArcCanvas.jsx`, `handleStageLockToggle` in `client/src/pages/PipelineIssue.jsx` (removes the now-dead `stageLockSaving` useState). (7) `[skip-the-text-accumulator-in-promptrunner]` — `runPromptThroughProvider`'s `onData` now skips the `APPEND_CHUNK` text concat for TUI providers (which discard the accumulated `text` anyway in favor of `result.text` from `executeTuiRun`); TUI screen-redraw streams can hit hundreds of KB per run. (8) `[aitoolkit-createprovider-field-parity-test]` — new exhaustive test in `server/lib/aiToolkit/providers.test.js` that round-trips all 20 fields defined in `createProvider`'s explicit field list through `create → save → reload`, guarding against the regression where a Zod-schema field is added without being mirrored into the explicit `createProvider` field list. All 5690 server tests + 103 client tests pass; client build clean.- **[characterdetaileditor-listrow-row-draft-hook] Extract `ListRow`'s multi-column row-draft state into a shared `useRowDraft` hook.** `client/src/components/universe/CharacterDetailEditor.jsx`'s `ListRow` carried 19 lines of inline `useState({})` draft buffer + `draftFor`/`setDraft`/`commit` triple, with the load-bearing sibling-draft "ride-along" merge (`{...row, ...drafts, [col]: v}`) that keeps a fast A-blur → B-blur sequence from losing column A when the parent hasn't re-rendered yet. Lifted into new `client/src/hooks/useRowDraft.js` — the row-level analogue of `useFieldDraft` (single-field draft+blur). Hook signature is `useRowDraft(row, onChange)` returning `{ draftFor, setDraft, commit }`; preserves the ride-along merge verbatim and coerces `null`/`undefined` persisted columns to `''` so inputs stay controlled. `ListRow` collapses to a single hook call. 9 new vitest cases cover persisted/empty fallback, draft buffering without firing onChange, commit no-op when value equals persisted, commit no-op when no draft set, null-as-empty equivalence, the ride-along race-protection invariant (committing column B with a pending column-A draft ships both in one onChange), and that commit clears only the committed column from the drafts map. All 112 client tests pass.diff --git a/PLAN.md b/PLAN.mdindex 0782e5c10b..aef834b470 100644--- a/PLAN.md+++ b/PLAN.md@@ -56,11 +56,12 @@ _Nothing currently parked — pick the next item from the Backlog._### Sharing — performance follow-ups (deferred from content-addressed asset dedup, 2026-05-18)-- [ ] [sharing-exporter-cache-sourcefile-hash-by-mtime] **Cache `sha256File` results in the exporter by `(sourcePath, mtime, size)`.** `copyAssetIfPresent` (`server/services/sharing/exporter.js`) re-hashes every referenced asset on every export, even when the blob already exists in the bucket. A subscription re-export of a 200MB series re-reads 200MB just to confirm "blob already there." Maintain a sidecar `<bucket>/assets/blobs/.index.json` mapping `<sourcePath>:<mtime>:<size> → <hash>`; skip the hash + copy when the cached entry matches and the blob is present. Invalidate purely on mtime change. ~30 LOC + one JSON file.- [ ] [sharing-annotationssync-cache-bucket-asset-keys] **Cache `listBucketAssetKeys` per (bucket, manifests-dir mtime).** Today `annotationsSync.js#listBucketAssetKeys` re-scans every manifest in every auto-merge bucket on every 2s-debounced annotation flush (post-v2 because content-addressed blob paths don't carry filenames, so manifests are the only source of truth). Memoize `Map<bucketPath, { mtime, keys }>` keyed on the manifests dir mtime; invalidate when mtime advances. The legacy `assets/{images,videos}/` dir scan is still needed as a fall-through for pre-v2 buckets and can run un-cached.### Code quality / dedup (from `/simplify` passes)+- [ ] [export-isplainobject-helper-from-server-lib-objects] **Export `isPlainObject` from `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` plain-object check is inlined at 14 sites across the codebase: `server/lib/objects.js:27` (private), `server/lib/mediaModels.js:183` (private), `server/services/calendarAccounts.js:11`, `messageAccounts.js:13`, `messagePlaywrightSync.js:29`, `loras.js:65`, `mortalLoomStore.js`, `updateChecker.js:93`, `meatspacePost.js:75`, `dataSync.js:112`, `featureAgents.js:108`, `taskSchedule.js:1900`, `pipeline/issues.js:673`, and (newly added 2026-05-19) `server/services/sharing/exporter.js#loadAssetHashCache`. Promote the helper to a named export in `objects.js`, add a row to `server/lib/README.md`, and migrate the call sites. Surfaced by /simplify during `[sharing-exporter-cache-sourcefile-hash-by-mtime]`; deferred to keep that PR scoped.+- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.- [x] [auto-save-after-expand-can-clobber-concurrent] ~~**Auto-save after expand can clobber concurrent canon edits.**~~ **Fixed in Phase B Copilot iteration 13** — both `handleExpand`'s auto-save and `handleSave`'s manual-save (when `canonDirty`) now refetch the server's canon via `getUniverse(selectedId)` and merge local additions with `mergeCanonByName` before the update payload is sent. Concurrent edits from NounsStage/other tabs are preserved on identity collision.- [x] [canon-merge-can-revert-concurrent-deletions] ~~**Canon-merge can revert concurrent deletions/renames.**~~ **Fixed in Phase B Copilot iteration 15** — handleExpand records each merge's NEW canon entries in a `pendingCanonAdditionsRef` sidecar; handleSave + handleExpand auto-save + handleCanonChange now merge ONLY that ledger onto the refetched server canon (not the full stale draft). Concurrent deletions in other tabs/surfaces are preserved because the deleted entry isn't in the ledger, so the server response (which already lacks it) wins.