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

151 KB
Raw Blame

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/.

One pure module, one definition. When the browser and the server need the same pure logic, the client imports the server/lib leaf — export { a, b } from '../../../server/lib/x.js' — it does not copy it. Import the LEAF, never server/lib/index.js, and never the other direction: nothing under server/ may import from client/, because a client-only dependency added to such a file breaks the server CI job. A server module the client imports must reach no Node built-in and nothing outside server/lib; when the natural home does (storyBible.js pulls crypto), split the pure part into its own leaf — or, when the only impurity is an id the browser never mints, take it from uuid.js, which reads the global WebCrypto and so keeps the leaf importable (browser code mints through client/src/lib/uuid.js). scripts/client-server-import-purity.test.js and scripts/server-imports-no-client.test.js enforce both halves.

Discovery rule

grep -i "what you want to do" client/src/lib/README.md

| navFeatures.js | filterNavByFeatures(navEntries, isFeatureEnabled) — drops nav-manifest entries whose optional instance feature (post, datadog, jira, gsd) is off. The single gate for BROWSE surfaces (sidebar, ⌘K); routes stay reachable by URL, bookmark, and voice. Pair with useInstanceFeatures. | | pageNavTabs.js | buildPageNavTabs(manifestTabs, presentation, pageName) — merges getPageNavTabs(group) (nav-manifest, owns id/label/order) with a page-owned presentation map (icon, layout flags), throwing at import time when a manifest tab has no entry. buildSectionNavTabs(sectionTabs, presentation, section) does the same for getSectionNavTabs(section), resolving icons by path out of NAV_PRESENTATION. The one way a tabbed page or section builds its tab bar. | | eidoverseDraftReconcile.js | Pure three-way merge of the Eidoverse world-config drafts (recipe, asset overrides, label aliases) with a server response, plus the single shouldReplaceDraft rule for when a response may overwrite the draft. | | eidoverseFrame.js | Versioned hosted Eidoverse message guards, exact section navigation allowlist, and browser label preferences. | | eidoverseWorldReset.js | Client reset-reconciliation maps for Eidoverse source kinds and district asset slots; parity-tested against the authoritative server world-design contracts. | | postQuickSession.js | Pure Quick POST duration presets, local-observation estimator, deterministic budget composer, and preview metadata. | | postRotation.js | Re-export of server/lib/postRotation.js — orderByRecencyRotation sorts POST practice candidates fresh-before-recently-practiced, then by priority, rotating equivalent ones by local day. | | perpetualSkipCauses.js | Re-export of server/lib/perpetualSkipCauses.js — formatSkipCauses(skipCauses, maxCauses?, excludeCause?) renders a perpetual work-detector's per-cause skip map ({ 'needs-input': 49, blocked: 17 }) as a compact largest-first string; used by the on-demand "Run" toast and the work-item picker. |


Prompt & rendering

