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

add lib/hooks barrels + catalogs so reuse beats re-implementation

[._.]/ Adam Eivy791a4b94fba4
diff --git a/CLAUDE.md b/CLAUDE.md
index 1f270eaed8..5004a7f44b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -135,6 +135,58 @@ PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodul
- CoS agents can use `loadSlashdoCommand(name)` from `subAgentSpawner.js` to inline command content into prompts (resolves `!cat` lib includes automatically)
- The `.claude/commands/do/` symlinks make all `/do:*` commands available as project-level Claude Code slash commands
+## Module Organization
+
+PortOS has reached the size where re-implementing a helper is now cheaper to *start* than to find what already exists. To keep that pressure off, every directory that holds reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**
+
+### Where new code lives
+
+- **Pure / side-effect-free helpers** → `server/lib/` or `client/src/lib/`
+- **React hooks (state + lifecycle)** → `client/src/hooks/`. Names start with `use`.
+- **Formatting helpers (pure, no React)** → `client/src/utils/` (`formatters.js`, `cronHelpers.js`, etc.)
+- **HTTP / Socket / browser clients** → `client/src/services/`. API wrappers start with `api*`.
+- **Express handlers** → `server/routes/`. Use `validateRequest` + `lib/validation.js` schemas.
+- **Domain orchestration (multi-step business logic over models + services)** → `server/services/`.
+
+One concern per file. Tests live next to their source as `<name>.test.js`. Naming is camelCase with a domain prefix (`brainValidation.js`, `creativeDirectorPrompts.js`).
+
+### Discovery rule (BEFORE writing a helper)
+
+Grep the catalog for the directory most likely to hold it:
+
+```
+grep -i "what you want to do" server/lib/README.md
+grep -i "what you want to do" client/src/lib/README.md
+grep -i "what you want to do" client/src/hooks/README.md
+grep -i "what you want to do" client/src/services/README.md
+```
+
+If a close match exists, **extend it or use it**. Only add a new module when no existing one fits. Examples of pre-existing helpers that are easy to miss but should be reused:
+
+- `tryReadFile` in `server/lib/fileUtils.js` — collapses `readFile(path).catch(() => null)`.
+- `atomicWrite` in `server/lib/fileUtils.js` — `ensureDir + writeFile + JSON.stringify` in one call.
+- `optionalBooleanMap(keys)` in `server/lib/validation.js` — `z.object(Object.fromEntries(KEYS.map(k => [k, z.boolean().optional()])))` collapsed.
+- `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` in `server/lib/canonPrompt.js` (mirrored to client) — render `[{ prefix?, value }]` fragments to a sentence string or array.
+- `copyToClipboard` / `writeClipboardSilently` / `readClipboard` in `client/src/lib/clipboard.js` — safe across insecure-origin contexts. Do not use `navigator.clipboard.writeText` inline.
+- `useLockToggle` in `client/src/hooks/useLockToggle.js` — optimistic-PATCH lock-toggle for any new lock button.
+- `useSseProgress` in `client/src/hooks/useSseProgress.js` — generic JSON-frame EventSource subscriber; build new progress hooks on top of this.
+- `formatBytes` / `formatTimecode` / `formatDateShort` / `formatDurationMs` / `timeAgo` in `client/src/utils/formatters.js` — do not re-define formatters inside components.
+
+### Maintenance rule (WHEN adding a public module)
+
+Any new file added to `server/lib/`, `client/src/lib/`, `client/src/hooks/`, or a new `apiX.js` in `client/src/services/` **MUST**:
+
+1. Be re-exported from the same-directory `index.js` barrel (or, for `services/`, from `api.js`).
+2. Get a one-line row in the same-directory `README.md`.
+
+This is the one rule that keeps catalogs from rotting. The barrel is enforced by `server/lib/index.test.js` (and matching client tests) which verify that every non-test `.js` file appears both in the barrel AND in the README — boot will fail loudly if either drifts.
+
+**Name collisions.** When two modules in the same directory export the same identifier (e.g. `settingsUpdateInputSchema` in both `brainValidation.js` and `digitalTwinValidation.js`), the barrel uses `export * as <name>` namespace exports so the collision is unambiguous: callers reach for `brainValidation.settingsUpdateInputSchema` explicitly. The catch-all `validation.js` (and similar central modules) stays flat. The collision-detector test fails if two flat-`export *` modules ever share an identifier — forcing namespace resolution at the point the conflict is introduced.
+
+Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the barrel exists for *discovery*, not to force a re-import. New code may use either form.
+
+The worked example for "barrel + documented exports" is `server/lib/aiToolkit/index.js`.
+
## Scope Boundary
When CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps must be written to the target app's own repository/directory -- never to this repo. PortOS stores only its own features, plans, and documentation. If an agent generates a PLAN.md, research doc, or feature spec for another app, it goes in that app's directory.
diff --git a/PLAN.md b/PLAN.md
index 9a3e32cae8..41412d9069 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -68,7 +68,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [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.
-- [ ] [extract-useswipenav-hook-lib-clipboard-js] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.
+- [ ] [extract-useswipenav-hook-lib-clipboard-js] **Extract `useSwipeNav` from `MediaLightbox`.** Clipboard half of the original entry already shipped (`client/src/lib/clipboard.js`); `client/src/hooks/useSwipeNav.js` also exists for the swipe pattern but `MediaLightbox` still inlines its own swipe state. Migrate `MediaLightbox` swipe to `useSwipeNav` so the lightbox + any future mobile-swipe surface share one hook.
- [ ] [route-medialightbox-settings-drawer-through] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.
- [ ] [useasyncaction-post-unmount-setstate-guard-add] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.
- [ ] [scene-level-wardrobe-picking-per-scene] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with wardrobe-picker dropdown. Decide first: does the extractor guess or does the user pick? Append wardrobe after physicalDescription vs substitute body fields?
@@ -78,7 +78,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [sweep-provider-type-tui-inline-checks-in-client] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.
- [ ] [datasync-migrate-categories-to-atomicwrite] **Migrate all `dataSync.js` categories to `atomicWrite`.** Every category (`goals`, `character`, `digitalTwin`, `meatspace`, `universe`, `pipeline`) inlines `ensureDir + writeFile + JSON.stringify(..., null, 2)` — 6+ duplicate sites. `server/lib/fileUtils.js:124` exports `atomicWrite(path, data)` that handles all three steps as a temp+rename atomic write. One-line collapse per site + meaningful partial-write protection for the larger pipeline JSON files (which other services write concurrently). Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`; deferred to keep that PR focused on the new categories.
- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.
-- [ ] [extract-flatten-canon-descriptor-fragments-helper] **Extract `flattenCanonDescriptorFragments(fragments, { separator, trailingPeriod })` into `server/lib/canonPrompt.js` (+ client mirror).** The `.map(f => f.prefix ? \`${f.prefix}: ${f.value}\` : f.value).join(...)` pattern is now inlined at 4+ sites: `descriptorForCanonEntry` (server/lib/canonPrompt.js:175 — joins with `. `, no trailing-period), `buildScenePrompt` (server/lib/scenePrompt.js + client mirror — per-frag trailing-period, later joined with single space), `composeComicPagePrompt` (server/services/pipeline/visualStages.js:613 — joins with `. `, no trailing-period), and `synthesizeCanonPrompt` (server/services/universeBuilder.js ~1417). Two flag axes (separator, per-frag trailing-period) collapse to a small helper. Deferred from /simplify during `[pipeline-visual-stages-setting-field-injection]` to keep that PR tightly scoped to the field-injection.
+- [x] [extract-flatten-canon-descriptor-fragments-helper] ~~**Extract `flattenCanonDescriptorFragments(fragments, { separator, trailingPeriod })` into `server/lib/canonPrompt.js` (+ client mirror).**~~ Shipped — `flattenCanonDescriptorFragments` + `mapCanonDescriptorFragments` added to `server/lib/canonPrompt.js` and mirrored to `client/src/lib/canonPrompt.js`. All 6 inline sites migrated: server `canonPrompt.js`/`scenePrompt.js`/`services/pipeline/visualStages.js`/`services/universeBuilder.js` + the two client mirrors. The `mapCanonDescriptorFragments` companion supports the scene-prompt budget-truncator that needs the array form.
- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
@@ -169,7 +169,11 @@ God-file decomposition candidates — none are bugs; pick up when touching the f
## Deferred from better/2026-05-19
-- [ ] **Client formatter dedupe — signatures differ, skipped.** `client/src/pages/VideoTimelineEditor.jsx:41` defines `formatTime(sec)` (outputs `M:SS.ss` for video timecodes) vs shared `formatTime(timestamp)` (relative time like "5m ago"). `client/src/pages/VideoTimeline.jsx:7` defines `formatDuration(sec)` in seconds; shared alternatives are `formatDurationMs` (ms) and `formatDurationMin` (minutes). `client/src/components/brain/tabs/ImportTab.jsx:56` defines `formatDate` with `month: 'short'` and `'—'` fallback; shared version uses `month: 'long'` and returns `null`. All three need either reconciliation of the shared helper signatures or new named exports (`formatTimecode`, `formatDurationSec`) added to `client/src/utils/formatters.js` before the locals can be removed.
+- [x] ~~**Client formatter dedupe — signatures differ, skipped.**~~ Shipped — `formatTimecode`, `formatDurationSec`, and `formatDateShort` were added to `client/src/utils/formatters.js`; all 3 sites (`VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, `brain/tabs/ImportTab.jsx`) now import the shared helpers.
+
+- [ ] [move-usenextevalcountdown-to-hooks] **Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** `client/src/components/cos/useNextEvalCountdown.js` is a generic `useX` countdown hook living under `components/`, which the new "Module Organization" convention in CLAUDE.md places exclusively under `client/src/hooks/`. The other `useX`-named functions outside `hooks/` (`useThemeContext`, `useCitySettingsContext`, `useTokenEntries`) are context-consumer or pure `useMemo` helpers conventionally co-located with their providers — `useNextEvalCountdown` doesn't fit that exception. Surfaced by /simplify during the module-discovery PR; deferred to keep that PR scoped to infrastructure.
+
+- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.
## Future Ideas
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
new file mode 100644
index 0000000000..12d7aa91ca
--- /dev/null
+++ b/client/src/hooks/README.md
@@ -0,0 +1,96 @@
+# client/src/hooks/ — shared React hooks
+
+State + lifecycle + side-effect hooks. **Before writing a `useX` hook, grep this catalog
+first** — many domain patterns already have one. When you add a new hook, add it to
+`index.js` AND add a row here.
+
+Pure helpers (no React state) live in `client/src/lib/`. HTTP/socket clients live in
+`client/src/services/`. Formatting helpers live in `client/src/utils/`.
+
+## Discovery rule
+
+```
+grep -i "what you want to do" client/src/hooks/README.md
+```
+
+---
+
+## Notifications & toasts
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useNotifications` | Generic toast dispatch + socket-subscribed notification list. | You need to read / dispatch the global notification stream. |
+| `useErrorNotifications` | Subscribes to server error events and shows toasts. | Wire once high in the tree to surface server errors. |
+| `useAIStatusNotifications` | Subscribes to AI operation status events. | Wire once to surface AI run lifecycle as toasts. |
+| `useAgentFeedbackToast` | Agent completion toast with thumbs-up/down UI. | Show actionable agent-run completion feedback. |
+| `useSharingNotifications` | Subscriber for share-bucket notifications. | Wire once to surface federation/sync events. |
+
+## Progress & streaming (SSE / socket)
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
+| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
+| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
+| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
+| `usePipelineAutoRunProgress` | Auto-run-text SSE for a pipeline issue. | Pipeline auto-run UI surfaces only. |
+| `usePipelineVolumeBeatsProgress` | Volume beat-sheet SSE. | Volume beat-sheet UI only. |
+
+## Media (annotations, completion, attachments)
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useMediaAnnotations` | Per-entry `own`/`others` annotations with back-compat aliases. | Showing media annotations + ownership. |
+| `useMediaCompletionRefresh` | Refetch on image/video completion socket events. | A list view that needs to refresh when new media lands. |
+| `useOpenClawAttachments` | File attachment handling (base64, size-capped). | OpenClaw attachment UI. |
+| `useImagePreviewActions` | Shared MediaPreview / MediaLightbox action handlers. | New surface that exposes the same 4 preview actions. |
+| `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |
+
+## Sockets & lifecycle
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
+| `useUpdateChecker` | Detect stale client bundle; show reload toast. | Wire once at app root. |
+| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
+
+## UI / interaction
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useArmedAction` | Two-click-arm `[armed, fire]` confirmation. | Destructive button needing a confirm tap. (Project memory: user finds this less discoverable — prefer inline confirm rows for new UI.) |
+| `useAutoRefetch` | Poll-based refetch on an interval. | Data needs periodic refresh (no socket / SSE available). |
+| `useClickOutside` | Fire `onOutside` on mousedown outside a ref. | Popovers, menus, drawers. |
+| `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. |
+| `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |
+| `useFieldDraft` | Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. |
+| `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. |
+| `useKeyboardControls` | Keyboard binding for CyberCity mode toggle. | CyberCity-specific. |
+| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
+| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
+| `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. |
+| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
+| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
+
+## Storage & persistence
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useLocalStorageBool` | Boolean `useState` mirrored to `localStorage`. | Per-user UI preference toggle. |
+
+## Apps / Sessions / Domain
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useAppDeploy` | Stream `deploy.sh` output via Socket.IO. | App deployment surfaces only. |
+| `useAppOperation` | Socket-based app ops (update, standardize) with step tracking. | App operations UI. |
+| `useCityAudio` | CyberCity ambient audio. | CyberCity only. |
+| `useCityData` | CyberCity environment data + physics. | CyberCity only. |
+| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
+| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
+| `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |
+| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
+| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
+| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
+| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
+| `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
new file mode 100644
index 0000000000..904bd6eb6e
--- /dev/null
+++ b/client/src/hooks/index.js
@@ -0,0 +1,73 @@
+// Barrel for client/src/hooks/ — discovery surface, not a forced import path.
+// See client/src/hooks/README.md for the human-readable catalog and
+// CLAUDE.md "Module organization" for the maintenance convention.
+//
+// Hooks export shape: most are named exports (`export function useX`), but a
+// handful default-export (`export default function useX`). The barrel
+// surfaces both as `useX` so importers don't need to know which style each
+// hook uses.
+
+// === Default-exporting hooks (re-exported as named) ===
+export { default as useCityAudio } from './useCityAudio.js';
+export { default as useClickOutside } from './useClickOutside.js';
+export { default as useContainerWidth } from './useContainerWidth.js';
+export { default as useFieldDraft } from './useFieldDraft.js';
+export { default as useImageGenQueue } from './useImageGenQueue.js';
+export { default as useImagePreviewActions } from './useImagePreviewActions.js';
+export { default as useKeyboardControls } from './useKeyboardControls.js';
+export { default as useMediaJobProgress } from './useMediaJobProgress.js';
+export { default as useMoltworldWs } from './useMoltworldWs.js';
+export { default as useMounted } from './useMounted.js';
+export { default as useProviderModels } from './useProviderModels.js';
+export { default as useRowDraft } from './useRowDraft.js';
+export { default as useTheme } from './useTheme.js';
+export { default as useUniverseAction } from './useUniverseAction.js';
+
+// === Mixed (both default and named) — surface both ===
+export { default as useAsyncAction } from './useAsyncAction.js';
+export * from './useAsyncAction.js';
+export { default as useCitySettings } from './useCitySettings.js';
+export * from './useCitySettings.js';
+
+// === Notifications & toasts ===
+export * from './useAIStatusNotifications.js';
+export * from './useAgentFeedbackToast.jsx';
+export * from './useErrorNotifications.js';
+export * from './useNotifications.js';
+export * from './useSharingNotifications.js';
+
+// === Progress & streaming (SSE / socket) ===
+export * from './useImageGenProgress.js';
+export * from './useOpenClawStream.js';
+export * from './usePipelineAutoRunProgress.js';
+export * from './usePipelineVolumeBeatsProgress.js';
+export * from './useSseProgress.js';
+
+// === Media (annotations, completion, attachments) ===
+export * from './useMediaAnnotations.js';
+export * from './useMediaCompletionRefresh.js';
+export * from './useOpenClawAttachments.js';
+
+// === Sockets & lifecycle ===
+export * from './useSocket.js';
+export * from './useUpdateChecker.jsx';
+
+// === UI / interaction ===
+export * from './useArmedAction.js';
+export * from './useAutoRefetch.js';
+export * from './useCmdKSearch.js';
+export * from './useKeyboardHelp.js';
+export * from './useLockToggle.js';
+export * from './useScrollLock.js';
+export * from './useSwipeNav.js';
+
+// === Storage & persistence ===
+export * from './useLocalStorageBool.js';
+
+// === Domain: City / Voice / Mortality / Universe / Apps / Sessions ===
+export * from './useAppDeploy.js';
+export * from './useAppOperation.js';
+export * from './useCityData.js';
+export * from './useDeathClock.js';
+export * from './usePostSession.js';
+export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/index.test.js b/client/src/hooks/index.test.js
new file mode 100644
index 0000000000..cee58844e5
--- /dev/null
+++ b/client/src/hooks/index.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import * as barrel from './index.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const BARREL_SRC = readFileSync(join(HERE, 'index.js'), 'utf8');
+const README_SRC = readFileSync(join(HERE, 'README.md'), 'utf8');
+
+const sourceFiles = readdirSync(HERE).filter(
+ (f) => (f.endsWith('.js') || f.endsWith('.jsx'))
+ && !f.endsWith('.test.js') && !f.endsWith('.test.jsx')
+ && f !== 'index.js',
+);
+
+describe('client/src/hooks/ barrel', () => {
+ it('resolves every re-export', () => {
+ expect(Object.keys(barrel).length).toBeGreaterThan(0);
+ });
+
+ it('exposes hooks under their canonical names', () => {
+ // Both default-exported and named-exported hooks should surface as `useX`.
+ expect(typeof barrel.useLockToggle).toBe('function');
+ expect(typeof barrel.useMounted).toBe('function');
+ expect(typeof barrel.useAsyncAction).toBe('function');
+ expect(typeof barrel.useSseProgress).toBe('function');
+ expect(typeof barrel.useSocket).toBe('function');
+ expect(typeof barrel.useClickOutside).toBe('function');
+ });
+
+ it('re-exports every non-test hook file from index.js', () => {
+ for (const f of sourceFiles) {
+ expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);
+ }
+ });
+
+ it('every non-test hook file has a README row', () => {
+ for (const f of sourceFiles) {
+ const base = f.replace(/\.(js|jsx)$/, '');
+ expect(README_SRC, `missing README entry for ${f}`).toContain(base);
+ }
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
new file mode 100644
index 0000000000..7f6eb7d9d8
--- /dev/null
+++ b/client/src/lib/README.md
@@ -0,0 +1,60 @@
+# client/src/lib/ — shared client helpers
+
+Pure / side-effect-free helpers used by pages, components, and hooks.
+**Before adding a new helper here, grep this catalog first** — if a similar module exists,
+extend it. When you add a new module, add it to `index.js` AND add a row here.
+
+Hooks (state + lifecycle) live in `client/src/hooks/`. HTTP/socket clients live in
+`client/src/services/`. Pure formatting helpers live in `client/src/utils/`.
+
+Several modules here are **server mirrors** — they must be kept byte-for-byte in sync with
+their server counterpart. The server copy is authoritative; the matching server test file
+is the contract.
+
+## Discovery rule
+
+```
+grep -i "what you want to do" client/src/lib/README.md
+```
+
+---
+
+## Prompt & rendering (server mirrors)
+
+| Module | Purpose |
+|---|---|
+| `canonPrompt.js` | Mirror of `server/lib/canonPrompt.js`. SHORT/RICH/PREVIEW spec + `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. |
+| `scenePrompt.js` | Mirror of `server/lib/scenePrompt.js`. Scene-prompt composer + bible matchers. |
+| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
+| `cleanPlatePrompt.js` | Clean-plate prompt builder for setting canon entries (Cluster A — A4). |
+| `seasonStructure.js` | Mirror of `server/lib/seasonStructure.js`. |
+| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
+| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |
+| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
+| `issueLength.js` | Mirror of `server/lib/issueLength.js`. |
+
+## Pipeline / image-gen defaults
+
+| Module | Purpose |
+|---|---|
+| `pipelineImageDefaults.js` | Pipeline comic-page image-gen defaults + settings reader. |
+| `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. |
+| `imageGenBackends.js` | `IMAGE_GEN_MODE` enum (local / codex / external) + metadata. |
+| `imageGenResolutions.js` | Shared resolution presets for image generation. |
+
+## Graph & sim
+
+| Module | Purpose |
+|---|---|
+| `graphSimulation.js` | 3D force simulation parameters for BrainGraph / CyberCity. |
+
+## Generic UI / collection utilities
+
+| Module | Purpose |
+|---|---|
+| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
+| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
+| `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |
+| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
+| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
+| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
diff --git a/client/src/lib/canonPrompt.js b/client/src/lib/canonPrompt.js
index 0e9111f203..6e4e130290 100644
--- a/client/src/lib/canonPrompt.js
+++ b/client/src/lib/canonPrompt.js
@@ -139,6 +139,27 @@ export function richCanonDescriptorFragments(kind, entry) {
return fragmentsFromSequence(sequence, entry);
}
+/**
+ * Render `[{ prefix?, value }]` fragments as an array of display strings.
+ * Mirror of server `mapCanonDescriptorFragments`. See server docstring.
+ */
+export function mapCanonDescriptorFragments(fragments, { trailingPeriod = false } = {}) {
+ if (!Array.isArray(fragments)) return [];
+ return fragments.map((f) => {
+ if (!f) return '';
+ const body = f.prefix ? `${f.prefix}: ${f.value}` : (f.value ?? '');
+ return f.prefix && trailingPeriod ? `${body}.` : body;
+ });
+}
+
+/**
+ * Flatten `[{ prefix?, value }]` fragments to a single sentence-style string.
+ * Mirror of server `flattenCanonDescriptorFragments`. See server docstring.
+ */
+export function flattenCanonDescriptorFragments(fragments, { separator = '. ', trailingPeriod = false } = {}) {
+ return mapCanonDescriptorFragments(fragments, { trailingPeriod }).join(separator);
+}
+
/**
* Flatten SHORT fragments into a sentence-style descriptor string.
* Matches the legacy `KINDS[].descFor` output:
@@ -147,9 +168,7 @@ export function richCanonDescriptorFragments(kind, entry) {
* objects: "description" else "significance"
*/
export function descriptorForCanonEntry(kind, entry) {
- return shortCanonDescriptorFragments(kind, entry)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
- .join('. ');
+ return flattenCanonDescriptorFragments(shortCanonDescriptorFragments(kind, entry));
}
/**
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
new file mode 100644
index 0000000000..f3181e983f
--- /dev/null
+++ b/client/src/lib/index.js
@@ -0,0 +1,31 @@
+// Barrel for client/src/lib/ — discovery surface, not a forced import path.
+// See client/src/lib/README.md for the human-readable catalog and
+// CLAUDE.md "Module organization" for the maintenance convention.
+
+// === Prompt & rendering (mirror server/lib/ — keep byte-for-byte in sync) ===
+export * from './canonPrompt.js';
+export * from './cleanPlatePrompt.js';
+export * from './composeStyledPrompt.js';
+export * from './scenePrompt.js';
+export * from './seasonStructure.js';
+export * from './universeStylePreset.js';
+
+// === Pipeline / image-gen defaults ===
+export * from './bibleLimits.js';
+export * from './imageGenBackends.js';
+export * from './imageGenResolutions.js';
+export * from './issueLength.js';
+export * from './pipelineImageDefaults.js';
+export * from './runnerFamilies.js';
+export * from './wrImageDefaults.js';
+
+// === Graph & sim ===
+export * from './graphSimulation.js';
+
+// === Generic UI / collection utilities ===
+export * from './clipboard.js';
+export * from './genUtils.js';
+export * from './joinInfluenceList.js';
+export * from './mediaNavigation.js';
+export * from './unsorted.js';
+export * from './upsertByIdPrepend.js';
diff --git a/client/src/lib/index.test.js b/client/src/lib/index.test.js
new file mode 100644
index 0000000000..c676f38a4b
--- /dev/null
+++ b/client/src/lib/index.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import * as barrel from './index.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const BARREL_SRC = readFileSync(join(HERE, 'index.js'), 'utf8');
+const README_SRC = readFileSync(join(HERE, 'README.md'), 'utf8');
+
+const sourceFiles = readdirSync(HERE).filter(
+ (f) => f.endsWith('.js') && !f.endsWith('.test.js') && f !== 'index.js',
+);
+
+describe('client/src/lib/ barrel', () => {
+ it('resolves every re-export', () => {
+ expect(Object.keys(barrel).length).toBeGreaterThan(0);
+ });
+
+ it('exposes a representative sample of helpers', () => {
+ expect(typeof barrel.copyToClipboard).toBe('function');
+ expect(typeof barrel.flattenCanonDescriptorFragments).toBe('function');
+ expect(typeof barrel.mapCanonDescriptorFragments).toBe('function');
+ expect(typeof barrel.descriptorForCanonEntry).toBe('function');
+ expect(typeof barrel.composeCleanPlatePrompt).toBe('function');
+ expect(typeof barrel.getAdjacentMedia).toBe('function');
+ });
+
+ it('re-exports every non-test .js file from index.js', () => {
+ for (const f of sourceFiles) {
+ expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);
+ }
+ });
+
+ it('every non-test .js file has a README row', () => {
+ for (const f of sourceFiles) {
+ const base = f.replace(/\.js$/, '');
+ expect(README_SRC, `missing README entry for ${f}`).toContain(base);
+ }
+ });
+});
diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.js
index 5bffb553a9..c33c7e87d6 100644
--- a/client/src/lib/scenePrompt.js
+++ b/client/src/lib/scenePrompt.js
@@ -1,7 +1,7 @@
// Mirror of server/lib/scenePrompt.js — keep byte-for-byte in sync.
// The shape-invariant tests in server/lib/scenePrompt.test.js are the contract.
-import { richCanonDescriptorFragments } from './canonPrompt.js';
+import { mapCanonDescriptorFragments, richCanonDescriptorFragments } from './canonPrompt.js';
const PROMPT_MAX = 1900;
@@ -101,8 +101,7 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
: '';
const placeMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');
const baselineFrags = matchedPlace
- ? richCanonDescriptorFragments('place', matchedPlace)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value))
+ ? mapCanonDescriptorFragments(richCanonDescriptorFragments('place', matchedPlace), { trailingPeriod: true })
: [];
const placeFrags = matchedPlace ? [
placeMetaFrag ? `${placeMetaFrag}.` : '',
diff --git a/client/src/services/README.md b/client/src/services/README.md
new file mode 100644
index 0000000000..b0ea5a30c8
--- /dev/null
+++ b/client/src/services/README.md
@@ -0,0 +1,106 @@
+# client/src/services/ — HTTP, sockets, and browser-facing clients
+
+API wrappers, Socket.IO client, and browser-facing clients (voice, DOM, UI dispatch).
+**Before adding a new HTTP call inline, grep this catalog first** — almost every backend
+domain already has a service file.
+
+`api.js` is a barrel that re-exports everything from the `apiX.js` files; callers can
+either `import * as api from '.../services/api'` or `import { specificFn } from '.../services/apiX'`.
+
+This directory has no `index.js` barrel because every file already follows the `apiX.js`
+naming convention, and `api.js` already aggregates them. When you add a new `apiX.js`,
+add it to `api.js` and add a row here.
+
+## Discovery rule
+
+```
+grep -i "what you want to do" client/src/services/README.md
+```
+
+The `request()` helper in `apiCore.js` toasts errors by default. Pass `{ silent: true }`
+when the caller owns its own error UI (custom catch + toast, or `useAsyncAction` which
+toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire twice.
+
+---
+
+## Core / infrastructure
+
+| File | Purpose |
+|---|---|
+| `api.js` | Barrel — re-exports every `apiX.js`. |
+| `apiCore.js` | `request()` helper + stable PortOS-app id. Shared error / toast handling. |
+| `socket.js` | Singleton Socket.IO client over relative path (Tailscale-friendly). |
+| `appUrls.js` | Compute candidate launch URLs for an app from page context. |
+
+## App lifecycle / system
+
+| File | Purpose |
+|---|---|
+| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs). |
+| `apiAccounts.js` | Platform accounts. |
+| `apiAgents.js` | Running-agent process management. |
+| `apiCommands.js` | CLI command dispatch. |
+| `apiDashboard.js` | Dashboard state. |
+| `apiDatabase.js` | Database introspection. |
+| `apiGit.js` | Git operations. |
+| `apiGithub.js` | GitHub repo metadata. |
+| `apiHistory.js` | Historical logs / runs. |
+| `apiPorts.js` | Port forwarding / allocation. |
+| `apiProviders.js` | AI provider config. |
+| `apiReferenceRepos.js` | Per-app reference-repo registry. |
+| `apiReview.js` | Review hub. |
+| `apiRuns.js` | Agent run history. |
+| `apiScaffold.js` | App scaffolding templates. |
+| `apiSchedules.js` | Automation schedules. |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts). |
+| `apiLoops.js` | Scheduled loops. |
+
+## Personal data / identity
+
+| File | Purpose |
+|---|---|
+| `apiBrain.js` | Brain (second-brain) search + ingest + edit. |
+| `apiMemory.js` | Memory CRUD. |
+| `apiNotes.js` | Notes vault. |
+| `apiDigitalTwin.js` | Digital twin status + summary. |
+| `apiGoals.js` | Identity / goals tracking. |
+| `apiHealth.js` | Apple Health. |
+| `apiMeatspace.js` | MeatSpace (genome + location). |
+| `apiMortalLoom.js` | Mortality tracking. |
+| `apiCalendar.js` | Calendar events. |
+| `apiMessages.js` | Messages / notifications. |
+| `apiPersonalities.js` | Agent personality profiles. |
+
+## Media / creative
+
+| File | Purpose |
+|---|---|
+| `apiImageVideo.js` | Image-gen local backend extras (gallery, models, LoRAs, cancel, delete). |
+| `apiMedia.js` | Screenshots + media assets. |
+| `apiMediaJobs.js` | Media generation job tracking. |
+| `apiCreativeDirector.js` | Creative Director (video production). |
+| `apiPipeline.js` | Pipeline (issues + stages + canon). |
+| `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |
+| `apiWritersRoom.js` | Writers Room (folders + works + drafts). |
+| `apiSharing.js` | Share buckets + federation sync. |
+
+## Tools / integrations
+
+| File | Purpose |
+|---|---|
+| `apiAsk.js` | Ask page (chat-like). |
+| `apiGSD.js` | "Get Stuff Done" integration. |
+| `apiImporter.js` | Manuscript / chat importer. |
+| `apiOpenClaw.js` | File browser / picker backend. |
+| `apiPalette.js` | Command-palette manifest + action dispatch. |
+| `apiVoice.js` | Voice synthesis / processing. |
+
+## Browser-facing (DOM, voice, build) — not pure API wrappers
+
+| File | Purpose |
+|---|---|
+| `voiceClient.js` | Browser-side voice capture + playback (two modes). |
+| `voiceVisibility.js` | Voice UI state manager. |
+| `uiInteract.js` | Execute voice `ui_click` / `ui_fill` / `ui_select` against live DOM. |
+| `domIndex.js` | DOM indexer for voice accessibility mode. |
+| `staleBuildToast.jsx` | Sticky toast shown when server's build id differs from client's. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 825aa7f35b..97e2a5f583 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -42,6 +42,9 @@ export * from './apiWritersRoom.js';
export * from './apiUniverseBuilder.js';
export * from './apiPipeline.js';
export * from './apiSharing.js';
+export * from './apiCreativeDirector.js';
+export * from './apiImporter.js';
+export * from './apiVoice.js';
// Default export for simplified imports (get/post/put/delete helpers)
export { default } from './apiCore.js';
diff --git a/server/lib/README.md b/server/lib/README.md
new file mode 100644
index 0000000000..b74ec07a43
--- /dev/null
+++ b/server/lib/README.md
@@ -0,0 +1,169 @@
+# server/lib/ — shared server helpers
+
+Pure / side-effect-free helpers, validators, parsers, prompt builders, and shared constants.
+**Before adding a new helper here, grep this catalog first** — if a similar module exists,
+extend it. When you add a new module, add it to `index.js` AND add a row here.
+
+Service-layer orchestration (multi-step business logic) lives in `server/services/`, not here.
+
+## Discovery rule
+
+```
+grep -i "what you want to do" server/lib/README.md
+```
+
+The barrel `server/lib/index.js` is a machine-checkable enumeration of every public surface;
+`server/lib/index.test.js` verifies that every non-test `.js` file is re-exported AND appears in this README, AND that no two flat-exported modules share an identifier name.
+
+**Namespace exports.** The validation modules (`brainValidation`, `digitalTwinValidation`, etc.), `runners`, `stageRunner`, and `storyBible` are surfaced through the barrel as namespace exports — `barrel.brainValidation.settingsUpdateInputSchema`, not bare `settingsUpdateInputSchema` — because their generic names collide with peers. Direct deep imports (`import { settingsUpdateInputSchema } from './brainValidation.js'`) are unaffected.
+
+---
+
+## Validation (Zod schemas + request validators)
+
+| Module | Purpose |
+|---|---|
+| `validation.js` | Catch-all Zod schemas + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`). Most route inputs validate through here. |
+| `appleHealthValidation.js` | Apple Health import payloads. |
+| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
+| `digitalTwinValidation.js` | Digital twin document/category schemas. |
+| `genomeValidation.js` | Genome upload + search schemas. |
+| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
+| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
+| `memoryValidation.js` | Memory record + retrieval schemas. |
+| `notesValidation.js` | Notes route schemas + safe-relative-path guard. |
+| `postValidation.js` | Social post schemas. |
+| `socketValidation.js` | Socket event payload schemas. |
+| `telegramValidation.js` | Telegram bot config + test schemas. |
+
+## Story & narrative
+
+| Module | Purpose |
+|---|---|
+| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. |
+| `storyArc.js` | Canonical Arc + Season shapes for pipeline arc planning. |
+| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. |
+| `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |
+| `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |
+| `seasonStructure.js` | Season/episode structure recommendation. |
+| `bibleExtractor.js` | LLM bible-extraction stage + sanitization. |
+| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
+| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
+| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
+| `creativeDirectorPrompts.js` | Creative Director agent prompt builders. |
+| `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context. |
+| `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). |
+| `writersRoomStylePresets.js` | Curated style presets for storyboards + universe. |
+
+## Prompt & AI
+
+| Module | Purpose |
+|---|---|
+| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. |
+| `aiProvider.js` | Shared AI provider utilities for LLM calls. |
+| `promptRunner.js` | Shared LLM runner wrapper. |
+| `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). |
+| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. |
+| `stageRunner.js` | Shared staged-LLM runner. |
+| `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. |
+| `promptPartials.js` | Mustache-style partial expansion. |
+| `mediaModels.js` | Single source of truth for image/video model metadata. |
+| `providerModels.js` | Provider model resolution sentinel + helpers. |
+| `runners.js` | Image-runner family constants. |
+| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
+| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
+| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
+| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
+
+## File & I/O
+
+| Module | Purpose |
+|---|---|
+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
+| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
+| `multipart.js` | Streaming multipart/form-data parser. |
+| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
+| `zipStream.js` | Streaming ZIP parser. |
+
+## Process execution
+
+| Module | Purpose |
+|---|---|
+| `commandSecurity.js` | Allowlist of safe shell commands. |
+| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
+| `pythonSetup.js` | Python venv / runner setup helpers. |
+
+## Networking
+
+| Module | Purpose |
+|---|---|
+| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). |
+| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |
+| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |
+| `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. |
+| `peerUrl.js` | Build the base URL for a peer. |
+| `sharingOrigin.js` | Origin metadata for records imported from share buckets. |
+| `tailscale.js` | Common paths where the Tailscale CLI binary is found. |
+| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
+
+## Search & indexing
+
+| Module | Purpose |
+|---|---|
+| `bm25.js` | BM25 ranking + inverted-index helpers. |
+| `vectorMath.js` | Vector math utilities (cosine, etc.). |
+| `memoryStats.js` | macOS-correct memory accounting (handles "Pages free" quirk). |
+
+## Extraction & parsing
+
+| Module | Purpose |
+|---|---|
+| `jsonExtract.js` | Pull JSON blocks out of LLM responses. |
+| `taskParser.js` | Parse `TASKS.md` format. |
+
+## Curated static data
+
+| Module | Purpose |
+|---|---|
+| `curatedGenomeMarkers.js` | Curated SNP database with classification logic. |
+
+## Domain utilities
+
+| Module | Purpose |
+|---|---|
+| `civitai.js` | Civitai URL parsing + API client. |
+| `issueLength.js` | Per-issue size targets fed into text stages. |
+| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
+| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
+| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
+| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
+| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
+| `telegramClient.js` | Telegram bot client. |
+
+## Model & config
+
+| Module | Purpose |
+|---|---|
+| `db.js` | PostgreSQL connection pool. |
+| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
+| `platform.js` | Platform/OS detection helpers. |
+| `timezone.js` | Timezone utilities for scheduling. |
+| `buildId.js` | Build-ID derived from the built client bundle. |
+
+## General utilities
+
+| Module | Purpose |
+|---|---|
+| `asyncMutex.js` | Promise-based async mutex. |
+| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
+| `objects.js` | Object utilities (deep merge, etc.). |
+| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
+| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
+
+## Test support
+
+| Module | Purpose |
+|---|---|
+| `mockPathsDataRoot.js` | Shared `vi.mock` factory for `PATHS.data → temp dir`. |
+| `testHelper.js` | Test HTTP request helper. |
diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.js
index c9557a899c..a32b217d9e 100644
--- a/server/lib/canonPrompt.js
+++ b/server/lib/canonPrompt.js
@@ -163,6 +163,38 @@ export function richCanonDescriptorFragments(kind, entry) {
return fragmentsFromSequence(sequence, entry);
}
+/**
+ * Render `[{ prefix?, value }]` fragments as an array of display strings.
+ *
+ * When `trailingPeriod` is true, each prefixed fragment is rendered as
+ * `${prefix}: ${value}.` so that a downstream caller can later join the array
+ * with a single space and still preserve "Palette: red. Era: Victorian."
+ * sentence boundaries (see `buildScenePrompt`'s budget-truncation join).
+ * Bare-value fragments never get a trailing period — the caller controls
+ * sentence punctuation when no prefix is involved.
+ */
+export function mapCanonDescriptorFragments(fragments, { trailingPeriod = false } = {}) {
+ if (!Array.isArray(fragments)) return [];
+ return fragments.map((f) => {
+ if (!f) return '';
+ const body = f.prefix ? `${f.prefix}: ${f.value}` : (f.value ?? '');
+ return f.prefix && trailingPeriod ? `${body}.` : body;
+ });
+}
+
+/**
+ * Flatten `[{ prefix?, value }]` fragments to a single sentence-style string.
+ *
+ * Shared by `descriptorForCanonEntry` (SHORT spec, `. ` separator),
+ * `composeComicPagePrompt` (RICH spec, `. ` separator), and
+ * `synthesizeCanonPrompt` (RICH spec, `. ` separator). The 4-arg
+ * `mapCanonDescriptorFragments` companion supports the scene-prompt budget
+ * truncator that needs the array form (`buildScenePrompt`).
+ */
+export function flattenCanonDescriptorFragments(fragments, { separator = '. ', trailingPeriod = false } = {}) {
+ return mapCanonDescriptorFragments(fragments, { trailingPeriod }).join(separator);
+}
+
/**
* Flatten SHORT fragments into a sentence-style descriptor string.
* Matches the legacy `KINDS[].descFor` output:
@@ -171,9 +203,7 @@ export function richCanonDescriptorFragments(kind, entry) {
* objects: "description" else "significance"
*/
export function descriptorForCanonEntry(kind, entry) {
- return shortCanonDescriptorFragments(kind, entry)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
- .join('. ');
+ return flattenCanonDescriptorFragments(shortCanonDescriptorFragments(kind, entry));
}
/**
diff --git a/server/lib/index.js b/server/lib/index.js
new file mode 100644
index 0000000000..2d13074a2e
--- /dev/null
+++ b/server/lib/index.js
@@ -0,0 +1,130 @@
+// Barrel for server/lib/ — discovery surface, not a forced import path.
+//
+// Existing deep imports (e.g. `import { x } from '../lib/fileUtils.js'`)
+// continue to work; this barrel exists so new code (and grep-driven
+// discovery) can find every shared helper from one place. See
+// `server/lib/README.md` for the human-readable catalog.
+//
+// MAINTENANCE RULE: any new module added to server/lib/ MUST be re-exported
+// here AND get a one-line entry in README.md. The same rule applies to
+// client/src/lib/, client/src/hooks/, and client/src/services/. See
+// CLAUDE.md "Module organization" for the full convention.
+
+// === Validation (Zod schemas + validators) ===
+// Domain-prefixed validators are namespace-exported so generic names that
+// collide across domains (e.g. `settingsUpdateInputSchema` exists in both
+// brain and digital-twin) can be disambiguated as `brainValidation.X` /
+// `digitalTwinValidation.X`. The catch-all `validation.js` stays flat — its
+// names are the canonical PortOS-wide schemas.
+export * as appleHealthValidation from './appleHealthValidation.js';
+export * as brainValidation from './brainValidation.js';
+export * as digitalTwinValidation from './digitalTwinValidation.js';
+export * as genomeValidation from './genomeValidation.js';
+export * as identityValidation from './identityValidation.js';
+export * as meatspaceValidation from './meatspaceValidation.js';
+export * as memoryValidation from './memoryValidation.js';
+export * as notesValidation from './notesValidation.js';
+export * as postValidation from './postValidation.js';
+export * as socketValidation from './socketValidation.js';
+export * as telegramValidation from './telegramValidation.js';
+export * from './validation.js';
+
+// === Story & narrative ===
+export * from './bibleExtractor.js';
+export * from './canonPrompt.js';
+export * from './comicScriptParser.js';
+export * from './composeStyledPrompt.js';
+export * from './creativeDirectorPresets.js';
+export * from './creativeDirectorPrompts.js';
+export * from './sceneExtractor.js';
+export * from './scenePrompt.js';
+export * from './seasonStructure.js';
+export * from './storyArc.js';
+// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for
+// back-compat — namespace it so the canonical scenePrompt export wins flat.
+export * as storyBible from './storyBible.js';
+export * from './universePromptRenderers.js';
+export * from './writersRoomPresets.js';
+export * from './writersRoomStylePresets.js';
+
+// === Prompt & AI (toolkit lives in aiToolkit/ — see its own index.js) ===
+export * from './aiProvider.js';
+export * from './ansiStrip.js';
+export * from './codexAssistantExtract.js';
+export * from './codexCliOutput.js';
+export * from './hfToken.js';
+export * from './mediaModels.js';
+export * from './promptPartials.js';
+export * from './promptRunner.js';
+export * from './promptTemplate.js';
+export * from './providerModels.js';
+// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
+// mediaModels.js — namespace it so the barrel surface is unambiguous.
+export * as runners from './runners.js';
+// `stageRunner.js` defines its own `extractJson` distinct from `jsonExtract.js`.
+export * as stageRunner from './stageRunner.js';
+export * from './tuiHandshake.js';
+export * from './tuiPromptRunner.js';
+
+// === File & I/O ===
+export * from './fileUtils.js';
+export * from './fileWriteQueue.js';
+export * from './multipart.js';
+export * from './pdfImageEmbed.js';
+export * from './zipStream.js';
+
+// === Process execution ===
+export * from './commandSecurity.js';
+export * from './execGit.js';
+export * from './ffmpeg.js';
+export * from './pythonSetup.js';
+
+// === Networking ===
+export * from './fetchWithTimeout.js';
+export * from './httpClient.js';
+export * from './httpsState.js';
+export * from './peerHttpClient.js';
+export * from './peerSelfHost.js';
+export * from './peerUrl.js';
+export * from './sharingOrigin.js';
+export * from './tailscale.js';
+
+// === Search & indexing ===
+export * from './bm25.js';
+export * from './memoryStats.js';
+export * from './vectorMath.js';
+
+// === Extraction & parsing ===
+export * from './jsonExtract.js';
+export * from './taskParser.js';
+
+// === Curated static data ===
+export * from './curatedGenomeMarkers.js';
+
+// === Domain utilities ===
+export * from './civitai.js';
+export * from './issueLength.js';
+export * from './mediaItemKey.js';
+export * from './navManifest.js';
+export * from './pipelineIssueOrder.js';
+export * from './planIds.js';
+export * from './renderSlot.js';
+export * from './telegramClient.js';
+
+// === Model & config ===
+export * from './buildId.js';
+export * from './db.js';
+export * from './platform.js';
+export * from './ports.js';
+export * from './timezone.js';
+
+// === General utilities ===
+export * from './asyncMutex.js';
+export * from './errorHandler.js';
+export * from './objects.js';
+export * from './sseUtils.js';
+export * from './uuid.js';
+
+// === Test support (consumed by *.test.js files) ===
+export * from './mockPathsDataRoot.js';
+export * from './testHelper.js';
diff --git a/server/lib/index.test.js b/server/lib/index.test.js
new file mode 100644
index 0000000000..2af2520568
--- /dev/null
+++ b/server/lib/index.test.js
@@ -0,0 +1,79 @@
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import * as barrel from './index.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const BARREL_SRC = readFileSync(join(HERE, 'index.js'), 'utf8');
+const README_SRC = readFileSync(join(HERE, 'README.md'), 'utf8');
+
+const sourceFiles = readdirSync(HERE)
+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js') && f !== 'index.js');
+
+// The barrel is the machine-checkable enumeration of every public surface in
+// `server/lib/`. If a `export * from './foo.js'` line points to a non-existent
+// module, the `import * as barrel` above throws — and so does this test. The
+// catalog-parity test below catches the inverse drift: a file added without
+// a README row. Both halves keep the discovery contract in CLAUDE.md honest.
+
+describe('server/lib/ barrel', () => {
+ it('resolves every re-export', () => {
+ expect(Object.keys(barrel).length).toBeGreaterThan(0);
+ });
+
+ it('exposes a representative sample of helpers', () => {
+ expect(typeof barrel.tryReadFile).toBe('function');
+ expect(typeof barrel.atomicWrite).toBe('function');
+ expect(typeof barrel.optionalBooleanMap).toBe('function');
+ expect(typeof barrel.flattenCanonDescriptorFragments).toBe('function');
+ expect(typeof barrel.mapCanonDescriptorFragments).toBe('function');
+ expect(typeof barrel.descriptorForCanonEntry).toBe('function');
+ expect(typeof barrel.ServerError).toBe('function');
+ expect(typeof barrel.v4).toBe('function');
+ });
+
+ it('re-exports every non-test .js file from index.js', () => {
+ // Forces the maintenance rule: a new server/lib/foo.js must be added to
+ // index.js. Catches a new helper that bypassed the barrel.
+ for (const f of sourceFiles) {
+ expect(BARREL_SRC, `missing barrel re-export for ${f}`).toContain(`'./${f}'`);
+ }
+ });
+
+ it('every non-test .js file has a README row', () => {
+ // Forces the catalog parity: a new helper must also get a one-line
+ // README entry. Looser match (filename anywhere in the README) so the
+ // table format can evolve without breaking this guard.
+ for (const f of sourceFiles) {
+ const base = f.replace(/\.js$/, '');
+ expect(README_SRC, `missing README entry for ${f}`).toContain(base);
+ }
+ });
+
+ it('has no export-name collisions across flat-`export *` modules', async () => {
+ // `export * from './foo.js'` (flat) silently drops names when two
+ // modules export the same identifier — whichever line comes last wins.
+ // `export * as foo from './foo.js'` (namespaced) is safe: it surfaces
+ // exports under a single `foo.*` key. Parse the barrel source for
+ // flat-star lines only, then verify their exports don't collide.
+ const flatStarRe = /^export \* from '\.\/([^']+)';/gm;
+ const flatModules = [...BARREL_SRC.matchAll(flatStarRe)].map((m) => m[1]);
+ const seen = new Map();
+ const collisions = [];
+ for (const f of flatModules) {
+ const mod = await import(/* @vite-ignore */ `./${f}`);
+ for (const name of Object.keys(mod)) {
+ if (name === 'default') continue;
+ if (seen.has(name) && seen.get(name).export !== mod[name]) {
+ // Same-name + different-identity = real collision. Same identity
+ // (e.g. one module re-exports another's symbol) is silently fine.
+ collisions.push(`${name}: ${seen.get(name).file} vs ${f}`);
+ } else if (!seen.has(name)) {
+ seen.set(name, { file: f, export: mod[name] });
+ }
+ }
+ }
+ expect(collisions, `Switch one module to \`export * as <name>\` namespace export:\n ${collisions.join('\n ')}`).toEqual([]);
+ });
+});
diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.js
index 02843af4e3..9b37c20a51 100644
--- a/server/lib/scenePrompt.js
+++ b/server/lib/scenePrompt.js
@@ -3,7 +3,7 @@
* deps — mirrored to `client/src/lib/scenePrompt.js` for the client bundle.
*/
-import { richCanonDescriptorFragments } from './canonPrompt.js';
+import { mapCanonDescriptorFragments, richCanonDescriptorFragments } from './canonPrompt.js';
const PROMPT_MAX = 1900;
@@ -151,8 +151,7 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
// preserves "Palette: X." sentence boundaries when the budget-truncation
// join collapses fragments with a single space.
const baselineFrags = matchedPlace
- ? richCanonDescriptorFragments('place', matchedPlace)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value))
+ ? mapCanonDescriptorFragments(richCanonDescriptorFragments('place', matchedPlace), { trailingPeriod: true })
: [];
const placeFrags = matchedPlace ? [
placeMetaFrag ? `${placeMetaFrag}.` : '',
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 81e9eac020..7922842876 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -36,7 +36,7 @@ import {
buildCharByKey, matchSceneCharacters, matchCharactersInText,
matchPlacesInText, matchObjectsInText,
} from '../../lib/scenePrompt.js';
-import { richCanonDescriptorFragments } from '../../lib/canonPrompt.js';
+import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../../lib/canonPrompt.js';
import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';
import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';
import { runStagedLLM } from '../../lib/stageRunner.js';
@@ -607,9 +607,7 @@ export function composeComicPagePrompt({
// is supported (a single page can span more than one location).
const placesClause = (matchedPlaces || [])
.map((p) => {
- const body = richCanonDescriptorFragments('place', p)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
- .join('. ');
+ const body = flattenCanonDescriptorFragments(richCanonDescriptorFragments('place', p));
const head = p.name ? `${p.name}:` : '';
return [head, body].filter(Boolean).join(' ');
})
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 3262a99979..5581a89384 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -30,7 +30,7 @@ import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir, resolveImageRef } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
-import { richCanonDescriptorFragments } from '../lib/canonPrompt.js';
+import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../lib/canonPrompt.js';
import {
sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,
SERVER_OWNED_CHARACTER_FIELDS,
@@ -1439,9 +1439,7 @@ export function synthesizeCanonPrompt(kind, entry) {
? entry.slugline.trim()
: '';
const identifier = name || sluglineId;
- const body = richCanonDescriptorFragments(kind, entry)
- .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
- .join('. ');
+ const body = flattenCanonDescriptorFragments(richCanonDescriptorFragments(kind, entry));
if (identifier && body) return `${identifier} — ${body}`;
return identifier || body;
}