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
simplify: drop dead refine exports, tighten createBibleStore API, loosen source-text test
Adam Eivy78a243649c3c
diff --git a/PLAN.md b/PLAN.mdindex 88741fc6c1..73e371f6b1 100644--- a/PLAN.md+++ b/PLAN.md@@ -48,6 +48,8 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud- [ ] **Unify VideoGen.jsx RESOLUTIONS with the shared image-gen list** — `client/src/pages/VideoGen.jsx:54` defines its own private `RESOLUTIONS` array + finds-by-w/h block, duplicating the pattern in `client/src/lib/imageGenResolutions.js`. Move VideoGen's presets into a shared `client/src/lib/videoGenResolutions.js` (or extend `imageGenResolutions.js` with a `media: 'image' | 'video'` field) so the dropdown + custom-fallback logic only lives in one place. Surfaced during the codex hi-res / per-backend filter work — `filterResolutions(mode, runner)` is exactly the helper VideoGen will want once mlx-video models gain runner-specific size constraints.- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`** — `MediaLightbox.jsx` hand-rolls touch-swipe nav (SWIPE_MIN_PX / TAP_MAX_PX / horizontal-dominant guard) and `navigator.clipboard.writeText` is inlined across 8+ call sites (`ExportTab`, `EditAppModal`, `NextActionBanner`, `JiraReports`, `RapidReader`, `Shell`, `RunsHistoryPage`, `MediaLightbox`). Extract once a second swipe consumer appears; clipboard can move now (`copy(text, label)` with the existing "insecure context" toast). Surfaced from the lightbox full-screen pass.- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`** — In full-screen mode the lightbox renders a hand-rolled aside (`absolute top-0 right-0 bottom-0 w-full sm:w-96 z-20`) that is exactly the project's existing `Drawer` component. Skipped during the simplify pass because `Drawer`'s flat Esc handler conflicts with the lightbox's layered Escape cascade (drawer → fullscreen → close); reconcile by either lifting the cascade above `Drawer` or letting `Drawer` accept a no-op-Esc prop.+- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern** — `client/src/pages/VideoGen.jsx` and `client/src/pages/CreativeDirector.jsx` both render an identical "filter(!deprecated).map + optgroup('Legacy') + filter(deprecated).map" block (differ only in `m.name` vs `m.name || m.id`). Extract `client/src/components/ModelSelect.jsx` taking `{ models, value, onChange, labelOf?, disabled? }` and convert both sites. ~30 LOC removal, and any future model dropdown picks up the deprecated-grouping for free. Surfaced from the LTX-deprecate /simplify pass.+- [ ] **Extract `mockPathsDataRoot()` test helper** — `server/lib/storyBible.test.js`, `server/services/writersRoom/{characters,settings,objects,local,promoteToPipeline}.test.js` (6 files) all open with byte-identical setup: `let tempRoot; vi.mock('../../lib/fileUtils.js', async () => { const actual = await vi.importActual(...); return new Proxy(actual, { get(t,p){ if (p==='PATHS') return new Proxy(actual.PATHS,{get(tp,pp){ if(pp==='data') return tempRoot; ... }}); ... } }); }); beforeEach(() => { tempRoot = mkdtempSync(...) }); afterEach(() => rmSync(tempRoot, { recursive: true, force: true }))`. Extract into `server/test-utils/tempDataRoot.js` exposing `mockPathsDataRoot()` that returns a live tempRoot getter. ~20 LOC saved per file plus a single fix-point if PATHS mocking semantics ever change. Surfaced from the bibleStore-factory /simplify pass.### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)diff --git a/client/src/hooks/useAsyncAction.js b/client/src/hooks/useAsyncAction.jsindex fc00925ffb..7bffedab3d 100644--- a/client/src/hooks/useAsyncAction.js+++ b/client/src/hooks/useAsyncAction.js@@ -1,4 +1,4 @@-import { useState, useCallback } from 'react';+import { useState } from 'react';import toast from '../components/ui/Toast';/**@@ -18,15 +18,15 @@ import toast from '../components/ui/Toast';*/export function useAsyncAction(fn, { errorMessage } = {}) {const [running, setRunning] = useState(false);- const run = useCallback(async (...args) => {+ const run = async (...args) => {setRunning(true);- const result = await Promise.resolve(fn(...args)).catch((err) => {+ const result = await fn(...args).catch((err) => {toast.error(err?.message || errorMessage || 'Action failed');return null;});setRunning(false);return result;- }, [fn, errorMessage]);+ };return [run, running];}diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 878f775b00..f9319790a0 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -380,25 +380,13 @@ export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAU/*** createBibleStore — per-work CRUD + merge factory. Collapses the three* writers-room domain files (characters/settings/objects) onto one- * implementation parameterized by `opts`:- *- * kind, idPrefix, idRegex, fileName, listKey- * dedupKey(entry) → string — normalize an entry to its dedup key- * primaryFields — fields that participate in the dedup key (['name'] for- * char/obj, ['slugline', 'name'] for settings)- * editableFields — patchable fields that DON'T go through the dedup-aware- * path; capped/cleaned by the kind's sanitizer- * requireOnCreate(patch) → string|undefined — message if required field- * missing (lets char/obj require `name`, settings require name-or-slugline)- * validateAfterUpdate(next) — optional; throw if invalid (settings use- * this for "both name and slugline blank → reject")- * conflictMessage(value), notFoundLabel, invalidIdMessage — error strings- *- * Returns { list, get, create, update, remove, mergeExtracted }. `remove`- * (not `delete`) because the latter is a JS keyword.+ * implementation. `remove` (not `delete`) because the latter is a JS keyword.*/const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;+const ID_SUFFIX_RE = /^[0-9a-f-]+$/i;+const FILE_NAME = Object.freeze({ character: 'characters.json', setting: 'settings.json', object: 'objects.json' });+const LIST_KEY = Object.freeze({ character: 'characters', setting: 'settings', object: 'objects' });const badReq = (message) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });const notFoundErr = (what) => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });const wrDir = (workId) => {@@ -408,15 +396,21 @@ const wrDir = (workId) => {export function createBibleStore(opts) {const {- kind, idPrefix, idRegex, fileName, listKey, dedupKey, primaryFields,+ kind, idPrefix, dedupKey, primaryFields,editableFields, requireOnCreate, validateAfterUpdate, conflictMessage,notFoundLabel, invalidIdMessage,} = opts;const sanitizer = SANITIZERS[kind];- if (!sanitizer) throw new Error(`createBibleStore: unknown kind "${kind}"`);+ const fileName = FILE_NAME[kind];+ const listKey = LIST_KEY[kind];+ if (!sanitizer || !fileName) throw new Error(`createBibleStore: unknown kind "${kind}"`);const sortKeyFn = sortKey(kind);const filePath = (workId) => join(wrDir(workId), fileName);- const assertId = (id) => { if (!idRegex.test(id)) throw badReq(invalidIdMessage); };+ const assertId = (id) => {+ if (typeof id !== 'string' || !id.startsWith(idPrefix) || !ID_SUFFIX_RE.test(id.slice(idPrefix.length))) {+ throw badReq(invalidIdMessage);+ }+ };async function load(workId) {const fallback = { [listKey]: [], updatedAt: null };diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 986b3bf1ef..3789f11a1b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -671,21 +671,13 @@ export const writersRoomObjectUpdateSchema = z.object({}).strict();// Generic bible-entry schemas — re-exports of the writers-room schemas under-// kind-neutral names so the Pipeline routes can share the same validation-// surface. The Pipeline extends these with its own back-compat fields-// (`description` legacy alias on character, `imageRefs`, `id`) in-// `server/routes/pipeline.js`; both surfaces ultimately funnel through the-// canonical sanitizer in `server/lib/storyBible.js`.-//-// NOTE: `settingBibleCreateSchema` is the un-refined ZodObject (not the-// refined ZodEffects export `writersRoomSettingCreateSchema`) so callers-// can `.extend()` it. The "needs name or slugline" refine is exported as-// `settingBibleRefine` so extenders can re-apply it after extending.+// kind-neutral names so the Pipeline routes share the same validation+// surface and funnel through the canonical sanitizer in storyBible.js.+// `settingBibleCreateSchema` is the un-refined ZodObject (not the refined+// `writersRoomSettingCreateSchema`) so Pipeline can `.extend()` it.export const characterBibleCreateSchema = writersRoomCharacterCreateSchema;export const characterBibleUpdateSchema = writersRoomCharacterUpdateSchema;export const settingBibleCreateSchema = writersRoomSettingCreateObject;-export const settingBibleRefine = settingHasIdentifier;-export const settingBibleRefineMessage = 'Setting requires either a slugline or a name';export const settingBibleUpdateSchema = writersRoomSettingUpdateSchema;export const objectBibleCreateSchema = writersRoomObjectCreateSchema;export const objectBibleUpdateSchema = writersRoomObjectUpdateSchema;diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex a73afafbd9..af60b4802f 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -304,27 +304,24 @@ describe('spawningTasks dedup — late-delete race', () => {// flips red and points the dev at the race the structural change re-opened.describe('agentLifecycle source — spawningTasks delete placement', () => {- it('releases the dedup guard inside a finally that wraps the spawn call', () => {+ it('releases the dedup guard inside a finally, not after updateTask(in_progress)', () => {const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');expect(fnStart, 'spawnAgentForTask must exist').toBeGreaterThan(-1);-- // Slice from the function start to the first closing top-level `}`.- // The function body is ~430 lines; grab enough to cover it.const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);- // The function must contain `spawningTasks.add(task.id)` (the guard add).expect(fnBody).toMatch(/spawningTasks\.add\(task\.id\)/);- // ANTI-PATTERN: a `spawningTasks.delete(task.id)` immediately after the+ // ANTI-PATTERN: bare `spawningTasks.delete(task.id);` directly after the// `updateTask(... 'in_progress' ...)` await (the pre-fix shape). The- // negative lookahead allows the `delete` only inside an `if (!update…)`- // / `cleanupOnError` branch.+ // delete must live inside a `finally` block instead.const buggyPattern = /await\s+updateTask\([\s\S]{0,800}?status:\s*['"]in_progress['"][\s\S]{0,800}?\}\s*,\s*task\.taskType[\s\S]{0,200}?\)\s*;\s*spawningTasks\.delete\(task\.id\)/;expect(fnBody).not.toMatch(buggyPattern);- // The spawn-call section (spawnViaRunner / spawnDirectly) must be wrapped- // in a try/finally with the dedup delete in the finally clause.- const tryFinallyPattern = /try\s*\{[\s\S]*?spawnViaRunner[\s\S]*?spawnDirectly[\s\S]*?\}\s*finally\s*\{\s*spawningTasks\.delete\(task\.id\)\s*;?\s*\}/;- expect(fnBody).toMatch(tryFinallyPattern);+ // The dedup-delete must be inside a `finally { ... }` clause somewhere in+ // the function — the structural guarantee that the guard outlives the+ // spawn call regardless of which runner/direct branch is taken or what+ // the function names become.+ const finallyPattern = /finally\s*\{[\s\S]{0,400}?spawningTasks\.delete\(task\.id\)/;+ expect(fnBody).toMatch(finallyPattern);});});diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.jsindex 8ee12bac12..bf7edcdd48 100644--- a/server/services/writersRoom/characters.js+++ b/server/services/writersRoom/characters.js@@ -18,9 +18,6 @@ export const {} = createBibleStore({kind: BIBLE_KIND.CHARACTER,idPrefix: 'wr-char-',- idRegex: /^wr-char-[0-9a-f-]+$/i,- fileName: 'characters.json',- listKey: 'characters',dedupKey: (entry) => normalizeBibleName(entry?.name),primaryFields: ['name'],editableFields: ['aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'],diff --git a/server/services/writersRoom/objects.js b/server/services/writersRoom/objects.jsindex b42cbc052f..b03188f596 100644--- a/server/services/writersRoom/objects.js+++ b/server/services/writersRoom/objects.js@@ -18,9 +18,6 @@ export const {} = createBibleStore({kind: BIBLE_KIND.OBJECT,idPrefix: 'wr-object-',- idRegex: /^wr-object-[0-9a-f-]+$/i,- fileName: 'objects.json',- listKey: 'objects',dedupKey: (entry) => normalizeBibleName(entry?.name),primaryFields: ['name'],editableFields: ['aliases', 'description', 'significance', 'notes'],diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/settings.jsindex b29838c00e..c0b69269ee 100644--- a/server/services/writersRoom/settings.js+++ b/server/services/writersRoom/settings.js@@ -27,9 +27,6 @@ export const {} = createBibleStore({kind: BIBLE_KIND.SETTING,idPrefix: 'wr-setting-',- idRegex: /^wr-setting-[0-9a-f-]+$/i,- fileName: 'settings.json',- listKey: 'settings',dedupKey,primaryFields: ['slugline', 'name'],editableFields: ['description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'],