Module Purpose
canonPrompt.js Re-export of server/lib/canonPrompt.js. SHORT/RICH/PREVIEW spec + flattenCanonDescriptorFragments / mapCanonDescriptorFragments / descriptorForCanonEntry. Named exports only, so the server-only flatten* helpers stay out of the client barrel.
scenePrompt.js Re-export of server/lib/scenePrompt.js. Scene-prompt composer + bible matchers.
composeStyledPrompt.js composeStyledPrompt re-exported from server/lib/composeStyledPrompt.js (accepts a single preset or an array). composeCanonStyledPrompt (client-only) builds the "<name>: <description>" + universe-preset render the canon section and characters step share.
cleanPlatePrompt.js Clean-plate prompt builder for setting canon entries (Cluster A — A4).
personaTraitBlend.js Re-export of server/lib/personaTraitBlend.js. Digital-twin persona trait-blending (M34 P7) — describeTraitAdjustments / renderTraitBlendDirective / BIG_FIVE_LEAN for the Personas UI preview.
seasonStructure.js Re-export of server/lib/seasonStructure.js.
styleSourceChoice.js BOARD_FOLLOW_UNIVERSE / BOARD_NONE — the mood-board choice sentinels shared by the universe/mood-board style pickers (Code Animation, Creative Commissions).
squarifyTreemap.js squarifyTreemap(items, width, height, getValue?) — squarified treemap layout; returns { item, x, y, w, h } tiles whose areas are proportional to each item's value. Drives the Data Manager disk-usage map.
sheetPointers.js Re-exports the shared browser-safe character-sheet pointer helpers from server/lib/sheetPointers.js. LEGACY_SHEET_VARIANT_ID + readSheetPointer / listSheetPointers / applySheetPointer for traversing both the legacy referenceSheetImageRef field and the referenceSheets map.
shotContinuity.js The storyboards / episode-video stages' INLINE pre-render continuity warnings (#1468). findAxisReversals / findShotTypeMonotony are re-exported from server/lib/editorial/shotContinuity.js, the same detectors the authoritative visual.shot-continuity check runs; sceneShotWarnings(scene, opts) is the client-only composer (the server emits findings in a different shape). Pure/DOM-free.
shotGrammar.js Storyboard shot-grammar display labels. SHOT_TYPES / SCREEN_DIRECTIONS are re-exported from server/lib/shotGrammar.js, so a hand-set value in the editor always passes storyboardShotSchema; SHOT_TYPE_LABELS / SCREEN_DIRECTION_LABELS are the client-only selects (#1468).
untrustedContentSources.js Untrusted-content source display labels. UNTRUSTED_CONTENT_SOURCES / PRIVATE_UNTRUSTED_CONTENT_SOURCES are re-exported from server/lib/untrustedContentSources.js, so the Abuse Guard panel always offers every source the server screens; UNTRUSTED_CONTENT_SOURCE_LABELS is the client-only select (#7680).
universeStylePreset.js universeStylePreset(universe, series) re-exported from server/lib/universeVisualStyle.js, plus withUniverseLabel(preset) (names it "Universe style" for the prompt-addition chips) — the style preset composeStyledPrompt layers on top, shared with the FableLoom visual-canon compiler so a series style override composes identically on both sides (#8442).
universeRunTag.js buildUniverseSectionRenderTag(universe, kindKey, entry) — the durable universeRun job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to generateImage so the server auto-files the render into the universe collection AND appends it to the entry's imageRefs[] (no client follow-up PATCH).
autopilotMilestones.js Series-Autopilot milestone map. buildAutopilotMilestones(plan, progress, {terminal}) folds the run's projected plan (the start frame) and its live progress snapshot (progress frames / the status route) into ordered rows with a MILESTONE_STATUS each — a furthest-index cursor, so a gate the run revisits can't un-finish the milestones after it; summarizeAutopilotMilestones(rows) rolls them into the header meter (a settled-but-unstepped milestone counts as complete); describeAutopilotVerification(kind, verification) renders what a gate actually validated — shared with the panel's frameLabel, since the milestone row and the activity log render the same telemetry; isStoppedTerminal(terminal) is the one definition of "the run stopped mid-plan"; autopilotMarkerTerminal(status) translates a persisted autopilot.status into the terminal frame type the fold reads, so a map rebuilt from the marker after a reload (#4140) flags the step a paused run stopped on. Also owns AUTOPILOT_STEP_LABELS / autopilotStepLabel(kind), the one set of human labels for conductor step kinds (shared by the map and the panel's live status line). Used by components/pipeline/AutopilotMilestones.jsx + AutopilotPanel.jsx.
beeperMessageBody.js Beeper message bodies: decodeHtmlEntities (the five predefined entities plus &nbsp;, using the shared server/lib/xmlEntities.js decoder), looksLikeHtmlBody, parseMessageBody(body) → blocks of marked spans (p/div/br/blockquote/strong/b/em/i/a[href], null when the body carries none of them) and messagePreviewText(body) for the one-line rail row. Some networks deliver HTML (Discord, Matrix) and the mirror stores it verbatim, so the thread and the preview parse it into a data model and render React elements — never dangerouslySetInnerHTML; a non-http(s) href degrades to plain text.
backupExcludes.js CLIENT MIRROR of the backup-exclude block in server/lib/sharedSchemas.js (#7241) — anchorUserExclude / anchorUserExcludes / isSafeExcludePattern / EXCLUDE_PATTERN_MAX_LENGTH. The Backup settings tab anchors a newly added exclude and renders the effective list with these, so the chip the user sees is the rsync filter the server will actually run instead of an unanchored pattern that matches at any depth.
beatColors.js BEAT_KIND_COLORS + getBeatKindColor(kind) — per-kind display colors for reader-map emotional beats (kinds defined server-side in storyArc.js). Keeps every beat visualization consistent.
beatGrid.js Music-video beat-quantized timeline arranger (#1854). buildBeatGridPoints(audioAnalysis) merges beats/downbeats/section edges into one ranked snap-point list; snapTimeToGrid(timeSec, gridPoints, toleranceSec) finds the nearest point within tolerance; computeSceneSpans(scenes, durationSec) lays out scenes without a persisted startSec/endSec contiguously as a display-only fallback; computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...}) resolves a timeline drag gesture ('move' or 'right' — no 'left', since the render can only trim from a clip's own frame 0) into a new span; shouldMarkBeatAligned({kind, snapped, wasPersisted}) gates the beatAligned flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; autoArrangeScenes(scenes, audioAnalysis) proposes a full { sceneId, startSec, endSec, beatAligned }[] arrangement by distributing scenes across song sections weighted by each section's energy (#1915). Used by components/musicVideo/BeatTimeline.jsx and pages/MusicVideo.jsx.
musicVideoAspect.js Re-export of server/lib/musicVideoAspect.js: musicVideoAspect, musicVideoFrameGenSize, matchesMusicVideoAspect. Used by hooks/useMusicVideoSceneMedia.js so board frames match the project aspect.
musicVideoFiling.js Which music video an Image Gen / Video Gen render is for: MUSIC_VIDEO_FILING_PARAM (the musicVideo URL param), musicVideoFilingFields(searchParams) (the musicVideoProjectId request field), musicVideoOf(item) (a record's video). Used by components/media/MusicVideoFilingSelect.jsx, hooks/useMediaPreviewActions.js and the two generate pages.
musicVideoMotion.js Re-export of server/lib/musicVideoMotion.js (MOTION_CONTINUITY_CLAUSE, AUDIO_REACTIVE_PERFORMANCE_GUARD, silentMotionPrompt) for board motion prompts.
musicVideoBatchPlan.js Pure helpers for the Music Video missing-frame / missing-clip batches (#10153): videoBatchPreview (count + fal estimate summed from falSceneTake, unpriced count), scenesWaitingForFrame, videosButtonLabel, batchSummary, batchActive, batchSceneName. Used by components/musicVideo/ProjectActionGroups.jsx.
musicVideoLayers.js Music-video per-scene visual layers (#8985), re-exported from server/lib/musicVideoLayers.js: MUSIC_VIDEO_VISUAL_LAYERS, MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_TEXT_ZONES / MUSIC_VIDEO_LYRIC_ROLES (#10583 lyric type per shot), sceneVisualLayer(scene, { layered }), sceneHasAuthoredSpan, sceneRenderReady(scene, { layered }), and a footage shot's hand-set clip speed, offset and reverse (clipSpeedRate, clipOffsetSec, clipReversed). stillFrameTransform(scene, songTime, { fps, startSec, endSec }) gives the animatic the composed render's frame-clamped push/pan transform (explicit Move before planned camera). Used by components/musicVideo/SceneCard.jsx, StoryboardAnimatic.jsx, ProjectActionGroups.jsx and hooks/useMusicVideoSceneMedia.js. clipPlaybackWindow(scene, edit, duration) / clipLoops / clipCanLoop share source timing and loop eligibility; clipNeedsMoreFootage and COVERAGE_TOLERANCE_SEC keep held-clip coverage identical in the card and render preflight.
musicVideoTakes.js Music-video scene takes view helpers (#8965): sceneTakeList(scene, kind) lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only legacy take; takePreviewKey, takeThumbUrl, takeClipUrl (hover-preview clip), sceneHasPendingDecision (contact-sheet filter), takeProvenance; TAKE_SLOT maps a take kind to its selection field. Used by components/musicVideo/SceneTakeStrip.jsx and pages/MusicVideo.jsx.
musicVideoSceneAttention.js Music Video per-scene attention model (#10152): sceneAttention(scene, ctx) returns the codes (missing-frame, missing-clip, under-covered, contract-problem, perf-blocked, candidates-pending, plate-unverified, no-span, last-failure) behind the collapsed scene-row chips, the Board ?scenes=attention|missing|all filter (parseSceneFilter, sceneMatchesFilter) and the Produce per-shot strip; SCENE_ATTENTION_LABELS; sceneMediaKind (clip / image / code / card) and SCENE_MEDIA_LABELS for the Board thumbnail badges. Used by components/musicVideo/SceneCard.jsx, stages/BoardStage.jsx and stages/ProduceStage.jsx.
musicVideoCoverOverlay.js Cover-art lettering preview (#10345): re-export of server/lib/musicVideoCoverOverlay.js (the design vocabulary, normalizeCoverDesign, coverOverlaySvg) plus canvasCoverWidths(design, texts, fonts), which measures text with a canvas so the live preview wraps and sizes the title the way the server's measured render does.
musicVideoSceneTiming.js buildSceneTimingPresentation: pure provider timing, cost, coverage and split/merge projection for the Music Video scene card, reusing canonical shot-timing policy.
musicVideoShotTiming.js Re-export of server/lib/musicVideoShotTiming.js (#8977) — shot modes and performance styles, the verified source-audio lip-sync and music-driven capability tables, performanceBlockedReason, planPerformanceRepair (measured accepted-prefix boundary, suffix interval and next spend), planPerformanceWindow, grokCoverage, approximateMotionCues, shotSplitLimit (when a scene offers a lyric-boundary split), falSceneTake (a fal take's model, length, resolution and estimated cost). clipAudioOffsetSec (how far into an aligned take's clip its audio window starts, #11210). Used by hooks/useMusicVideoSceneMedia.js and components/musicVideo/SceneCard.jsx.
musicVideoStages.js Music Video page stage model: MUSIC_VIDEO_STAGES (six steps: Song setup → Look cast-sets → Storyboard board → Make produce → Final render review → Publish; a retired compose link resolves to Make), resolveStageParam(value) for the :stage route param, deriveStages(project) (per-stage done/active/blocked/todo + current, the first incomplete step; a live production run pins Make), deriveNextAction(project, ctx) (the one primary action the sticky header offers — approve Cast & Sets, verify lyric timing, stop/resume production, render final, …), describeProjectStatus (the header line and the step that needs the director), autopilotStatus (the header Autopilot button), projectSpend(project) (paid generation used vs. cap), projectShotSummary(project) (document shots or scene counts), stageChecklist(stageId, project, readiness) (what one step still needs, with the open approval's reason and a scroll anchor; an optional item, such as Make's animated proof, is listed but not counted), summarizeStoryboardProblems(problems) (folds the server's one-sentence-per-shot storyboard problems into one count line per kind), stepNotes(project, readiness, publish) (one fact per step for the step list), listPreviewSources (final, live composition, drafts, then the storyboard animatic), projectServicesSummary(project) (the saved image/video render services), compareMusicVideoProjectsNewestFirst(a, b) (sort projects newest created / updated first for project cards and pickers), and currentProductionRun; productionReviewStopGuidance separates current approval blockers from historical run stops. Used by components/musicVideo/MusicVideoLayout.jsx and pages/MusicVideo.jsx. projectFalSpend(project) (estimated fal.ai and Runway spend by model across paid takes and production steps).
musicVideoAttention.js Music Video "Needs attention" model (#9940): deriveAttentionItems(project, live) returns the banner rows for server-held states a client-orchestrated workflow can strand — an open/rendering revision, an interrupted Cast & Sets stage, a running auto-review waiting on its revised sections, a final render nobody is watching — derived from the persisted record so they survive a reload (healthy work this tab can see progressing is not flagged); openRevisionOf(project); ATTENTION_ANCHOR_ID + revealAttention() scroll a refusal toast to the banner. Used by components/musicVideo/NeedsAttentionBanner.jsx and pages/MusicVideo.jsx.
musicVideoProjectList.js Music Video project index model (#10167): projectRunPill(project) (Running / Needs you / Interrupted / Done, from the same next-action and attention logic as the header), groupMusicVideoProjects(projects, query) (collapse forks under their root, newest version first, name filter, groups ordered by last touch), and compareMusicVideoProjectsRecentlyTouched. Used by pages/MusicVideo.jsx and components/musicVideo/MusicVideoProjectCard.jsx.
musicVideoPreview.js Pick the representative produced asset for a Music Video project card (selectMusicVideoPreview: final video → latest excerpt → latest rendered scene clip → latest scene reference frame → visual spec reference) for the main project grid. Pure, computed off the project record, with image path and fallback helpers (musicVideoImageSrc, musicVideoImageFallback, scenePosterSrc: a scene's frame or its clip's poster).
musicVideoUniverseRefs.js pullUniverseCanonReferences(universe, existingReferences) (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at MUSIC_VIDEO_MAX_REFERENCES (24, mirrors the server schema). Returns { next, added, skipped }; the caller persists next via the ordinary visualSpec PATCH. Used by components/musicVideo/VisualSpecPanel.jsx. (The style snapshots are derived server-side, #9105.)
musicVideoAutonomous.js Fully-autonomous Music Video, client half: re-exports the server stage vocabulary (AUTONOMOUS_STAGES, checkpoint ids, default tools/limits, autonomousMedium), the status/checkpoint labels, and owns the start form's emptyAutonomousDraft / autonomousRequestFromDraft mapping (including the Suno form options and isSunoModelValid) plus autonomousStageRows(run) and isAutonomousLive(run) for the run panel, and autopilotDraftFromParams / autopilotParamsFromDraft for the music-video-autopilot Schedule settings form.
musicVideoAutomation.js Music Video automation brief, client half: re-exports the server tool catalog (MUSIC_VIDEO_AUTOMATION_TOOLS / _TOOL_IDS), DEFAULT_AUTOMATION_TOOLS (the unmetered tools), and the form mapping automationDraftFrom(automation) / automationFromDraft(draft) (empty budget = no cap; the direction-LLM pin rides as llm, absent = Auto), plus llmRouteLabel(route) for the stage-route summary. Used by the create drawer and AutopilotPanel.
bibleLimits.js BIBLE_LIMITS re-exported from the pure leaf server/lib/bibleLimits.js, plus the client-only capImageRefs / appendImageRefById for the optimistic imageRefs-append paths.
characterEvolution.js The five-stage character evolution lens as the editors consume it. Re-exports EVOLUTION_STAGES / EVOLUTION_OUTCOMES / EVOLUTION_STAGE_LABELS / EVOLUTION_STAGE_TEXT_FIELDS / EVOLUTION_EVIDENCE_FIELDS / EVOLUTION_EVIDENCE_STATUSES / CHARACTER_EVOLUTION_LIMITS / evolutionEvidenceStatus / isDeclaredEvolution from the pure leaf server/lib/characterEvolution.js (a guard in server/lib/characterEvolution.test.js fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors EVOLUTION_STAGE_EDITOR_FIELDS / EVOLUTION_OUTCOME_HINTS (#6440), and the draft-mutation helpers evolutionStage / patchEvolution / patchEvolutionStage / patchEvolutionEvidence that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441).
characterFramework.js The narrative-character framework as the editors consume it. Re-exports CHARACTER_ARC_TYPES / CHARACTER_FRAMEWORK_FIELDS / CHARACTER_FRAMEWORK_TEXT_FIELDS / CHARACTER_FRAMEWORK_LIMITS / CHARACTER_PSYCHOLOGY_LIMITS / CHARACTER_SLIDER_AXES / PSYCHOLOGY_ASSESSMENTS / PSYCHOLOGY_DRIVE_AXES / RELATIONSHIP_LINK_TYPES from the pure leaf server/lib/characterFramework.js, and adds the editor descriptors CHARACTER_FRAMEWORK_EDITOR_FIELDS (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), CHARACTER_MOTIVATIONS_FIELD, CHARACTER_SECRETS_FIELD, CHARACTER_PSYCHOLOGY_EDITOR_FIELDS / CHARACTER_PSYCHOLOGY_NOTE_FIELD / CHARACTER_PSYCHOLOGY_DRIVE_HINTS (#6414), and CHARACTER_SLIDER_MIN / CHARACTER_SLIDER_MAX. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417).
characterIntegrity.js Display half of the cast-integrity contract (#6415) — re-exports the finding kinds, review statuses, depths, dimensions and castIntegrityPassed from server/lib/characterIntegrityVocabulary.js, plus the client-only FINDING_KIND_META / REVIEW_STATUS_META / DEPTH_META badge copy and DIMENSION_LABELS (read off the server's dimension table), findingIsRepairable (which gates the Augment button off contradictory findings), incompleteCoverage and humanizeIntegrityField (a dotted field path rendered for a reader). characterIntegrity.test.js checks the tables cover every value the server can emit.
catalogForms.js Alternate forms of a cast record (other ages, eras, looks/styles; payload.forms): newFormId, formsOf(payload), formAgeField(type) / formAgeLabel(type) (the canonical form's age/era field), and splitSheetRole(role) for sheet:<variant>@<formId>.
catalogTypes.js The catalog ingredient type registry as the UI consumes it. CATALOG_TYPES is PROJECTED from server/lib/catalogTypes.js (label, badge color, primary-content key/label, snippet fallback chain, editableListFields and its BIBLE_LIMITS caps) and decorated with the client-only editor layout (editorSections / editorFields); RELATION_KINDS, MEDIA_KINDS, canonicalTagKey, payloadSnippet, USER_TYPE_FIELD_KINDS are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization useCatalogTypes merges in.
creativeDirectorPlan.js Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate plan.steps[] with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps.
creativeDirectorPreview.js selectProjectPreview(project) → { kind: 'video'|'image'|'audio'|'none', jobId?, src?, poster?, label, durationSec? } — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → musicBed audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus previewAspectClass(aspectRatio) (literal Tailwind classes — a computed aspect-[w/h] never lands in the build), startingImageSrc() (client mirror of localImageFilename), and the videoSrcForJob/videoPosterForJob/imageSrcForJob/musicBedSrc path builders — the one client-side definition of the <jobId>-named asset convention, shared with ScenePreview.jsx.
creativeDirectorStatus.js describeCreativeDirectorStatus(project, { activeAgents, activeTab }) → { headline, tone, facts, next } — the one "where it stands, what's next" status line for a CD project (stage in words, whether it waits on the user, a single start/resume/edit-draft/goto/open-final next action). Pure; rendered by components/ui/RecordStatusLine.
creativeLibraries.js CREATIVE_LIBRARIES — the Casting / Environments / Objects pages as views over the catalog's character / place / object ingredients, with libraryById / libraryForType / libraryForPathname, ingredientPath(ingredient) (library detail route, else /catalog/:type/:id), ingredientCoverUrl(ingredient) (attached media, else the canon starred/first render, both under /data/images) usageSummary(usage) ("1 universe · 2 videos" from the list endpoint's link counts), per-library detailTabs with resolveDetailTab / detailTabPath (record page sections at /casting/:id/:tab), and media-role predicates isSheetMedia / isPlateMedia / isReferenceTabMedia(m, liveLookIds?) (sheet:*, plate, look:*; a look whose wardrobe is gone counts as a reference) and lookIdOf(m).
editorialRoadmap.js projectAnalyzedPoints (aggregate roadmap → analyzed chart points with arc-position frac) + dominant (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page.
federatedMediaReadiness.js One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. resolvePeerMediaReadiness(peer, { now }) maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives stale when the snapshot’s freshUntil has passed, so a snapshot probed as ready cannot keep reading ready after the server would refuse to submit against it. Also exports FEDERATED_MEDIA_KINDS (audio/image/video + their config fields and icons), the state/help tables, and peerMediaProviderConfig. summarizePeerMediaQueue(queue) renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. federatedMediaModelsForPeer(peer, kind) intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their ready / unavailableReason), so no surface can offer a model the server would refuse or hide why a listed one cannot run. federatedMediaSupports(status, feature, capability) mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (lyrics, inputAssets) from the status-root features list, retaining only the legacy inputAssets capability block for peers on the previous build because that signal is genuinely per-model, and peerMediaProviderSnapshot(peer) returns the status payload to ask it against. peerModelAcceptsInput(capability, role, status) / peerModelRequiresInput(capability) read the capability’s inputAssets block — which conditioning slots (initImage / referenceImages / sourceImage / lastImage) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with absent reading as NO, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves.
fableLoomReadiness.js Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting.
glbFailure.js Turns a 3D asset failure into an actionable sentence. glbFailureHint(error) matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns null when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. glbErrorText(error) reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by media/GlbViewer.jsx and cos/CoSCanvasGuard.jsx.
grokVideoClip.js Re-export of server/lib/grokVideoClip.js — GROK_VIDEO_DURATIONS ([6, 10, 15]) + GROK_VIDEO_DEFAULT_DURATION, the clip lengths grok's image_to_video actually delivers.
reactorVideoClip.js Re-export of server/lib/reactorVideoClip.js — REACTOR_MAX_PROMPT_LENGTH (800, counted in the VideoGen prompt field before submit), REACTOR_MIN_CLIP_SECONDS / REACTOR_MAX_CLIP_SECONDS, the picker list REACTOR_CLIP_LENGTHS + REACTOR_DEFAULT_CLIP_LENGTH + reactorClipLengthLabel(), and the canvas contract REACTOR_CANVASES / REACTOR_ASPECTS / REACTOR_DEFAULT_ASPECT / reactorCanvas() / nearestReactorAspect().
runwayVideoModels.js Re-export of server/lib/runwayVideoModels.js — the curated Runway video model catalog, per-model request rules and estimateRunwayVideoCostUsd(). Used by the Music Video Runway pickers and the Video Gen page's Runway backend.
imageThumbnailSrc.js imageThumbnailSrc(src) maps a gallery PNG (/data/images/x.png) to its on-demand 512px WebP (/data/image-thumbnails/x.webp), else null; used by catalog cards and inline catalog previews so lists don't pull multi-MB originals.
imageCleaners.js Re-exports resolveCleanersFromConfig from the shared pure server/lib/imageCleanDefaults.js policy. Reads {cleanC2PA, denoise} off a per-mode settings record. cleanC2PA defaults are mode-aware (on for codex + external — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); denoise defaults off everywhere (lossy, opt-in only).
reviewerModels.js reviewerModelsFromDefaults / reviewerModelsToDefaults / reviewerEffortsFromDefaults / reviewerEffortsToDefaults — adapt the Code Review Defaults' per-reviewer SCALARS (codexModel, ollamaModel, claudeEffort, …) to and from the token-keyed maps ReviewerPicker's Model and Effort columns take. Mirrors reviewerModelsFromDefaults / reviewerEffortsFromDefaults in server/lib/reviewerConfig.js. Also preserves configured-provider model and effort pins in the additive providerModels / providerEfforts maps, keyed by provider:<id>; empty maps clear overrides without changing builtin scalars.
reviewerPins.js Client mirror of the whole reviewer vocabulary — the roster (REVIEWER_VALUES), REVIEWER_ALIASES, DEFAULT_REVIEWER(S), normalizeReviewers, the review-username pattern/cap (MAX_REVIEW_USERNAMES / cleanReviewUsername / normalizeReviewUsernames), MAX_REVIEWER_MAX_ROUNDS, REVIEW_STOP_MODES / DEFAULT_REVIEW_STOP_MODE, plus the per-reviewer pin vocabularies (MODEL_SELECTABLE_REVIEWERS / EFFORT_SELECTABLE_REVIEWERS / REVIEWER_EFFORT_LEVELS / reviewerEffortLevels / normalizeReviewerSlug / sanitizeReviewerModelInput) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against server/lib/reviewerConfig.js, so it must not reach for a client-only package. Re-exported by components/cos/constants.js. isProviderReviewer recognizes the shared provider:<id> identity alongside legacy harness slugs.
loraEffect.js How the LoRA manager card renders an adapter-effect measurement (#4872). LORA_EFFECT_STATUSES is re-exported from server/lib/loraEffect.js; LORA_EFFECT_BADGES + loraEffectBadge(status) (only zero is styled as an error, because only zero refuses a render server-side) and loraEffectDetail(report) are client-only — the detail line returns null when the badge already says everything, where the server's formatLoraEffect always returns a sentence for its log.
loraTriggers.js The picker's + trigger append (#4665). firstTriggerWord / promptHasTriggerWord / separatorFor are re-exported from server/lib/loraTriggers.js, so the hint reads the rule the render enforces. appendTriggerWords(prompt, words, effectivePrompt?) is client-only: it adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit.
runnerFamilies.js Mirror of server/lib/runners.js, including the shared LTX + MiniMax H3 Ref2VA audio-to-video runtime predicate; loraCompatKeysMatch keeps image Test handoffs and the adapter picker on the same size/family compatibility rule.
selectorTestFailureTask.js Build the CoS task payload behind the DOM-selector-test "Investigate & fix" action (Settings > Messages > Sync tab): buildSelectorTestFailureTask({ provider, status, results, error }) → { description, prompt } naming the provider, the testSelectors() status, the per-selector match counts, and the relevant source files. Fed to the generic QueueInvestigationButton (components/ui/QueueInvestigationButton.jsx), the same queueing primitive installFailureTask.js uses.
slashdoCatalog.js The Agent Operations buttons. SLASHDO_WORKFLOWS is server/lib/slashdoCatalog.js's list decorated with a per-command Tailwind tone, and slashdoWorkflowsForApp(isSwiftApp) filters it through the server's own slashdoWorkflowAppliesTo — so the panel cannot be a workflow short. SLASHDO_NAMESPACE + slashdoLabel(command) (the /do:x UI spelling) stay local: the server module that owns the namespace reaches for the provider registry.
isSafeHref.js Pure http(s)-only scheme check (isSafeHref) for user-supplied URL fields rendered as a clickable <a href> — rejects javascript:/data:/etc. stored-XSS payloads. Re-exported from server/lib/isSafeHref.js; utils/urlNormalize.js re-exports it again as isHttpUrl.
issueLength.js The Length Profile picker's helpers. LENGTH_PROFILES, DEFAULT_LENGTH_PROFILE and the CUSTOM_* bounds are re-exported from server/lib/issueLength.js (the same profiles the server computes targets from); clampInt and summarizeLengthProfile are client-only form/display helpers.
issueRefs.js Bare forge issue references (#7640) in rendered markdown. splitIssueRefs(text, issueUrlBase) splits literal text into strings and { ref, url } segments; agentIssueLinkifier(agent) is the linkifyText resolver for one CoS run, reading the tracker base the server stamped at spawn (agent.metadata.repoIssueUrl, built by server/lib/workTracker.js#repoIssueUrlBase). Holds NO forge knowledge — it appends a number to a base the server already shaped — and declines a qualified owner/repo#7640, which that base cannot retarget. Render-time only: nothing is rewritten on disk, so a run from before the stamp renders plain text.
musicDuration.js Lyric-aware MiniMax Music 3 duration analysis: section/word detection, ending-cushioned auto-duration recommendations, and cap warnings. Mirrors server/lib/musicDuration.js.

Pipeline / image-gen defaults

Module Purpose
pipelineImageDefaults.js Pipeline comic-page image-gen defaults + settings reader.
pipelineIssueStatus.js describePipelineIssueStatus(issue, { stages, labels, autoRunActive, latest, activeStage }) → { headline, tone, facts, next } — the pipeline issue's status line (failed / generating / needs-review / next-empty stage, or the live auto-run frame in words) with the one next action. Pure; rendered by components/ui/RecordStatusLine.
reverseOutlineGrid.js buildPlotlineGrid (reverse-outline scenes + plotlines → plotline-by-sequence grid rows/cells) + sceneComponentCount. Used by the Reverse Outline page.
wrImageDefaults.js Writers Room per-scene image-gen defaults + style discriminators.
imageGenBackends.js Icon metadata, deriveAvailableBackends, isLocalImageConfigured(local) (Python or a native MOSS pin), and imageGenReadiness(status) — a compatibility-safe ready / unavailable / unknown read of image-gen status responses; re-exports everything from imageGenModes.js so consumers keep one import site.
imageGenModes.js Node-safe image/video backend constants + pure helpers. Re-exports the backend / render-target / lane alphabets from the server leaves server/lib/generationModes.js + server/lib/renderTargets.js (see its header for why nothing is copied); adds the Settings rows (RENDER_TARGET_OPTIONS), applyRecordRenderPin (fold a record's imageMode/imageModelId pin over a settings-derived cfg), isCloudCliMode/isCloudVideoMode, modeLabel, mediaJobLane (a projected media job's scheduler lane, re-derived for responses predating the server's executionLane field), and the cloud/model-override/i2i capability mirrors of the server service specs. Imported by the server-side parity suite — must stay importable without client packages.
decks.js Deck alphabet, card roster/status/completion rules, face-orientation defaults/prompts, render-prompt composition, and deckCardSize / deckCardAspectStyle (thumbnail box from the deck's trim) — re-exported from server/lib/deckTemplates.js (one definition, no client copy).
imageGenResolutions.js Shared resolution presets for image generation.
imageTo3dReasons.js Client mirror of the image-to-3D unavailable-reason labels in server/services/imageTo3d/targets.js: UNAVAILABLE_REASONS (reason code → user-facing label), UNAVAILABLE_REASON_FALLBACK, and unavailableReasonLabel(code, fallback?), plus isTargetReady(target) — the shared readiness predicate (installed is tri-state: null = a hosted lane with no install concept, ready as soon as it is available). Use these anywhere a target's unavailableReason or readiness is rendered — never re-declare the codes or re-derive readiness from target.installed truthiness. Parity + code coverage enforced by server/services/imageTo3d/unavailableReasons.parity.test.js.
imageTo3dTargetFixture.js imageTo3dTarget(overrides) — one representative image-to-3D target descriptor for tests. Shared by the /3d and Models → 3D suites so a server-side descriptor change is one edit, not two fixtures that can half-update.
imageTo3dRenderOptions.js Image-to-3D per-run render options — the client mirror of the server bounds (SEED_MAX), the STEPS_PRESETS / DETAIL_PRESETS / ALPHA_MODE_PRESETS select options, renderOptionsBody (fields → API body), fieldsFromRun (carry-over from the last run), and runWantsTransparency (mirrors the server's alpha gating — the viewer's force-opaque pass must agree with it). Pinned by renderOptions.parity.test.js.
importerDeepLink.js The Importer deep-link contract both ways: buildImporterLink({ universeId, seriesId, seriesName }) builds the /importer?… URL a Series Pipeline page navigates to; resolveImporterDeepLink(...) reads those params back into the universe + series names the importer matches on.
muscriptorModels.js MUSCRIPTOR_MODELS (audio → MIDI size tiers small/medium/large) + DEFAULT_MUSCRIPTOR_MODEL. Single source consumed by the transcribe <select>s in MusicVideo.jsx and ReferenceAnalysis.jsx. Mirrors the server's MUSCRIPTOR_MODELS in server/services/audioMidiTranscription.js.
videoFinish.js Finish-a-draft gate (#3696). isReproducibleTextToVideo(record) is true only for a single text-to-video render whose history record already carries everything a re-render needs — renderInputsVersion (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty conditioning array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. finishTargetForRecord(record, models) additionally resolves the draft model's server-declared finishModelId against the models this install can actually run, returning the delivery model entry or null. isDeliveryVideoModel(model, models) is the other end of the same graph — true when some entry names model as its finishModelId, which is what makes a delivery render always decode on the full decoder (#5423). Mirrors finishTargetForModel / isDeliveryVideoModel in server/lib/videoFinishProfiles.js; the pair table itself stays server-side.
videoGenEnqueuePolicy.js videoGenEnqueuePolicy(ctx) — the single enqueue decision for Video Gen's Generate button, "Add to queue" button and Options caption. One ordered row table scoped always/remote/local; an off-machine render (Grok, fal.ai, reactor.inc) skips every local row. Returns { canEnqueue, generateTitle, queueTitle, optionsHint }.
videoGenParams.js Pure VideoGen param helpers: FRAME_OPTIONS/FPS_OPTIONS/VIDEO_EDGE_BOUNDS/MAX_CHUNKS/CHUNK_OPTIONS/DEFAULT_CONTEXT_FRAMES/CONTEXT_FRAME_OPTIONS constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, supportsContextWindow(model) (does this runtime have an extend pipeline to feed a continuation window to — display mirror of server/lib/videoContinuity.js, pinned by server/lib/videoContinuity.parity.test.js), videoModelMemoryGb() (model memory footprint), selectVideoMemoryProfile(model, systemMemoryGb) + VIDEO_MEMORY_RESERVE_GB (#5420 — which declared weight-placement profile this machine can actually hold, out of the memoryProfiles the server decorates onto the entry; the floors ride on the model so only the reserve is mirrored, and an unmeasured systemMemoryGb returns a null usable figure rather than reading as a box that is too small), computeFflfSafeFrames() (FFLF/ltx2 pixel-budget back-solve, mirrors server/services/videoGen/local.js), and isModelAllowedForMode() (a2v uses the shared audio-runtime capability; IC remix remains LTX-only). Speed profiles (#4875) mirror the conditioner shape: DEFAULT_SPEED_PROFILE_ID (must equal SPEED_PROFILE_DEFAULT_ID in server/lib/videoSpeedProfiles.js — absence and 'quality' are the same request), isDefaultSpeedProfileId() mirrors the server's absence-is-the-default rule, speedProfilesForModel() reads the server-decorated speedProfiles off the entry, speedProfilesForMode(model, mode) applies the SAME mode gate the server's speedProfileDeclineReason does (so a profile the server would decline is never offered, nor allowed to lock the dials), normalizeSpeedProfileForModel() snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), speedProfileIdFromRecord() reads one back out of a history entry / resumed job, selectedSpeedProfile(id, model, mode) resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage }) derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ extend on a window-continuity chain or image on a frame hop), mirroring generateChainedVideo’s dispatch and resolveContinuityStrategy; resolveContextFramesForDisplay() is the absent/invalid→DEFAULT_CONTEXT_FRAMES half of resolveContextFrames that gate depends on. All pinned by server/lib/videoSpeedProfiles.parity.test.js. Also mirrors the IC-LoRA remix registry (IC_LORA_MODES/IC_LORA_MODE_VALUES/isIcLoraMode()/icLoraSpecForMode()/icResolutionIssue()) from server/lib/icLoraWeights.js so the form validates a reference render pre-submit — pinned by server/lib/icLoraWeights.parity.test.js.
videoGenResolutions.js Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and snapAspectToImage() to pick the closest-aspect preset for an I2V source.
videoGenSubmission.js Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels.
videoReferenceModes.js Re-export of server/lib/videoReferenceModes.js — the i2v reference-mode vocabulary and its per-mode rules.
videoStreamingMode.js Re-export of server/lib/videoStreamingMode.js — the block-streaming request vocabulary (auto | resident | stream) for LTX-2/2.5 MLX local video renders (#6499).
videoRenderPhase.js Video render phase → named progress step (#5872). resolveVideoRenderSteps({ generating, phase, progressPct, remote }) → `{ activeId, steps: [{ id, label, state: 'done'
videoTilingOptions.js VIDEO_TILING_OPTIONS (the <select> rows), VIDEO_TILING_ENUM_SET (the value-only Set), and normalizeVideoTiling (omit legacy/unknown values). Single source consumed by VideoGen.jsx, saved-video normalization, and Remix/requeue callers. Mirrors the server's z.enum in server/routes/videoGen.js.

Graph & sim

Module Purpose
brainGraphFocus.js Pure focus-trail (breadcrumb) transitions for BrainGraph re-focus navigation.
graphPicking.js Screen-space touch picking for the 3D brain graph (#4114). projectToScreen(point, viewProjection, width, height) projects a world point to canvas-local pixels (y down, null when the point sits on or behind the camera plane); pickNearestNodeByScreenDistance({ nodes, viewProjection, width, height, point, threshold }) returns the node whose projected centre is nearest the tap within TOUCH_PICK_THRESHOLD_PX (44px — a max-importance sphere only projects to ~38px at OrbitControls minDistance, so a tap anywhere inside a node still lands), tie-broken by depth then array order; isTapGesture(start, end, slop) separates a tap from a drag (TAP_SLOP_PX) — the picking helpers are 3D-only, but this one is the tree-wide movement-slop predicate and takes plain client coordinates, so 2D canvases use it too (fableloom/LoomCanvas.jsx passes its own tighter slop for node drag vs pan). Takes the 16 flattened column-major THREE.Matrix4 elements rather than a camera, so it stays three.js-free and unit-testable — jsdom has no WebGL context and therefore no raycast to exercise.
graphSimulation.js 3D force simulation parameters for BrainGraph / OpenWorld.
goalFeatureMap.js Re-export of server/lib/goalFeatureMap.js — deterministic goal category → PortOS feature-area deep-link map (Daily Driver). getGoalFeatureAreas(goal) honors the per-goal featureAreas override.

Generic UI / collection utilities

Module Purpose
a11yKeyboard.js clickableProps(handler, { role?, disabled? }) → { role, tabIndex, onKeyDown } and onActivateKeyDown(handler) — make a non-<button> element with an onClick keyboard-accessible (Enter/Space activation, focusable, role="button"). Spread clickableProps next to the existing onClick. Use instead of hand-rolling role/tabIndex/onKeyDown on clickable <div>/<span>/<li>. Also the shared predicate every app-global key handler consults: shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? }) — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open aria-modal dialog), used by useKeyboardShortcuts, useKeyCapture AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: isEditableTarget(el), isButtonActivation(event) (true when Space would natively activate the focused button) and isPressKey(event) (Enter or Space by either key or code). Also isFocusEscapeKey(event) — the shared "leave this widget" gesture (Shift+Tab backtab) that a key-capturing widget must release to the browser; the Shell terminal's attachCustomKeyEventHandler consults it so focus can escape the xterm trap. Plus noPointerFocusSurfaceProps — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too.
agentOutcome.js Re-export of server/lib/agentOutcome.js: isAgentHandoff(agent) — result.resumed === true — tells a record retired to hand its task to a continuation, a Resume or a provider Relaunch, from one that reached a verdict, and agentHandoffReason(agent) gives the line such a card should show. Cards reading result.success alone rendered a red "Failed" run for a swap the user made deliberately, and the needs-feedback filter asked them to rate it. Imported rather than copied so the run card and the daily report cannot disagree about whether a swap was a failure. normalizeTaskOutcome validates explicit delivery evidence; isTaskDeliveryComplete admits completed/no-action-needed delivery only, and the server also resolves reported evidence against delivery checks with resolveTaskOutcome.
cosAgentFeedback.js Client mirror of the server-owned CoS feedback eligibility, rating, legacy-update-target, and archive-locator predicates.
agentResumeOutcome.js agentResumeMessage(result, messages, fallback) — the toast wording for a CoS agent resume/relaunch result. The server answers with a mode (what it did to the task) plus spawned/spawnHold (whether it also STARTED it — a resumed task is force-spawned when a slot is free, and spawnHold names the refusal when it isn't). messages is keyed by mode as { queued, running? }; a mode with no running variant is one that deliberately queues nothing, so it can never be reported as started. Shared by the Resume dialog (cos/tabs/AgentsTab.jsx) and cos/tabs/RelaunchAgentModal.jsx so neither can say "queued" for a run that already started, or omit the reason it didn't.
appIdentity.js PORTOS_APP_ID — stable id of the baseline PortOS app. Re-exported from server/lib/appIdentity.js; dependency-free so a module reachable from a server test can import it.
applyManuscriptEdits.js applyEditsToContent(content, edits, anchorQuote) — PREVIEW-ONLY client mirror of the server's accept splice (server/services/pipeline/manuscriptFix.js): locate each find (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview.
avatarStyles.js Re-export of server/lib/avatarStyles.js — the CoS avatar-style vocabulary (#6253): AVATAR_STYLES, AVATAR_STYLE_IDS, AVATAR_STYLE_LABELS, WEBGL_AVATAR_STYLE_IDS. The picker labels, the lazy-load map / WebGL-stage set, and the server's avatarStyle zod enum all read the one list.
assessmentTuningNotice.js tuningNoticeChip(entry) — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. tuningApplied === false covers two opposite cases and tuningKey separates them: a TUNED run whose knobs never reached the daemon (tuning not applied), versus an UNTUNED run PortOS could not put back on backend defaults (not at defaults) — #4759. Shared by ModelThroughputReport.jsx's table cell and LocalModelAssessments.jsx's result toast; the long form is the server's exclusion reason in getAssessmentReport.
callAudioBridge.js Pure device/format helpers for the call-host page (pages/VoiceCallHost.jsx, #5308 + #5311) — shared by its Call mode (FaceTime Audio) and its Capture system audio mode (meeting transcription). missingCallHostApis(scope) lists every required browser API this browser lacks (MediaStreamTrackProcessor/Generator, AudioWorklet, enumerateDevices, setSinkId, Web Locks) so the page names all the gaps at once instead of one per reload; findAudioDevice(devices, label, kind) matches a device label EXACTLY after trim+case-fold (a substring match would resolve "BlackHole 1" to the 16ch device, indistinguishable from a dead call); describeDeviceProblem(devices, {inputLabel, outputLabel}) returns the one blocking message or null, and deliberately blames MICROPHONE PERMISSION rather than a missing driver when every label comes back blank — an ungranted tab enumerates unlabeled devices, and "reinstall BlackHole" would send the user to fix the wrong thing; outputLabel is OPTIONAL — capture mode only listens, so omitting it skips the output-device check entirely rather than reporting a device named "undefined" as missing. Format side: downmixToMono(channels) (BlackHole 16ch carries the call on all channels; truncates to the shortest rather than reading past one), resampleTo16k(samples, fromRate) (linear, 48k→16k for whisper), floatToInt16 (CLAMPED — wrapping would flip a hot sample's sign into an audible click), rmsLevel for the input meter, and buildTestTone (faded in/out so it cannot click through the call). Plus CALL_HOST_LOCK (the Web Lock name that stops a second tab double-answering — shared by both modes, since they read the same physical device) and CALL_FRAME_SAMPLES.
audioRecorder.js startMemoRecording() → { stream, stop, cancel } handle whose stop() resolves to { audioBase64, mimeType, peak, durationMs } (16 kHz mono WAV, base64); the live stream lets a tuner tap the same mic. createStreamAnalyser(stream, { fftSize }) → { analyser, context, close } taps an AnalyserNode off an existing stream (no second getUserMedia). Plus blobToWav16k (decode a recorded blob → { wav, peak }), float32ToWav16k(samples, sourceRate) (resample a raw Float32 PCM buffer, e.g. an AudioWorklet capture, → { wav, peak }; { wav: null, peak: 0 } for empty input), encodePcmToWav, MAX_VOICE_AUDIO_BYTES (8 MiB), RECORDING_TOO_LONG_MESSAGE, TARGET_SAMPLE_RATE (16000), pickRecordingMimeType, arrayBufferToBase64. Shared WAV-encode/resample path for both this standalone memo-capture flow AND the live voice-agent recorder in services/voiceClient.js. openAnalysisMic({ getUserMedia }) → { stream, processing } is the ONE way a pitch-analysis surface opens a mic: it requests ANALYSIS_AUDIO_CONSTRAINTS (echo cancellation / noise suppression / AGC off — plain booleans, never { exact }, so a browser that can't honor one still opens the mic) and reads track.getSettings() back so the UI can say what actually stuck. readAppliedProcessing(stream) reports each stage as true / false / null (browser didn't say — never collapse unknown into off) and hasUnwantedProcessing(p) gates the warning. Memo capture deliberately keeps the speech-tuned defaults; Whisper wants them.
bareUrl.js parseBareUrl(text) — the normalized URL when a capture's entire text is a URL, else null. Re-exported from server/lib/bareUrl.js, the rule the brain-capture route applies.
youtubeUrl.js isYoutubeVideoUrl(text) / youtubeVideoId(url) re-exported from server/lib/youtubeUrl.js, so Quick Capture can only offer the ingest path for a URL the server accepts. Also the client-only INGEST_OPTIONS — the single table of the three ingest artifacts (key / settingKey / fallback / label / hint) — plus defaultIngestOptions() and ingestOptionsFromSettings(settings). Everything that enumerates the switches derives from that table; add an artifact there, not at each call site.
boundedMap.js evictOldest(map, max, onEvict?) — evict oldest-first (map.keys().next().value) until a Map is within max, with an optional per-evicted-key teardown callback for a companion timer map; ORPHAN_BUFFER_MAX (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a jobId → … Map, evict the oldest on overflow" idiom shared by useSceneRenderLifecycle, useImageGenQueue, and clientErrorReporter.
buildStamp.js Does the bundle this browser loaded come from the same git commit the API is running (#4694)? SERVED_BUILD_ID (the server-injected build-id meta tag; null under npm run dev) is the trust gate — BUNDLE_STAMP is the raw __BUILD_STAMP__ Vite define, TRUSTED_BUNDLE_STAMP is it only when the page came from a real build, since the define is frozen at dev-server start while HMR serves every commit since. Display or compare TRUSTED_BUNDLE_STAMP, never BUNDLE_STAMP. compareBuildStamps(bundle, server) → match/mismatch/unknown (absent on either side is always unknown); resolveBuildFrame(signals, {embeddedBuildId}) → reload/drift/null, the two staleness kinds that need different remedies; createBuildDriftWatcher({embeddedBuildId, fetchIdentity, onShow, onClear}) is the tested state machine that merges the pushed bundle hash with the fetched commit and latches once per kind; describeBuild({commit, branch, dirty}) renders one line. Consumed by services/socket.js, components/Layout.jsx, and components/system-resources/BuildStampPanel.jsx.
chipContrast.js Contrast-safe chip colors for data-supplied colors the app did not pick — forge issue-label hexes (apps/tabs/IssuesTab.jsx), Google Calendar subcalendar colors (calendar/calendarUtils.js), and fixed category palettes rendered on theme-following surfaces (brain/tabs/BrainGraph.jsx, cos/TerminalCoSPanel.jsx). chipColors(color, mode) → { color, borderColor, backgroundColor } for an inline style (null when the color is missing/unparseable, so the caller falls back to a neutral chip): the wash keeps the label's own color, while the text/border keep its HUE and move only its LIGHTNESS, by the smallest step that clears WCAG AA against the chip's own tint on the ACTIVE theme mode. Memoized per (color, mode). Graded against SURFACES — the worst-case surface per mode (darkest day, lightest night), which the test re-derives from THEMES so a new theme can't silently escape the grading. Plus the primitives: parseColor (#rgb/#rrggbb/bare hex/rgb()), relativeLuminance, contrastRatio, blend, chipBackdrop, rgbToHsl/hslToRgb, ensureReadable. Pure — the caller passes theme.mode, nothing here reads the DOM.
clientErrorReporter.js reportClientError({ type, error?, message?, ... }) — POSTs window.onerror + unhandledrejection events to /api/client-errors with throttle + dedup, dropping browser-extension errors (see extensionErrors.js) before either gate. Wired from main.jsx; never call directly from React components.
clinicianReport.js Pure builders for the MeatSpace clinician-export view (/meatspace/export). buildClinicianReport({ tests, config }) → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); reportToMarkdown(report) → copy-paste markdown. Reuses the Blood tab's REFERENCE_RANGES / getBloodValueStatus so printed flags match the UI. Also exports buildBloodTestModel, buildLifestyleModel, getCategoryForKey, formatRange.
quotaBurnPatch.js mergeQuotaBurnPatch(base, patch) — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's jobs array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. quotaBurnJobIsSpent(job, ranAt) — whether a run once step has had its one dispatch, gated on the optimistic config's own runOnce so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's jobIsSpent). UNLIMITED_DISPATCHES / isUnlimitedDispatchCap(cap) / dispatchCapInput(value) — the -1 "no dispatch cap" sentinel (the default), mirrored from the server.
quotaBurnTasks.js MAINTENANCE_TASK_ORDER / MAINTENANCE_ORDER_GUIDANCE document the default ladder; maintenanceSequence populates audit and claim-drain references; maintenancePrerequisites lists missing saved settings and scoped setup patches for the selected mode and claim policy. The Quota Burn page's view of the SHARED scheduled-task catalog. buildQuotaBurnTaskCatalog({ schedule, jobs, apps }) groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a blockedReason on what is merely disabled or untargetable); searchTaskCatalog / flattenTaskCatalog / findTaskEntry query it. taskRefKey / stepFromTaskEntry / taskEntryNeedsApp build and address a step's taskRef. effectiveQuotaBurnSettings(step, saved) mirrors the server's effectiveSettings (overrides layered over the task's saved settings, params merged key-by-key). quotaBurnStepPayload(job) reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the overrides bag. taskSourceHref(entry) / CREATE_TASK_HREF link out to the source task.
clipboard.js copyToClipboard, writeClipboardSilently, readClipboard — safe across insecure-origin contexts. Use these instead of navigator.clipboard.writeText inline.
falVideoModels.js Re-export of server/lib/falVideoModels.js — the curated fal.ai video model catalog (including the FAL_AUDIO_VIDEO_MODELS audio-to-video lanes), per-model request rules and estimateFalVideoCostUsd(). Used by the Music Video fal model picker (components/musicVideo/VideoRenderSettings.jsx) and the Video Gen page's fal model suggestions.
falVideoHandoff.js buildFalH3MaxPrompt(prompt, negativePrompt) composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; FAL_H3_MAX_FREE_URL and FAL_H3_MAX_FREE_ALLOWANCE_NOTE carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API.
compareHelpers.js equalByKeys(a, b, keys) / equalListByKeys(a, b, keys) — typed key-based equality for useAutoRefetch's compare. Keys are property names, dotted paths ('context.running'), or (item) => value accessors. The typed alternative to sameJsonShape when a monotonic timestamp or unrendered field would break stringify-equality dedup.
consoleFilters.js installConsoleFilters() — drops a small allow-list of known-noise console strings (THREE.js Clock deprecation, expected WebGL Context Lost.) from console.{warn,log,debug}. Idempotent; auto-installed on import. Imported for its side effect from main.jsx.
cosDurationEstimate.js Shared CoS ETA estimator for the agent and task cards: estimateCosDuration({ durations, task, agentMetadata }) walks the /api/cos/learning/durations payload from the narrowest bucket outward — this run's provider+model+effort, then provider+model, then task type, then all tasks — and describeEstimateBasis(estimate) renders the cards' shared "Based on N completed …" tooltip clause naming which rung answered. MIRRORS the key composition in server/services/taskLearning/store.js.
cosSpawnWindow.js Re-export of the spawn-window settlement from the pure server leaf server/lib/cosSpawnWindow.js. A task keeps status: 'pending' for a beat after its agent registers as running, so a view rendering both lists must decide which side it belongs to (ACTIVE, until SPAWN_CLAIM_GRACE_MS). GET /api/cos/tasks already settles its payload, so most surfaces just read task.spawning; cos/tabs/TasksTab.jsx settles client-side because it also has the socket agent feed, which lands ahead of the next task refetch.
cosTaskType.js CoS task-learning bucket resolver for ETA surfaces: extractCosTaskType(task) mirrors the server's metadata-first extractTaskType handling for live tasks and archived-agent projections, so self-improve:*, user-task, and fallback estimates use the same history bucket that recorded the run.
diffLines.js diffLineBlocks(oldText, newText) → { blocks } ({ type: 'same', lines } / { type: 'change', oldLines, newLines }) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell LINE_DIFF_CELL_CAP guard. The structural layer behind HunkDiff (collapse same-blocks to context, word-diff each change-block).
diffWords.js diffWords(oldText, newText) → { tooLarge, oldRuns, newRuns } — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to { text, changed } runs, 4M-cell DIFF_CELL_CAP guard on the trimmed middle). Shared by InlineDiff (stacked), SideBySideDiff (columnar), and HunkDiff's change blocks.
dndKeyboardCoordinates.js createFreeDroppableKeyboardCoordinates({ isSkipped? }) + keyboardAwareCollisionDetection — build a KeyboardSensor coordinateGetter for a DndContext whose drop targets are free useDroppable zones (no SortableContext): arrow keys JUMP to the adjacent zone in visual order instead of nudging 25px. Use it in LibraryPane / GoalsListView-shaped surfaces; a sortable list uses @dnd-kit/sortable's sortableKeyboardCoordinates instead. Pair the getter with keyboardAwareCollisionDetection (keeps rectIntersection for pointer drags, closestCenter for keyboard ones) so adding keyboard support does not change where a mouse drop lands.
dndTransform.js dndTransformToCss(transform) — render a dnd-kit useSortable transform ({ x, y, scaleX, scaleY } or null) as a CSS transform string. Owned replacement for @dnd-kit/utilities' CSS.Transform.toString(); use it in every useSortable style object instead of re-adding that dependency.
downloadBlob.js downloadBlob(data, filename, type?) — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary <a> cleanup. Use instead of inlining URL.createObjectURL + <a download>.
standaloneDownload.js installStandaloneDownloadHandler(onDownload) delegates same-origin download links on share-capable touch browsers / Home Screen apps to DownloadManager; prepareDownload fetches a File for a fresh Save tap, assetDownloadUrl requests an attachment from static mounts, and isStandalonePwa detects Home Screen mode.
extensionErrors.js isExtensionError(payload) — true when an error report came from a browser extension's injected content script rather than from PortOS. Re-exported from server/lib/extensionErrors.js, which the ingest route filters on.
firstRunMissions.js Dashboard first-run missions (#5640). FIRST_RUN_MISSIONS is the four-slice catalog (Creative studio → /start-story, Personal knowledge → /brain/inbox, Run my machines → /apps, Delegate work → /cos/tasks) plus the matching Settings → Features ids each mission writes. shouldShowFirstRunCard / parseFirstRunQueryParam / featuresToEnable are the show/hide and write-set helpers — / only, session dismiss vs durable hideFirstRunCard, ?firstRun= force on/off. Pure / React-free; the card lives in components/onboarding/.
genUtils.js Shared bits between Image Gen and Video Gen pages.
repoUrl.js parseRepoUrl(url) / isRepoUrl(url) / repoBrowseUrl(parsed) / parseGitHubUrl(url) / isGitHubRepoUrl(url) — re-exported from server/lib/repoUrl.js, the authoritative repo-URL rule.
healthProvenance.js PROVENANCE_LEVELS / getProvenanceLevel(level) — the data-backed/inferred/experimental/speculative trust taxonomy (label, tone, description, "what would change this?" copy) behind the ProvenanceChip source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon.
healthStyle.js Shared health status styles and threshold-aware percentage/bar tones for system health views.
kanbanColumns.js bucketTickets / ticketInColumn / columnConfig / FALLBACK_COLUMNS — pure column logic for the Jira Kanban board (components/KanbanBoard.jsx). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique id (Jira name is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category).
localLlmBackends.js LOCAL_LLM_BACKENDS (id/label/lucide icon for Ollama + LM Studio) and localLlmBackendLabel(id). The two backends PortOS keeps a model catalog for, shared by the Runtimes view's backend cards and the Model Library's backend picker so a third backend is added in one place. Exported under qualified names because the barrel is flat and BACKENDS/labelFor are too generic to claim there.
localLlmTargetKey.js localLlmTargetKey({ backend, modelId }) — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip.
localModelAssessmentKey.js encodeLocalModelAssessmentKey, decodeLocalModelAssessmentKey, and localModelAssessmentPath — reversible base64url identity for a measured backend/model/tuning tuple, including the explicit null backend-default tuning. Invalid keys return null so selected-evidence routes can recover without guessing.
letteringDensity.js Re-export of server/lib/editorial/letteringDensity.js — analyzeComicLettering / panelLetteringMetrics / overflowSeverity / sanitizeLetteringThresholds / DEFAULT_LETTERING_THRESHOLDS. Powers the comic-script stage's INLINE per-page warnings (#1313) from the same code the authoritative comic.lettering-density check runs.
loomLayout.js FableLoom canvas layout — layoutLoomGraph(episode, { viewportWidth, orientation }) (BFS + barycenter-ordered positions, persisted pos overrides on left-to-right only, orthogonal port-fanned edges, canvas extents), pickLoomOrientation (stacks top-to-bottom under LOOM_STACK_WIDTH when orientation is not pinned), loomGraphLayers, routeLoomEdges (forward edges in packed gap lanes; backward/skip edges around the card band), placeEdgeLabels (de-collides intent labels), loomEdgePath(from, to, { laneY, self, orientation }), LOOM_NODE_W/LOOM_NODE_H/LOOM_EDGE_LABEL_MAX/LOOM_ORIENTATION/LOOM_STACK_WIDTH. A view-layer layering (shows unreachable nodes in trailing columns), deliberately NOT a mirror of the server's analysis-oriented computeGraphLayers. Pure/DOM-free.
loopbackHost.js isLoopbackHost(host) / isLoopbackOrigin() / describeMicAvailability() — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or getUserMedia-gated surface; matches the full 127.0.0.0/8 range, IPv6 ::1, and the browser-bracketed [::1] form.
manuscriptAnchors.js locateFind / locateAnchors / buildHighlightSegments — resolve editorial-comment anchorQuotes to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Shares the nearest-occurrence locateFind in server/lib/manuscriptLocate.js with the server accept path.
manuscriptFormat.js formatManuscript(text, stageId) / REFLOW_STAGES — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for prose only (scripts keep their structural line breaks). Pure/DOM-free.
mediaNavigation.js getAdjacentMedia(items, item) — prev/next computation for lightboxes.
assetProvenance.js Re-export of server/lib/assetProvenance.js. Stamp-time model/LoRA license provenance + rollup for collection/export Attribution.
mediaCollectionList.js Search / sort ordering for the Media Collections grid (#3283) and the CollectionPickerShell dropdown (#3312): applyCollectionView(collections, { query, sort }) filters via mediaSearch.js's AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by COLLECTION_SORTS (updated / name / count, normalizeCollectionSort coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (collectionItemCount(c) > 0) because it also needs the pre-filter count. isAutoCollection(c) recognizes a machine-created collection from ANY of four independent markers (AUTO_NAME_PREFIXES, Auto-created…/Auto-generated… description, uc-/sc- id, universe/series link) so a record predating a given marker still classifies; splitCollectionName(name) lifts the shared Creative Director: / Writers Room: / Universe: / Series: prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. Adding a server-side auto-creator means adding its prefix here or its collections silently rank as user-created. Pure — no React.
mediaSearch.js buildMediaHaystack, tokenizeQuery, matchHaystack, filterByQuery — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker.
ports.js PORTS + DEFAULT_PEER_PORT, re-exported from the pure leaf server/lib/ports.js (which ports.test.js pins against ecosystem.config.cjs, the source of truth — see docs/PORTS.md). Use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL.
providerManagement.js What every AI Providers surface shares about a service instance (#7567, #8014): catalogSummary reads its catalog state honestly (keeps unknown / known-and-empty / failed-with-retained-models distinct), serviceReadinessCopy / SERVICE_READINESS_COPY give one phrasing per readiness value (badge tone + label, and the predicate the compose popover and compatibility matrix append to the service's name), draftFromTransports / transportsFromDraft round-trip its transports map through a text form, dropping a blank endpoint rather than sending an empty one, and classifyServiceCategory / SERVICE_CATEGORIES / serviceMatchesQuery / sortServices / servicePresetAction group the Services view by what the definition offers (not the instance's selected plan) and decide whether a card may start a derived preset.
morsePractice.js Pure deterministic adaptive Morse sampler — selectMorsePrompt combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; canAdvanceMorseLevel guards level advancement on sample count, accuracy, and effective speed.
moodBoardAnalysis.js moodBoardAnalysisFromResult(item, result) picks the type-matched prompt-from-media payload stored on a pin; boardAnalyzePlan(items) splits pins into already-analyzed, still-readable, and skipped; boardPosterRenderCfg(imageCfg, mode) builds the explicit landscape poster render (any chosen image service) and posterStyleKey(style) detects a style change while that render is in flight; moodBoardItemSendLinks(item) builds the text-to-image / image-to-image / video handoff URLs for a pin card.
moodBoardItemSrc.js moodBoardItemSrc(item) resolves a mood-board item to a display image/poster src (imageUrl → served image:<file> bytes → derived video thumbnail → null); moodBoardPosterSrc(board) resolves the board's canonical poster filename to /data/images/…; moodBoardCollageSrc(board) resolves the persisted collage (collageImageRef) the same way; moodBoardItemVideoSrc(item) resolves a type:'video' item's playback URL; moodBoardItemAnalysisSource(item) resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip.
rapidReaderPosition.js Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text.
registerServiceWorker.js registerServiceWorker() / unregisterServiceWorkers() — wires up the offline app-shell + low-bandwidth asset-caching service worker (public/sw.js). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from main.jsx.
safeStorage.js safeReadStorage / safeReadJsonStorage / safeWriteStorage / safeWriteJsonStorage / safeRemoveStorage — guarded localStorage access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching localStorage inline so a storage failure never crashes init or a write path (#2387). Consumed by useTheme, useNavWorkingSet, and the command palette. Also safeReadJsonSession / safeWriteJsonSession / safeRemoveSession — the same guarantees over sessionStorage, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash).
unfoldToAnchor.js unfoldToAnchor(el) reveals a deep-link target inside folded sections before the page scrolls to it: opens every <details> around it and presses each [data-fold-toggle] that reads aria-expanded="false" in the [data-fold] elements around it (the element itself included), returning true when a React-state fold was pressed so the caller waits a frame. Used by the Music Video page's stage anchors (#mv-post-<target> into a folded Publish card or platform row).
sameJsonShape.js sameJsonShape(prev, next) — JSON.stringify-based equality for useAutoRefetch's compare option on small, deterministically-shaped poll payloads.
sketchCanvas.js Pure stroke model + 2D-context renderer for the media annotation canvas (createStroke, appendPoint, undoStrokes, drawStrokes, clampSize). Points stored in natural-pixel space; erase strokes use destination-out. Used by AnnotationCanvas.jsx / MediaAnnotate.jsx (#2036).
unsorted.js Synthetic "Unsorted" collection from media not filed in any real collection.
upsertByIdPrepend.js Newest-first upsert into an id-keyed list.
uuid.js uuidv4() — spec-valid v4 uuid that also works on insecure origins. Reach for this instead of crypto.randomUUID(), which only exists in a secure context (HTTPS / localhost) and throws crypto.randomUUID is not a function for the many users who reach PortOS over plain HTTP via Tailscale. Falls back to crypto.getRandomValues (available on insecure origins), then Math.random.
webglSupport.js isWebGLAvailable() — memoized probe for a creatable WebGL/WebGL2 context. CoS 3D avatars (and similar r3f mounts) call this before <Canvas> so headless Chrome / no-GPU displays degrade to a hint instead of unhandled WebGLRenderer rejections.
voiceLabel.js formatVoiceLabel(v, engine?) — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map.
withUnlistedOption.js withUnlistedOption(list, value, makeOption, {key = 'id'}) — keeps a stored-but-no-longer-listed pin (a retired model, a deleted persona, a stale voice/album link) selectable in a <select> instead of the value silently painting blank and a save dropping it: returns list unchanged when value is blank or already present under key, else prepends makeOption(value). key overrides the matched field for a list keyed by something other than id (e.g. 'name' for a voice list).

Page-scoped pure helpers

Module Purpose
audioContext.js getAudioContext() + resumeAudioContext(c) + acquireAudioSession(type) + getNoiseBuffer(c) (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio AudioContext singleton every playback feature shares (songPlayback, scorePlayback, metronome, midiPlayback). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. Every playback entry point resumes via resumeAudioContext(c), never by hand (it takes any context, so per-mount ones use it too) — it gates on state !== 'running', not state === 'suspended', because iOS Safari also parks a context in the non-standard 'interrupted' (a call/Siri/screen lock) which a suspended-only check walks past into silent "playback". acquireAudioSession(type) ARBITRATES navigator.audioSession.type, which is document-wide, and returns an idempotent release — playback keeps the hardware ring/silent switch from muting a pure-synth page but REFUSES capture, and the VoiceWidget is mounted on every page, so a last-writer-wins assignment trades one platform's silence for a dead mic. Each feature claims for exactly as long as it needs (play-and-record while a getUserMedia stream is open, playback while a player sounds) and the arbiter declares the union — capture always wins, since play-and-record also ignores the silent switch. Output-only players don't call it directly: pass audioSession: 'playback' to createLookaheadTransport, which claims on play and releases on teardown; a React surface owning its own context/stream uses hooks/useAudioSessionClaim.js, which adds the release-on-unmount backstop. Constructor resolved lazily (window → globalThis) so node-env test runs import cleanly; tests inject a fake via vi.stubGlobal('AudioContext', …) before first call.
chordPlayback.js Chord-sheet play-along for the SongBook tab/chordpro formats (#4104) — the chord-sheet sibling of drumPlayback.js and the fourth consumer of lookaheadTransport.js. sheetChordOccurrences(lines) flattens parseTabSheet(text).lines into the ordered chord tokens, each addressed { lineIndex, chordIndex } so <TabSheetView> can light exactly the token that is sounding; chordMidiNotes(name) voices one chord (bass note + chord tones, via chordShapes.chordTones); buildChordSchedule(lines, { bpm, beatsPerBar, countInBars }) is the PURE chord→[{ index, name, lineIndex, chordIndex, midis, startSec, durSec, rest }] mapping (a chord sheet writes no rhythm, so ONE chord token = ONE bar, and a dash-joined "Am-Am7" splits its bar between its segments) plus the count-in clicks; resolveChordPlayhead(schedule, posSec) converts an audio-clock position to { countIn, index, beat }; createChordPlayer(lines, …) strums it through scorePlayback's scheduleTone with a live metronome toggle.
chordShapes.js Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). getChordVoicing(name, instrument) → guitar { frets: [6 × (-1/0/n)], baseFret, bass }, ukulele (4-string GCEA, exact lowest-position search), or piano { notes: ['A','C','E'], bass } with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by baseFret (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry bass separately. parseChordName(name), splitJoinedChords('Am-Am7'), sheetUsedChords(text) (every chord a sheet names, unique, in first-appearance order — the viewer's "Chords used" card), toVoicingInstrument(songInstrument), VOICING_INSTRUMENTS. chordTones(name) returns the instrument-free half — the parse plus semitones above the root — so chordPlayback.js sounds a sheet without re-typing the interval tables. Reuses tabNotation.js's CHORD_TOKEN_RE/NOTE_TO_PC/spellPitchClass (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws.
canvasRoll.js Shared canvas helpers for the two piano-roll renderers (<PianoRoll> falling-note + <MidiPianoRoll> DAW-style, #2477). layerColor(index) — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; roundRect(ctx, x, y, w, h, r) — rounded-rect path with ctx.roundRect feature-detect and arcTo fallback; rollPalette() — resolves the theme-following { bg, accent, accentRgb } from --port-accent via getComputedStyle (canvas can't read CSS vars); ROLL_BG — the shared near-black bg literal. Pure canvas math/palette, no React.
wireframeCore.js The Kestrel Neon "core assembly": icosahedron geometry (ICOSAHEDRON_VERTICES / ICOSAHEDRON_EDGES, 12 vertices, 30 edges), rotatePoint / projectIcosahedron (Y-then-X rotation + perspective), and drawWireframeCore(ctx, frame) — one 2D-canvas frame of the depth-shaded wireframe with its orbit rings, vertex dots, and corner angle readout. Every color is an [r, g, b] triple so the caller sources them from AGENT_STATES and resolved theme tokens; no DOM reads. Consumed by cos/CoreCoSAvatar.jsx.
chiptunePlayback.js Looping WebAudio preview for LLM-generated chiptune scores (#2911) — buildChiptuneSchedule(score) (pure pattern/order → absolute-time flatten, MIRRORS server/lib/chiptuneScore.js timing semantics), parseChiptunePitch("C5") → MIDI, and createChiptunePlayer(getScore, { onLoop }) — a seamless-loop player over createLookaheadTransport (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing position() (monotonic across loop passes) + loopSec() for playhead UIs. No React — ChiptunePanel drives it.
waveSketchPlayback.js One-shot WebAudio preview for the Music Designer's LLM-made wave sketches (#8376; stereo painted canvases #8464) — createWaveSketchPlayer({ onEnded }) → `{ play(pcm
trackProvenance.js renderSourceLabel(source) / trackSourceLabel(track) — the display label (Suno, YouTube) for where a music take's audio came from, read off a render's source (#8967) or a track's ACTIVE render. Plain uploads and unrecorded (pre-provenance) takes return '' — never guessed. Shared by the Tracks render cards and the Music Video track row.
waveSketchSynth.js Off-main-thread synthesis for the drawn-waveform preview (#8470) — createSketchSynthesizer({ createWorker? }) → { synthesize(sketch, columns), dispose() }, resolving { channels, peaks } from a module Web Worker with the channel buffers transferred. Latest request wins: a new render terminates the in-flight worker and resolves the superseded promise to null; no Worker (or a worker load failure) falls back to a deferred main-thread render. WaveformPanel drives it.
waveSketchSynthWorker.js The Web Worker entry behind waveSketchSynth.js — renderSketchPreview(sketch, columns) → { channels, peaks } runs the server's synthesizeSketchChannels unchanged (sample-identical to the saved take) plus the mono-mix peaks. Its onmessage handler installs only inside a worker scope, so importing it elsewhere is side-effect free.
colorMatch.js Pure grading core for the song system's color-match training mode: buildColorMatchTimeline(score, { bpm }) → { notes, totalMs, msPerQuarter, bpm } (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring scorePlayback); gradeNote(hz, targetHz) classifies a sung pitch against a target into in-tune/close/off/missed (octave-folded, thresholds MATCH_IN_TUNE_CENTS/MATCH_CLOSE_CENTS); noteAtTime(timeline, tMs, fromIdx) finds the active note for a rAF cursor; summarizeAccuracy(grades) → { graded, counts, percentInTune, perNote } per-take summary (perNote is the ordered grade list a saved take persists, mirroring the server sanitizer); gradesFromPerNote(timeline, perNote) is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus centsBetween and the GRADE enum. No React, no audio — the useColorMatch hook drives it.
pitchDetect.js Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). detectFrequency(frame, { sampleRate }) → { hz, clarity } (McLeod NSDF; clarity gate rejects silence/noise); frequencyToNote(hz, { a4 }) → { letter, accidental, octave, step, cents } (cents ∈ [-50,+50], sharp positive; step reuses scoreNotation's diatonicStep so detected notes align with the renderer); noteToFrequency(note, { a4 }) inverse (color-match targets); createPitchTracker(analyser, { onUpdate }) → { stop } rAF/interval loop with median+EMA smoothing to kill octave jumps; tuningQuality(cents) → { level, label } buckets a cents deviation into in-tune/close/off/none (thresholds IN_TUNE_CENTS/CLOSE_CENTS) for the tuner color readout.
universeBuilderExpand.js mergeExpandIntoDraft(draft, result) — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with kind precedence, canon dedupe by name/slugline/alias). Also exports mergeVariations, mergeCanonByName, and extractPreservedFromDraft for callers that need the building blocks (per-category Generate, save-time refetch+merge).
editorialChecks.js Pure helpers for the Editorial Checks page (/pipeline/editorial-checks, #1285): groupChecksByScope(checks) buckets catalog rows into ordered Noun/Scene/Issue/Series sections; groupFindingsByCheck(comments, rowsById) groups check-sourced review comments per check with open/total + severity counts; openFindingsTotal(groups) sums open findings; findingManuscriptLink(seriesId, comment) builds the ?comment= deep-link into the manuscript editor; the triage filter/sort helpers (#1600) deriveFindingFacets(groups) (enumerate present severities/statuses/scopes/checks/issues), applyFindingsView(groups, filters, sort) (filter + recount + sort findings and groups), normalizeFindingSort, findingIssueKey, and the FINDING_SORT_OPTIONS table; the per-check maturity/quality helpers (#1629) checkDismissalRate(group) and checkMaturity(group) (→ { findings, dismissalRate, falsePositiveRate, level }, level ∈ new/unproven/noisy/reliable) plus the CHECK_MATURITY_MIN_SAMPLE/CHECK_NOISY_DISMISSAL_RATE thresholds; plus scopeLabel and the CHECK_SCOPE_ORDER/CHECK_SCOPE_LABELS tables. No React/window — the page and its tests share them.
editorialHealth.js Pure presentation helpers for the editorial health panel (/pipeline/editorial-checks, #1316): scoreBand(score) bands a 0–100 health score into a label + Tailwind tone; deltaDisplay(delta) formats the revision-to-revision score change (arrow + tone); sparklineGeometry(points, box) projects the trend's score points into SVG polyline coords; orderedCategories(openByCategory) sorts the per-category open-finding breakdown; orderedChecks(openByCheck, labelFor) sorts the per-check breakdown resolving each id to its catalog label (#1597); checkCountSeries(points, checkId) extracts one check's count series across the trend points; countSparklineGeometry(values, box) projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); diffCountMaps(current, previous) lists the buckets whose open-finding count changed between two snapshots (#1630); snapshotDiff(point, previous) builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the SEVERITY_ORDER/SEVERITY_LABELS and READINESS_GATE_LABELS/READINESS_GATE_ORDER tables. No React/window — the panel and its tests share them.
episodeSceneImport.js Best-effort mapping of a FableLoom episode's scene nodes into the Episode Composer's draft scenes shape (#6228): parseNodeTextToLines(text, { format }) splits prose into a single action line, or (for teleplay) picks out ALL-CAPS character cues + following dialogue lines and drops sluglines; loomEpisodeToDraftScenes(episode, { format }) maps every node to one draft scene. Lossy on purpose — the composer always leaves the import user-editable.
seriesReviewProgress.js Pure helpers for the "Review this series" SSE progress stream (SeriesReviewPanel.jsx, #4108): REVIEW_STEP_LABELS + reviewFrameLabel(frame) label a single frame, and summarizeReviewProgress(frames) folds the whole stream into { headline, alsoRunning }. Since the review runs the foundation judge and canon readiness concurrently with the editorial-checks pass, frames interleave — labelling only the newest frame made the headline flicker between a background step that just settled and the current check. The summarizer tracks which steps are still in flight, gives the headline to the editorial-checks pass while it runs, and reports the other in-flight steps alongside it. No React/window.
drumKits.js The three selectable synth kits for the SongBook drum play-along — DRUM_KIT_LIST (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived DRUM_KITS / DRUM_KIT_IDS / DEFAULT_DRUM_KIT (909 punchy, 808 deep-sub, acoustic), resolveDrumKit(id) (unknown/stale id → the default, never silence), kitVoiceLayers(kit, sound) (unmapped piece → the snare, never silence) and the kit-independent CLICK_VOICE. Pure DATA: each voice is a list of LAYERS — tone (wave, from, to, pitchDecay, drive), noise (filter), or metal (N square partials summed into one filter+envelope) — that drumPlayback.js realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: pitchDecay is INDEPENDENT of the amplitude decay (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), drive tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a metal layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers.
drumNotation.js Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (HH: x x x x) for the SongBook drum content format, drawn by <DrumSheetView> (hand-rolled SVG, no engraving lib). parseDrumChart(text) → { time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors } — key: value headers (time/tempo/subdivision/kit row-order override), blank-line-separated bar blocks with a # label x2 repeat suffix expanded into real bars, nine kit pieces (CR RD HH T1 T2 S FT K HF, long aliases accepted), six cell glyphs (- rest, x normal, X accent, o open, g ghost, f flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into errors — never throws. Plus KIT_PIECES (label / GM midi / synth sound / glyph), kitPiece(id), CELL_GLYPHS (per-glyph velocity + flags), isDrumNotation(text) (import-page format sniff, runs BEFORE tabNotation.detectFormat), drumChartHasMusic(text) and its already-parsed twin chartHasMusic(chart). Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — describeDrumCell(pieceId, cell) → { pieceLabel, char, articulation, detail, technique, velocityPercent, rest } (piece-aware: o is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), describeDrumPosition(bar, step, subdivision) → bar 6, count “2 e” (count-along syllables, exact +n/N fallback for an unconventional subdivision), drumGlyphLegend(pieceIds) (all six cell characters, with the o row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each KIT_PIECES row's technique (how that piece is struck). Only the hi-hat voice sustains an o in playback, so the open wording follows the piece's sound, not its glyph shape. NOT the lead-sheet parser (scoreNotation.js).
drumPlayback.js Synthesized drum-kit play-along for the SongBook drum format (#3115) — the third consumer of lookaheadTransport.js alongside scorePlayback/midiPlayback. buildDrumSchedule(chart, { bpm, loop, countInBars }) is the PURE chart→[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }] mapping (one notated beat = 60/bpm, one grid step = beat/subdivision; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; resolveLoopRange(barCount, loop) clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real countIn: true events on the same clock so there is no second timer. createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, clickVolume, kit, onStep, onEnded }) sounds it on the shared AudioContext from a SYNTHESIZED kit (no shipped samples — recipes in drumKits.js, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports onStep({ bar, step, countIn }) for the <DrumSheetView> playhead. The metronome — the through-music click AND the count-in, which both sound CLICK_VOICE, never a kit piece — rides its OWN gain bus into the master, so setClickVolume(0–1) moves clicks already queued in the lookahead window instead of only the next ones (a level of 0 additionally schedules no click voice at all — the level persists, so a silenced click must not keep building a voice per beat forever) (clampClickVolume returns null for an unset/garbled level so a caller can tell "never chosen" from a stored DEFAULT_CLICK_VOLUME-vs-silence). setKit(id), setClick(enabled) and setClickVolume(level) apply LIVE (they touch no timing, unlike setBpm/setLoop/setCountIn, which only rebuild while idle). Pure (no React) — SongBookViewer owns the transport UI.
lookaheadTransport.js Shared lookahead-transport state machine for the synth players (#2493) — createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? }) owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the resumeAudioContext() call with the teardown-race guard, the optional audioSession claim held for exactly as long as the transport sounds, track() node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the SYNTH_TIMING lookahead constants (LEAD/LOOKAHEAD_MS/SCHEDULE_AHEAD) scorePlayback/midiPlayback share. No React, no score/MIDI concepts — imports only the shared AudioContext.
lossSparkline.js lossSparklineGeometry(series, box) — projects an unbounded training-loss series ({step,loss}[]) into SVG polyline coords, normalized to its own min/max (unlike editorialHealth.sparklineGeometry's fixed 0–100 axis). Returns { points, coords, last, min, max }. Drives the Render Queue's training-row loss curve (#1408). No React.
managedAppSources.js Readers for the managed-app repository-source payload (GET /api/apps/:id/repository-sources). primaryRepositorySource picks the application checkout out of the source list; repositoryForkDiverged / repositoryForkPushable / repositoryForkNeedsSync answer whether a managed update may ask the server to fast-forward the origin fork (a diverged fork never can, nor can a fork PortOS lacks push access to — a correctness rule, not a label), with describeForkUnsyncable explaining why when it may not; describeRepositorySourcesBehind renders one clause per checkout an update can actually pull forward, over the shared countText pluralizer both surfaces phrase counts with. Shared by the app Git tab's Repository sources panel and the Eidoverse page's out-of-date advisory.
messageSyncModes.js Message-account sync capability + read-state helpers (#9968): accountSupportsSyncMode(account, mode) (reads the server-derived syncModes; a missing field means every mode), partitionAccountsBySyncMode(accounts, mode) → { supported, excluded } for aggregate sync actions, and messageReadState(message) → 'unread'/'read'/'unknown' (unknown only when the provider recorded null read flags, e.g. Teams).
metronome.js Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song tempo field. createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete }) lookahead-schedules accented click tones on the shared AudioContext clock (same pattern as songPlayback.js), emits { beat, bar, accent, countIn, whenAudioTime } per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on stop(). Plus clampBpm (20–320), secondsPerBeat, timeSignatureFromScore, beatDescriptor, and normalizeBeatsPerBar — the ONE reading of a time-signature numerator (garbled/zero/negative → 4), shared by the scheduler and the visual <BeatPulse> so the dots can't disagree with the clicks.
mindThinkingPresets.js Presentation helpers for the Persistent Mind's temporary thinking sessions (#6285). classifyMindRouteBilling(provider) answers the question the composer must settle without contacting anything: does borrowing this route run on THIS machine (local), stand behind a credential/subscription (account), or can PortOS not tell (unknown)? Unknown is treated as billable — guessing "free" is the one direction that costs money. Plus formatMindRoute (the one "provider / model · effort" phrasing), sameMindRoute (client mirror of the server's route-only equality, so a label rename does not read as a changed route), findMindThinkingPreset / mintMindPresetId (a server-legal id minted from a label), and the receipt readers formatMindCallUsage / formatMindCallOutcome / formatMindElapsed / mindTurnOutcome / mindTurnElapsedMs / temporaryMindTurns — all of which keep "the provider reported nothing" rendering as unknown rather than as a free, instant, successful call. Pure; no fetches, so previewing a preset can never start an inference.
mindTurnProgress.js Live progress derivation for a Persistent Mind turn (#7409). describeMindTurnProgress({ state, runtime, events }) folds the public state and the /mind/runtime snapshot into one `{ phase: 'thinking'
midiChords.js Chord detection for the MIDI visualization UI (#2477). detectChordWindows(notes, { minWindowSec }) sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → [{ startSec, endSec, label, midis }] (adjacent same-label windows merged); nameChord(pcs, bassPc) maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (C E G#) rather than guessing wrong; chordNoteNames(midis) for tooltips. Pure — no canvas/React.
midiNotes.js Minimal Standard MIDI File parser + normalizer for the MIDI visualization UI (#2477) — in-tree, zero deps. parseMidiFile(arrayBuffer) parses SMF format 0/1 (running status, note-on vel-0-as-off, tempo map incl. mid-file changes, SMPTE division, track names) into the piano-roll view-model { durationSec, minMidi, maxMidi, notes:[{id,midi,startSec,durationSec,velocity,track,name}], tracks, tempos }. Throws on non-MIDI bytes. Consumed by useMidiNotes → <MidiPianoRoll>. NOT the lead-sheet parser (scoreNotation.js).
midiPlayback.js Synth preview of a transcribed .mid (#2490) — createMidiPlayer(data, { onEnded }) plays the parseMidiFile view-model as velocity-scaled oscillator tones through a per-play master bus on the shared AudioContext, with the same lookahead-scheduler idiom + tone envelope (scheduleTone) as scorePlayback.js. Transport: play/pause/stop/seek(sec) (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point) and position() for the <MidiPianoRoll> moving playhead. Pure (no React) — useMidiPlayer wraps it.
pianoKeyboard.js Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (<PianoRoll>). Pure math, no canvas/React. keyboardRange(midis, { minSemitones }) → { lowMidi, highMidi } padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; buildKeyboardLayout({ lowMidi, highMidi, width }) → { keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth } (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus isBlackKey(midi), midiNoteName(midi) (sharps spelling), pitchClass(midi) (positive modulo), the canonical PITCH_CLASS_NAMES table (re-exported by referenceAnalysis.js, consumed by midiChords.js — single source for note/chord spelling), and the BLACK_KEY_RATIO/BLACK_KEY_HEIGHT_RATIO constants. Pairs with scorePlayback's per-note midi field.
referenceAnalysis.js Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs }) frames decoded PCM through detectFrequency offline (faster than realtime) into the [{ tMs, hz, clarity }] shape singToScore consumes; proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key }) runs the solo-segment pipeline (extract → transcribePitchTrack on the round's tempo/key grid) → { track, body, text }; buildScoreText({ key, tempo, body }) wraps a transcribed body in a lead-sheet header; barPitchClasses(scoreText) / diffScoreBars(proposed, existing) compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Stacked-mix extraction (#2121, spectral diff v2): magnitudeSpectrum(frame, { fftSize }) (hand-rolled radix-2 FFT, Hann-windowed) / averageMagnitudeSpectrum(samples, sampleRate, { startMs, endMs }) build a backing profile; estimateSpectralF0(mag, sampleRate, fftSize) picks the fundamental by weighted (1/k) harmonic sum (octave-robust); extractSpectralDiffTrack(samples, sampleRate, { startMs, endMs, bgStartMs, bgEndMs }) subtracts the backing profile per frame and estimates f0 on the residual to recover a voice that never plays solo; proposeStackedSegmentScore(...) is its proposeSegmentScore counterpart. Zero LLM calls — pure local DSP.
roundDraft.js Pure draft rules for the Round editor (/rounds/:id, #3389) shared by the page, its useRound* hooks, and the edit form: the mirrored server caps PARTNERS_MAX / SCORE_PARTS_MAX; the in-session temp-id contract (TEMP_ID_RE, localId(prefix), stripTempId(row)) that keeps a never-saved row's React key from being persisted and later colliding with a server uuid; the tempo band TEMPO_MIN/TEMPO_MAX with parseTempo(raw) (on change — no clamping, so typing "68" isn't mangled) and clampTempo(n) (on blur); and buildRoundPatch(song), the PUT body with every temp id — including a segment's dangling layerId — blanked.
scoreNotation.js Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the <ScoreSheet> SVG renderer draws (no abcjs / VexFlow / OSMD). parseScore(text) → { clef, key, keySig, time, tempo, measures, errors }, with each parsed note carrying its raw token and source offsets; replaceNotePitch(text, note, pitch) uses those spans to rewrite only one pitch while preserving the rest byte-for-byte. Plus parsePitch, diatonicStep, durationBeats, keySignature, DURATIONS, and scoreHasMusic(text). Forgiving: bad tokens collect into errors and are skipped, never thrown. Pure — the renderer only does geometry.
scorePlayback.js Melody synth playback for the lead-sheet notation — companion to songPlayback.js (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft OscillatorNode reference tones on a lazy shared AudioContext (no MIDI.js / Tone.js). buildSchedule(score, bpm?) is the pure notes→{ midi, freq, startSec, durSec } mapping (A4=440, quarter-beat = (60/bpm)·(beatValue/4) so it honors the time signature; midi feeds the <PianoRoll> key mapping); noteToFrequency/midiToFreq/pitchToMidi convert pitches; createScorePlayer(score, { bpm, onNote, onEnded }) plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the <ScoreSheet> playhead; createMultiScorePlayer(parts, { bpm, onNote, onEnded }) synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part onNote(partId, index) playhead, plus position()/duration() (score-seconds) for the continuous piano-roll visualizer. Both players are thin schedulers over the shared lookaheadTransport.js. Also exports the pieces midiPlayback.js shares: scheduleTone (attack/release envelope) and makeSafeCall(label) (interval-callback guard); the SYNTH_TIMING lookahead constants now live in lookaheadTransport.js.
singToScore.js Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. segmentPitchTrack(track, opts) groups [{ tMs, hz, clarity }] frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); quantizeSegments(segments, { bpm, beatValue }) snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue }) spells notes enharmonically from the key signature and emits measure-grouped | … | body text; transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue }) runs all three. Round-trips cleanly back through parseScore. Reuses frequencyToNote (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library.
singToVerify.js Pure strict-1:1 score verification: alignSingToVerify(score, track, { bpm, startBar, captureEndMs }) aligns clear sung-pitch frames to buildColorMatchTimeline windows, preserves detected octave and key-aware spelling, and returns written→sung rows with raw cents, grade, source note, and explicit acceptance state. Reached silent windows are missed; notes after Stop remain pending.
songCraft.js Canonical a cappella song-craft reference data rendered by the Songs Guide (/songs/guide) and reused by the Song editor: RHYTHM_SHAPES / DIRGE_RHYTHM_SHAPES (dirge & ballad pulse feels with BPM bands), VOICE_LAYERS (foundation-first harmony build ladder), LEARNING_STEPS (practice sequence), NOTATION_HELP (lead-sheet/notation primers), SOLFEGE_DEGREES + solfegeForDegree(n), and rhythmShapeLabel(id) (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift.
songBookDraft.js SongBook editor save/dirty boundary: buildSongBookPatch(draft, savedDraft) preserves unchanged-link omission; songBookDraftsEqual(a, b) compares the same serialized values. Exports SCROLL_DURATION_MIN/MAX for the form. Page owns defaults and lifecycle; add save normalization here so the navigation guard follows.
songPlayback.js createLayeredPlayer(takes) — decode N recorded vocal takes and start them together on one shared AudioContext so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer.
songProgress.js Pure training-progress core for the song system's memorize/learn/track mode. deriveTrainingSections(score, lyricSections?) slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); recordAttempt(progress, scope, summary) appends a graded take to a scope's bounded rolling history (drops zero-note takes); scopeStats(progress, scope)/wholeSongStats derive { attempts, best, average, last, streak, learned } (learned = streak of ≥LEARNED_PERCENT takes ≥LEARNED_STREAK); weakestSections(progress, sections) ranks weak/un-attempted sections for spaced-repetition; memorizationPercent is the learned-section share; hideLevelFor(average) maps a rolling average to a progressive lyric/note-hiding level (show/dim/hide/blind). No React/audio — useSongTraining drives it.
estimationTolerance.js estimationToleranceText(tolerancePct) → the one line an estimation drill shows to say how precise to be, e.g. "Within 10% counts — 2 significant figures is close enough". Converts the grading band into significant figures (scale-free: rounding to n of them is worst-case 0.5 x 10^(1-n) off, so the smallest n that fits the band IS the precision required), because a percentage of an answer you have not worked out yet is not actionable mid-drill. Reads the band through resolveEstimationTolerancePct (server/lib/postScoring.js), the same resolver both graders use, so the copy can never claim a band the ✓/✗ did not apply. Rendered by components/meatspace/post/EstimationPrecision.jsx. Pure, DOM-free.
powersBreakdown.js Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review.
promptStageGroups.js Search + grouping for the Prompt Manager's Stages pane (#3284). buildStageGroups(stages, { query, systemOnly, systemStageKeys }) → { groups, matchCount, totalCount }, filtering the { key: config } stage map on title + description + key (AND-token, reusing mediaSearch.js's tokenizeQuery/matchHaystack) and bucketing survivors into ordered [{ key, label, stages: [[key, config], …] }] groups (Other pinned last). stageGroupLabel(name) derives the family from the Family — Specific dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the STAGE_WORD_PREFIXES word list (CoS Agent Briefing) and then Other; stageGroupKey(label) case-folds it into the group's identity, so Pipeline — X and pipeline — y are one group rather than twin headers that render alike under uppercase; stageGroupLabelFor(key, config) / stageGroupKeyFor(key, config) are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. stageHaystack(key, config) is the searchable string. The system-stage list is NOT mirrored here — GET /api/prompts ships it as systemStages (the SYSTEM_STAGE_KEYS list in server/lib/promptSystemStages.js) and the page threads it in as systemStageKeys (#3314). Pure — no React, no I/O.
stageModelTiers.js Re-export of server/lib/stageModelTiers.js — the prompt-stage tier vocabulary (STAGE_MODEL_TIER_OPTIONS rows for every stage model select, canonicalStageModelTier so a legacy stored quick/coding still selects Light/Medium, isStageModelTier).
spriteCollectionActions.js Gating for the Sprite Manager asset collection's inline actions (#2931). buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim }) → { regenerateFor(asset), trimFor(asset) }, each returning null for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (south/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the correctionKey (#3134) the card binds its inline correction note to — walk:<dir> for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from spriteFacets.js and the key vocabulary from spriteCorrections.js.
spriteCorrections.js The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned corrections map (Sprites.jsx); this module owns its keys so the pure gating layer (spriteCollectionActions.js) and the React surfaces (CorrectionNote.jsx + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — anchorCorrectionKey(dir) keeps the bare direction (pre-#3134 state untouched) while walkCorrectionKey(dir) / MAIN_CORRECTION_KEY / AMBIENT_REFERENCE_CORRECTION_KEY prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. trackCorrectionKey(trackId, dir) (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. correctionPromptPayload(corrections, key) → { correctionPrompt } only when the note is non-empty after trimming, else {} — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O.
spriteFacets.js Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's classify_asset(). classifySpriteAsset(path) decodes a record-relative asset path into { family, status, role, direction, runId } — status ∈ runtime/approved/candidate/superseded/rejected/source, role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest — and is total (an unknown path degrades to sprite/source rather than throwing). classifySpriteAssets(assets) adds the one facet only knowable across a listing: an approved asset below the highest -vN of its stem becomes superseded. groupSpriteAssetsByRole(assets) returns render-ready { role, label, assets } sections in SPRITE_ASSET_ROLES order — it does NOT render a manifest group: each runtime atlas's sidecar manifest is folded onto its atlas row as row.manifest, and other behind-the-scenes JSON is omitted. runtimeVersionDir(path) / isRuntimeVersionPath(path) / isRuntimeSidecarManifest(path) expose the runtime/vN grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like AssetInspector reuse one definition instead of re-regexing. Also exports SPRITE_DIRECTIONS (mirror of server/services/sprites/prompts.js) — the direction/runId facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O.
spriteRecordGroups.js Grouping + search for the Sprite Manager sidebar's record picker (#2932). groupSpriteRecords(records) → ordered [{ key, label, records }] under Characters / Places / Objects (props folded into Objects alongside object, no migration). filterSpriteRecords(records, query, limit=8) is the autocomplete filter — multi-term (AND) substring over name/id/kind, capped at limit. groupKeyForKind(kind) maps a kind to its group key (unknown → objects). SPRITE_RECORD_GROUPS / NEW_SPRITE_KINDS back the browse disclosure and the create-panel kind selector. Pure — no React, no I/O; the page owns the per-group icons.
spriteTrimmer.js Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). buildTrimmerSources(walk, assets) → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each { id, kind: 'run'|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable } — every packed-strip run is trimmable (layout-agnostic), while saved trims are preview-only, mirroring spriteCollectionActions' gate. stripFrameGeometry(stripPreview) → { frameCount, fps, cellWidth, cellHeight } with the native 8-phase / 12fps fallback; phaseLabelFor(index, frameCount) names the 8 walk phases (bare frame N for any other length); sanitizeTrimSlug(name) → the server's [a-z0-9-]+ output slug; allColumns(n) / invertColumns(n, enabled) for the frame-toggle set. WALK_PHASES is the shared phase-label constant (WalkWorkflow imports it here). Also holds the walk-cycle authoring knobs mirrored from walkBounds.js — WALK_DEFAULT_FRAME_COUNT / WALK_DEFAULT_FPS, the WALK_FRAME_COUNT_OPTIONS list and walkFpsOptionsFor(fps) (splices a current odd fps into the even-step list so the <select> never lies) — feeding the shared CycleTarget control used by both the walk workflow and the trimmer's re-derive panel (#2980). Pure — no React, no canvas, no I/O.
spriteWalkUnlock.js The user-facing copy for a BLOCKED walk re-open (#3043/#3044), shared by the Walk Cycles header, per-direction cards, and Loop Trimmer so one server-stamped block can never be described two different ways. walkUnlockCopy(unlock, { mode?, direction? }) → { text, action, prompt, acknowledgeNoClips, toast } for a blocked scope (null when it is not blocked): a blocked-but-acknowledgeable scope gets the regeneration offer plus the acknowledgeNoClips consent flag its POST carries, a non-acknowledgeable one gets the dead-end explanation and no action. WALK_UNLOCK_TOAST is the ordinary unlock success message. Pure — no React, no I/O.
proseExportSettings.js Re-export of server/lib/proseExportSettings.js — TRIM_SIZES, DEFAULT_TRIM_SIZE, INTERIOR_FONTS, DEFAULT_INTERIOR_FONT for the Export page's selects.
layeredIntelligenceSources.js Re-export of server/lib/layeredIntelligenceSources.js — LAYERED_INTELLIGENCE_SOURCE_KEYS, the ordered list of built-in Layer-1 telemetry sources the self-improvement loop can gather. A test requires one LI_SOURCE_FIELDS toggle per key.
writersRoomPresets.js Re-export of server/lib/writersRoomPresets.js — WORK_KINDS, WORK_STATUSES, EXERCISE_STATUSES, ANALYSIS_KINDS; writers-room/labels.test.js requires a label per value.
tribe.js Pure Tribe domain helpers shared by the Tribe page and its TribeCircleMap visualization: RINGS (support→core→tribe→village Dunbar rings + the uncapped external "outside the tribe" classification — caps, cadence defaults, Tailwind tones + hex), TRIBE_RINGS (the four inner rings the care queue/capacity/overdue counts operate over, excluding external), ENERGY (energy tiers + hex), STATUS_HEX (cadence-status → SVG stroke color), contactStatus(contact) (presentation wrapper over the shared cadenceStatus — attaches label/tone to the missing/overdue/soon/steady/external state) / daysBetween(date) (alias of the shared daysSinceDate), ringFor / energyFor lookups, tagsToArray / tagsToInput, initialsFor(name) (node glyph), and the care-state filters shared by the summary tiles / roster / care queue (STATUS_FILTERS, STATUS_FILTER_IDS, STATUS_FILTER_LABELS, matchesStatusFilter(contact, filter) — unknown ids degrade to all). Ring cadenceDays come from DEFAULT_RING_CADENCE (via tribeCadence.js); the cadence STATE MACHINE lives in tribeCadence.js.
tribeCadence.js Re-export of server/lib/tribeCadence.js — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the server.
streakGlyph.js streakGlyph(streak) — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget.
syncCounts.js Directional pending-sync counts for the Instances federation cards. directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs }) → { toPull, toPush } (each a non-negative Number, or null when unknown) from monotonic change-log seqs; diffSeq(ahead, behind) is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past MAX_SAFE_INTEGER); describeDirectional({ toPull, toPush }) renders the plain-language { state, text } ("in sync" / "N to pull · M to push" / "checking…"). No React — SyncStatusBadge drives it.
tabNotation.js Guitar-tab / chord-sheet / ChordPro text parser for SongBook (/songbook). parseTabSheet(text) → { lines, meta, errors } classifying each line (section/chords/lyric/tabstaff/chordlyric/blank/text) with chord names + column offsets, plus ChordPro meta ({title:}/{artist:}/{key:}/{capo:}); detectFormat(text) → 'chordpro' | 'tab' | 'plain'; normalizePastedTab(text) uses the shared server/lib/xmlEntities.js decoder (ordinary spaces for &nbsp;) and cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; transposeChordName(name, n) / transposeText(text, n) transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); chordLineSegments, pairedLineChunks, and chordLyricRows build aligned, word-wrapping chord/lyric display rows; TAB_ARTICULATIONS documents tab-staff technique characters for the viewer legend; CHORD_TOKEN_RE exported for reuse, plus NOTE_TO_PC / spellPitchClass exported minimally so chordShapes.js derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as text. NOT the lead-sheet parser (scoreNotation.js).
tailnetPeer.js isTailnetPeer(peer) — is this registered peer reachable ONLY over the tailnet? A faithful port of server/lib/tailnetPeer.js (MagicDNS .ts.net, the 100.64.0.0/10 CGNAT range with every octet range-checked, and the fd7a:115c:a1e0::/48 ULA; an explicit non-tailnet host overrides a tailnet-looking address). FAIL-CLOSED — anything not positively recognized is not tailnet. Used to keep the unattended-render-routing picker from OFFERING a peer the server would refuse under ADR federated visual prompts rule 5; the server stays authoritative and refuses such a route both on save and on every enqueue. Keep the table in tailnetPeer.test.js identical to the server suite’s.
terminalDictation.js Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and replaces what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (determin + determine + determines…). attachDictationBridge(terminal, sendData) binds capture-phase listeners on terminal.element — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: TERMINAL_DEL (0x7f) per dropped character, then the added text. sendData returns false to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end) resync the mirror without emitting. In screen-reader mode xterm drops every insertText event and leaves handled keydowns uncancelled, so the bridge is the only path dictation has to the PTY and a live keydown counts as xterm's keystroke, like a keypress. planFieldEdit(mirror, next, floor) → { data, committed } is the pure core: floor is the prefix we did not write and must never rewind through, and committed (what the PTY holds afterward, which is not the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to U+FFFD. Wired in useShellSession; the test suite pins the seam against a real Terminal.
terminalFit.js In-tree xterm sizing helper. fitTerminal(terminal) measures the parent and terminal CSS box, accounts for padding and the overview-ruler scrollbar, clamps the calculated geometry to at least 2 columns × 1 row, and resizes only when the dimensions change.
terminalScroll.js Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds no touch handlers at all, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so scrollLines() clamps to a no-op there. Normal shell scrollback uses scrollLines(); alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. attachTerminalTouchScroll(terminal) (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. attachTerminalWheelScroll(terminal) handles native wheel input, and scrollTerminalPage(terminal, direction) powers the SCROLL_KEYS buttons. measureTerminalGeometry(terminal) takes one layout read per gesture; planTouchScrollSteps(accumPx, rowHeightPx) is the pure sub-row-remainder core. Wired in useShellSession.
terminalTheme.js Pure xterm.js palette builder for the Shell terminal. buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode) assembles the xterm theme object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (ANSI_NIGHT bright/pastel for dark backgrounds, ANSI_DAY darkened/saturated so colored CLI output stays legible on daytime themes). parseCssColorToHex(raw, fallback) normalizes both the 15 15 15 triple form and the rgb(7 7 7 / 0.86) function form (used by --port-terminal-* tokens) to #rrggbb, dropping alpha. No DOM reads — Shell.jsx resolves CSS vars and re-applies on theme switch.
textUtils.js escapeRegExp(value), countWords(text), isStr(v) and isNonBlankStr(v) re-exported from server/lib/textUtils.js — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same \S+ rule the server stores). Named exports rather than export *, so the file stays the list of what the browser actually uses. Also pluralize(count, singular, pluralForm?) — the shared "N item/items" phrasing helper for singular/plural counts.
threeVendorImportMap.js Inlines the vendored three.js modules into a Code Animation page for the sandboxed preview (#10464). importsThree(html) detects a bare three / three/addons/* import (mirrors the server's threeVendor.js); buildThreeImportMap(files) turns the GET /api/code-animation/vendor/three bundle into an import map of data: URLs (the opaque-origin iframe cannot fetch ./vendor/*.js), rewriting the vendored files' relative imports to three-vendor/<path> ids; inlineThreeVendor(html, files) replaces any import map in the page with it.
brainThreads.js Re-export of server/lib/brainThreads.js — Brain THREAD statuses, isTerminalThreadStatus / isThreadOverdue, threadNextLine and the server's list comparator compareThreads, so the Threads tab and the Open Threads widget group, badge and order rows exactly as GET /api/brain/threads does (a thread is a tracked open loop, never a message thread).
threadRefKinds.js Re-export of server/lib/threadRefKinds.js — the Brain THREAD ref vocabulary and (kind, id) → label/URL route table (a thread is a tracked topic or commitment, never a message thread). Named exports only — threadRefLabel/threadRefUrl (what the client renders with) and THREAD_REF_KIND_IDS / EXTERNAL_THREAD_REF_KINDS (what the Threads tab's ref picker enumerates and how ThreadRefChip picks <a> over <Link>). pages/CatalogIngredient.jsx renders its inbound-ref chips through threadRefUrl/threadRefLabel here instead of its own local switch, so the repo has exactly one kind→route table.
threejsAnimation.js Pure pose evaluator for the declarative clip contract in server/lib/threejsModel.js, used by the Three.js Models preview transport; the pose comes from the shared server/lib/threejsModelClipPose.js leaf the physical audit also measures. evaluateThreejsClipPose(clip, timeSeconds) → { timeSeconds, pose, activeSequenceIds, activePartIds } where pose is a null-prototype partId → { position?, rotationDegrees?, scale?, opacity?, visible? } map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), visible steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. collectThreejsCues(clip, from, to) returns the data-only sound cues a play loop crossed in the half-open [from, to) interval — a scrub calls it never, which is what makes scrubbing silent. listThreejsClips / listThreejsCues / resolveThreejsClip / getThreejsClipDuration read a spec that may have no animation key at all.
threejsEnvironment.js Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. spec.lights are punctual — they light a surface but give it nothing to REFLECT, so metalness, transmission, clearcoat and iridescence read off an environment or read off nothing, and a plausible conductor renders near-black without one. createSculptEnvironmentTarget(renderer, preset) builds a preset locally from three's own primitives and prefilters it through PMREMGenerator — neutral is three's bundled RoomEnvironment, studio a dark shell with three emissive softbox panels plus a floor bounce — returning null for none; the caller owns the render TARGET and disposes it (disposing only .texture leaks the framebuffer behind it). THREEJS_RENDER_PROFILE mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's <Environment preset=…>, which fetches an HDR from a CDN: rendering a local model makes no outbound request. resolveSculptEnvironment(spec) is the client mirror of resolveThreejsEnvironment in server/lib/threejsModel.js, reading a spec with no environment key as the none it was actually authored against.
threejsExplode.js Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. computeExplodeLayout(parts, amount) → { offsets, meshOffsets, unitIds, growth }: separation is a layout scale about the model centre (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where offsets add to a unit's own position and meshOffsets apply to a group around a container's own geometry (moving its group instead would drag its child units along), and growth measures how much the layout actually grew so the camera re-fits on real change. buildPartSelectionIndex(parts) → { owners, ancestry, names } for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and idSchema accepts toString. isReliefPart / isContainerPart expose the shared part definition: a part flagged explodeWithParent is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing.
threejsRig.js summarizeThreejsArticulation(spec) → { articulationReady, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, jointsByPartId } — client mirror of the readiness rule in server/lib/threejsModelRig.js, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no articulation key reads as a static assembly; a graph is ready only when it carries more than a lone root, every child joint names a pivot socket, and every declared attachment names what it hangs from (the anchored attachments list and the older anchor-less attachmentPartIds are merged into one count). jointsByPartId is null-prototype so a provider-authored part id cannot resolve to an inherited function.
threejsSculpt.js Three.js construction helpers for the validated procedural sculpt spec (server/lib/threejsModel.js) used by the Three.js Models preview. createSculptBufferGeometry(definition) builds the schema forms r3f has no direct element for — custom (indexed BufferGeometry), extrude (closed 2D outline + holes swept to depth, optional bevel) and tube (CatmullRom path swept at radius) — returning null for primitives, which stay declarative; callers own disposal. needsSculptBufferGeometry(definition) is the matching predicate. sculptMaterialProps(definition, envMapIntensity) maps a material definition to its Three.js props, forwarding the physical-only channels (clearcoat, ior, transmission, thickness, sheen, iridescence, anisotropy) only for type: physical, and the spec-level environment.intensity as envMapIntensity on every lit material (basic is unlit and takes none). Mirrors the createGeometry/createMaterial bodies buildThreejsFactorySource() emits, so the preview and the exported standalone factory render the same scene.
universeBuilderShared.js Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): TRUNK_TABS/TRUNK_BY_ID/TRUNK_BY_KIND, TAB_* + BUCKET_CANON, CATEGORY_LABELS, DEFAULT_RENDER_OPTS, COMPOSITE_BOARD_KINDS; and helpers groupBucketsByKind, normalizeCategoryKey, humanizeCategory, ensureDraftCategories, getCategoryKeys, compositeKindLabel. No React state — safe to import from the page or any tab component without a cycle.
universeGraphModel.js Vocabulary + derivations for the Universe Builder Graph tab: GRAPH_KINDS/GRAPH_KIND_ORDER, GRAPH_EDGE_TYPES/GRAPH_EDGE_GROUPS (the seven RELATIONSHIP_LINK_TYPES plus the derived attachment/appearance/membership/imageref groups), indexGraph (node map + adjacency + degree/storyDegree), computeUniverseGaps (isolated / empty place / one-directional / no render / co-appearance + lens suggestions — all pure derivations, never an LLM call), evolutionStageRows, neighbourIds, nodeInitials, hexToRgba.
universeGraphLayout.js 2D positioning for the Universe Builder graph canvas: seedPositions (deterministic phyllotaxis), stepLayout/settleLayout (force sim with per-kind collision radius), applyAnchors (radial rings by kind, timeline lanes by first appearance), computeFit, toScreen/toWorld, hitTest, radiusFor, GRAPH_LAYOUTS. Distinct from graphSimulation.js, which settles the Brain/CoS graphs in 3D with no anchors, collision or screen fit.
universeGraphPoster.js Print-ready infographic posters drawn from an indexGraph result: POSTER_LAYOUTS (cast roster, character dossier, place atlas, timeline strip, relationship web), POSTER_SIZES, POSTER_THEMES, posterDimensions, and renderPoster(canvas, opts) — the same call drives the on-screen preview (scale 1) and the 2× PNG download, so they can't diverge.
universeBuilderCounts.js Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what /render will enqueue: totalVariationCount, canonEntryHasContent, countCanonWithContent, renderPromptCount, scopedPromptCount. The server compilePrompts/synthesizeCanonPrompt copy is authoritative — keep in sync.
videoTimelineModel.js Pure model helpers for the layered video timeline, mirroring server/services/videoTimeline/segments.js so the browser preview and the ffmpeg export make the same cut/geometry/mix decisions: segmentDuration/timelineDuration/findSegmentAt (project-time ↔ segment mapping), fadeMultiplier (linear, matching ffmpeg's default tri curve), overlayOpacityAt, audioTrackStateAt, segmentVolumeAt (clipVolume × segment volume × fade — the product the export writes into each segment audio chain, so the preview auditions the mix that renders), assetUrl(assetKind, assetFile), the edit clamps clampTrim (keeps ≥ 1 frame, matching the server's CLIP_TOO_SHORT floor) and fitFadePatch (shrinks an over-long fade pair proportionally instead of letting the PATCH 400), the index summary projectSummary(project, thumbnailFor) (block count / duration / card thumbnail — reads the segments lane, NEVER the derived clips mirror, which omits stills), and the save helpers stripKey/withKeys/timelinePatch. Change a rule here and in the server module in the same commit. Fade fitting re-exports the shared server/lib/videoTimelineFades.js leaf, and the source-span rules come from server/lib/videoTimelineSourceSpans.js: resolvePlaybackLanes(lanes, { sourceDurationFor, bedDurationFor }) turns the authored lanes into what the export renders (clip trims clamped to the history clip length, beds to their measured file length, fades refit; an unknown length keeps the authored span), projectSummary takes an optional sourceDurationFor so the index total agrees.
wrSceneCursor.js Resolve which script scene the editor caret sits in (sceneAtCursor, sceneAnchorIndex) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target.
writingGuide.js Canonical Writers Room reference data + craft principles rendered by the Guide page (/writers-room/guide): WRITING_LENGTH_TARGETS (microfiction→novel word/char bands), BOOK_LENGTH_ESTIMATES (page-based), WRITING_PRINCIPLES, PLANNED_ANALYSES (e.g. the emotional-roadmap evaluator), and classifyByWordCount(n) for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs.
universeMarkdownFilename.js slugifyUniverseName / universeMarkdownFilename — client-side safe filename helpers for Universe Markdown world-bible downloads, kept in step with the server attachment name.
universeMarkdownFilename.cases.js Shared client/server filename contract cases used to keep the browser download name and server attachment name in lockstep.
qrCode.js Deterministic SVG QR code generator for scoped mobile session join links (#5383).
mindBundle.js Persistent Mind portable-bundle format vocabulary, re-exported from the server/lib/mindBundleFormat.js leaf (never copied): file extension, passphrase floor, size cap, export scopes, and the import group ids / source scopes / choice values the import panel renders. The sealing code stays server-side — that module imports node crypto.
publicGuestRoutes.js isPublicGuestRoute identifies standalone guest pages that skip private app bootstrap.
riggingReasons.js Client mirror of the character-rigging readiness reason labels in server/services/rigging/readiness.js: RIGGING_UNAVAILABLE_REASONS (reason code -> user-facing label), RIGGING_REASON_FALLBACK, and riggingReasonLabel(code, fallback?). Render these anywhere a GET /api/rigging/readiness reason is shown; never re-declare the codes. Parity + code coverage enforced by server/services/rigging/unavailableReasons.parity.test.js.
scopeAdherenceReasons.js Re-export of server/lib/scopeAdherenceReasons.js — operator-facing labels for a scope-adherence failure code (SCOPE_ADHERENCE_REASONS, SCOPE_ADHERENCE_REASON_FALLBACK, scopeAdherenceReasonLabel). Every label reads as "no advisory", never as a verdict. One definition, no mirror to keep in parity.
jevHeadReasons.js Re-export of server/lib/jevHeadReasons.js - operator-facing labels for why a trained jev project head cannot be adopted (JEV_HEAD_BLOCKER_REASONS, JEV_HEAD_BLOCKER_FALLBACK, jevHeadBlockerLabel). Each label names WHICH baseline the head lost to, because the stock scorer and the majority class send an operator to different places. One definition, no mirror to keep in parity.
usagePeriods.js The report windows every usage-cost surface offers — USAGE_PERIOD_OPTIONS, DEFAULT_USAGE_PERIOD (what a URL with no ?period means) and resolveUsagePeriod. Shared because ?period is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default.
usageChartColors.js seriesColors(series) — shared provider palette for rolling and monthly usage charts.
usdzExport.js AR Quick Look (USDZ) export for the 3D viewer (#5756): exportSceneToUsdz(scene, { maxTextureSize }) lazy-loads three's USDZExporter and serializes the already-decoded scene to bytes, countSceneTriangles(object3d) measures an object graph against AR_TRIANGLE_BUDGET, and supportsArQuickLook() feature-detects the <a rel="ar"> handoff (Safari on iOS/iPadOS only — never sniff the user agent) so a desktop is offered a download instead of a button that does nothing. AR_MAX_TEXTURE_SIZE bounds the file: USDZ stores every texel raw, with no Draco/meshopt equivalent.
installFailureTask.js Build the CoS task payload behind the installer-failure "Queue agent to investigate" button (#5981): buildInstallFailureTask({ label, stage, error, logs, surface }) → { description, prompt } carrying the installer name, failing stage, error text and a bounded log tail, and installLogTail(logs) (the useInstallStream { kind, text } entries rendered as text, capped at INSTALL_FAILURE_LOG_TAIL_LINES / INSTALL_FAILURE_LOG_TAIL_CHARS so a 1000-line pip stream cannot push a huge body through POST /api/cos/tasks, cutting on a line boundary, redacting the home-directory paths pip/git echo, and neutralizing a log line that would close the prompt fence). Shared by both install modals and LocalSetupPanel so every surface queues the same reproducible context.

| layoutRoutes.js | isFullWidthRoute(pathname) classifies routes that own their scrolling layout. | | navPresentation.js | Sidebar icon presentation and section ordering, separate from the Layout React refresh boundary. |

| musicVideoGrade.js | Shared Music Video grade preset and grain bounds for the composition controls. | | filmLook.js | Shared film look controls, presets, normalizer, prompt vocabulary, the SVG filter markup the editor previews with and the playback-time motion layers (server lib/filmLook.js). | | musicVideoNarrativeEvents.js | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. | | musicVideoImageEffects.js | Music-video image effects (a camera flash that develops over a still shot), re-exported from server/lib/musicVideoImageEffects.js: the effects, labels and develop lengths, sceneImageEffect, imageEffectState. Used by components/musicVideo/SceneImageEffect.jsx and the storyboard animatic. | | musicVideoCutEffects.js | Music-video cut effects (beat toggle, dissolve, fade through black across a cut), re-exported from server/lib/musicVideoCutEffects.js: settings, labels, sceneCutEffect, sceneCutEffects, plannedTransitions. Used by components/musicVideo/SceneCutEffect.jsx and the storyboard animatic. | | musicVideoTransitions.js | Music-video cut transitions (VHS glitches over a cut), re-exported from server/lib/musicVideoTransitions.js: the styles and labels, sceneTransitionSections, transitionGlitchFrames, transitionFrameAt, in-shot glitches (sceneShotGlitchFrames), blockBox and edgeGlows for painting. Used by components/musicVideo/SceneTransitions.jsx, SceneGlitches.jsx and the storyboard animatic. | | musicVideoShotEffects.js | Music-video shot effects at a glance: shotEffects (a shot's start / mid-shot / end effects, read through the render's own transition, image-effect and cut-effect helpers) and shotEffectCounts (every effect option's use per slot, zeros included). Used by the Shots board's card badges and its Effects card. | | musicVideoFrameCapture.js | capturePreviewFrame freezes the displayed animatic DOM, decoded media and canvas layers into an inert SVG and PNG with actual fitting, transforms and film look; lyricFrameCaptureBridge captures the known sandboxed lyric/title canvas layers after an acknowledged seek. Fails on missing, tainted or unsupported layers. |