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

500 KB
Raw Blame

server/lib/ — shared server helpers

Pure / side-effect-free helpers, validators, parsers, prompt builders, and shared constants. Before adding a new helper here, grep this catalog first — if a similar module exists, extend it. When you add a new module, add it to index.js AND add a row here.

Service-layer orchestration (multi-step business logic) lives in server/services/, not here.

Discovery rule

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

The barrel server/lib/index.js is a machine-checkable enumeration of every public surface; server/lib/index.test.js verifies that every non-test .js/.jsx file is re-exported AND appears in this README, AND that no two flat-exported modules share an identifier name.

Namespace exports. The validation modules (brainValidation, digitalTwinValidation, etc.), runners, and storyBible are surfaced through the barrel as namespace exports — barrel.brainValidation.settingsUpdateInputSchema, not bare settingsUpdateInputSchema — because their generic names collide with peers. Direct deep imports (import { settingsUpdateInputSchema } from './brainValidation.js') are unaffected.


Validation (Zod schemas + request validators)

managedVisitorValidation.js — strict scoped managed-visitor credentials, admissions, observations and bounded action schemas.

Module Purpose
appOperationErrorContext.js appOperationErrorContext projects bounded forge scope repair fields for failed update events and history; all other error context is withheld.
checkoutRetirementAdmission.js Durable common-repository publication/cut admission for explicit initialized-checkout quarantine; pending reservations survive restart and block managed checkout mutations until verified recovery.
branchRetirementArchive.js preserveBranchRetirement remains for direct callers and historical tests. Production branch deletion does not call it and does not write data/cos/branch-retirement-archives. Deletion still uses Git's receiver lease and holder guards, then removes the local branch section after the ref is actually gone.
reconcileRetirementEvidence.js Matches exact checkout receipts and recovered-preservation receipts, preserves observation identity across delayed scans, and retains each unresolved checkout incarnation. Legacy observations keep their original generation timestamps. A recreated checkout at the same branch, path and head starts after every older receipt; verified historical preservation does not assert branch deletion.
legacyRetirementTransition.js Freezes archive-era observations for evidence-based reconciliation and retains their original diagnoses and delivery/receipt proofs as audit history, without manufacturing deletion receipts or changing task outcomes.
retirementCheckoutObservation.js Reads a checkout's filesystem identity and verifies its live branch/head before the schedule writer admits a recreated checkout's obligation.
retiredLoraTraining.js Retirement refusal and short-lived admission for retained training data access/removal.
backupSharedAdmission.js Durable cross-process backup cuts and publication leases, with fail-closed owner recovery.
runtimeFilePublication.js Admitted runtime recording updates with rollback of the prior file pair on failure.
maintenanceAdmission.js Durable machine-local workflow drain, cross-process admission permits, continuation ownership and stale-resume fencing.
maintenanceExclusive.js Coordinator-owned exclusive claims, opaque idle observations, durable ownership, one-use fixed-adapter capabilities and verified settlement. Peer credentials alone never grant authority.
peerExecutionAuthority.js Non-rewound receiver execution epoch and restore-owner journal; default-deny on stale evidence or pending/conflicting recovery. Invalidates grants on identity changes and refuses stale epochs.
appDeployFlags.js Shared allowlist of flags PortOS may forward to a managed app's deploy.sh, consumed by socket validation and deployment orchestration without reversing the lib/services dependency.
apiContractSchemas.js Canonical Zod request contracts for externally callable APIs plus zodToOpenApiSchema (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects.
credentialEnvVars.js isCredentialEnvVarName(name) / isNonCredentialEnvVarName(name) / isMaskedEnvVar(name, secretEnvVars): name-convention classifier for credential env vars (API_KEY, TOKEN, SECRET…), shared by provider response masking and the client readiness check. Pure.
codeAnimationAcceptance.js Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure.
codeAnimationContainment.js Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is services/codeAnimation/containedWorker.js.
diceNotation.js Dice notation (NdM[+-K]) bounds shared by the character routes and rollDice: 1–100 dice, 2–1000 sides (#13088). parseDiceNotation (null when out of range), the diceNotationSchema Zod refinement, and requireDiceNotation (400 ServerError).
dockerContainment.js Docker containment profile for untrusted install/build/test runs (#12844), pure: digest-pinned Node images and Node-major selection, buildDockerContainmentRunArgs (read-only /src, work volume, no host env, --network none for validate / per-run proxy network for install), assertDockerMountSource (refuses engine sockets, the data dir, the home and credential stores), the in-container driver that emits a tracked-file patch, volume-init/proxy/network argv and .npmrc registry-host parsing. Runner: services/dockerContainment.js.
dockerContainmentValidation.js Zod schemas for Docker containment: the machine-local dockerContainment settings slice (limits, extra egress hosts, digest-pinned image overrides) and the /api/docker-containment run/pull bodies. Kept out of validation.js to keep that closure narrow.
dockerEgressProxy.js The install phase's egress proxy (#12844): decideEgressConnect (allowlisted host + port, no IP literals), isNonPublicAddress, and DOCKER_EGRESS_PROXY_SOURCE, the builtins-only HTTPS CONNECT proxy program the proxy container runs with node -e.
autofixVerifyContainment.js Containment contract for the autofixer verify command (#12487): Linux bubblewrap argv and seccomp policy that contain a forking test runner, deny network and host sockets, restrict writes to the worktree/scratch and hide credential stores; unsupported platforms refuse verification. Includes the from-scratch verify environment. Pure; the runner is autofixer/sandbox.js#runVerifyCommand.
generatedPreviewSandbox.js OS network-isolation plan for generated preview browsers: macOS Seatbelt or Linux bubblewrap, otherwise refusal. The jail denies IP and the host DNS resolver; Chrome flags are defense in depth. Pure; the launcher is services/htmlComposition/ownedBrowser.js.
generatedPreviewPlaybackSchema.js Strict optional generated-preview clock, preparation, playback-anchor and pause message contracts, plus authored-producer reply contracts and private bridge constants; legacy open and seek payloads remain unchanged.
codeAnimationPackage.js Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, createCodeAnimationPackage and summarizeCodeAnimationPackage; validation never executes or stages code.
socketEventContracts.js Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots.
socketEventInventory.js Cached source-derived Socket.IO event inventory: event names and directions only, with no checked-in manifest or positional source metadata.
agentContextValidation.js Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and advertiseAgentContextTools(scopes) for the opt-in read-only agent-context surface.
validation.js Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the validateRequest middleware + shared helpers (optionalBooleanMap, isSafeRecordId, parseIndexParam, parsePagination). Re-exports the per-domain validation files below so existing deep imports keep working.
taskDataInputCatalog.js Pure catalog and persisted ids for deterministic context sources that scheduled agent tasks can preload before dispatch.
sharedSchemas.js Cross-domain Zod fragments that validation.js and the per-domain *Validation.js files both need, kept in a leaf module so the domain files never import back through validation.js (its hoisted export * from lines would TDZ). grokVideoDurationSchema (grok clip-length union), cloudModelIdString(message) (cloud-CLI model-id charset/bounds), recordRenderPinFields (the imageMode/imageModelId per-record render pin pair), and isSafeSubdirFilter(v) (relative path with no wildcard, .. segment, or leading /), and csvIdsParam({ max, maxIdLength, truncate }) (the ?ids=a,b,c batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): anchorUserExclude / anchorUserExcludes prepend the rsync root anchor (/) to any user pattern that is not already anchored and is not deliberately */**-led, and isSafeExcludePattern (defined as anchorUserExclude(x) !== null, so the two can never disagree) rejects a .. segment, a NUL, or a pattern longer than EXCLUDE_PATTERN_MAX_LENGTH once anchored — one rule shared by backupConfigSchema and services/backup.js#computeEffectiveExcludes, since an unanchored cache/ is an rsync filter that matches at EVERY depth. Mirrored to client/src/lib/backupExcludes.js. Also resolveAutoUpdateConfig(settings.autoUpdate) + the channel/interval constants — same sparse-slice rule for the automatic self-update: omitted enabled means OFF, omitted channel means release, minIntervalHours clamps into [1, 720], resolveBlockersWithAgent defaults on — shared by autoUpdateSettingsSchema, services/autoUpdateScheduler.js, and the settings GET projection.
generationModes.js Shared immutable image/video render-backend alphabets (IMAGE_GEN_MODE[S], QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODE[S], and cloud subsets) plus mediaJobExecutionLane({ kind, mode, remote }) / MEDIA_JOB_EXECUTION_LANES — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules.
mediaJobPreparation.js createMediaJobPreparation() tracks per-job cancellation before cloud providers install a render handle; run, cancel, take, and ids cover preparation, handoff, and bulk cancellation.
imageGenCapabilities.js Per-backend image-gen capability literals, a dependency-free leaf beside generationModes.js: EDIT_INCAPABLE_IMAGE_MODES/isEditCapableMode and the derived I2I_CAPABLE_MODES, the shipped defaults (CODEX_IMAGEGEN_DEFAULT_MODEL/_EFFORT, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL), the AGY_/GROK_ASPECT_RATIOS alphabets, and IMAGE_GEN_PROVIDER_CAPABILITIES (supportsModelOverride, maxInputImages, promptRequiredWithInputImage) with its supportsCloudModelOverride/maxInputImages/cloudPromptRequired readers. The services/imageGen/* modules re-export these, and client/src/lib/imageGenModes.js imports them instead of copying them (#6590).
imageQuotaSignal.js parseQuotaDeferral(text, { now }) — read a provider quota exhaustion that states its own reset out of a failed render's error text, returning { resumeAt, resetsInMs } or null. Requires BOTH an exhaustion marker and a parseable Go-style duration (2h26m1s), because the text embeds the agent's own prose about the page being rendered. Plus formatDeferral and MAX_QUOTA_DEFERRAL_MS. Consumed by services/mediaJobQueue to hold queued renders for a cooling backend instead of burning them against the same wall.
falImageModels.js Curated fal.ai image model catalog, a dependency-free leaf the client imports: FAL_IMAGE_FAMILIES (text + /edit endpoint per family, per-model reference cap, sizing alphabet, pricing), FAL_IMAGE_DEFAULT_MODEL, FAL_IMAGE_MODEL_IDS (the only ids a fal cloudModel may name), falImageFamily/isFalImageModel, falImagePriceLabel, buildFalImageRequest (routes to /edit when input images are present; maps width/height to aspect-ratio + resolution tier or pixel image_size) and estimateFalImageCostUsd (with FAL_MEGAPIXEL, fal.ai's binary megapixel).
imageRuntimeRemedies.js Local image-runtime vocabulary, a dependency-free leaf beside imageGenCapabilities.js: IMAGE_RUNTIME_READINESS (ready/unavailable/unknown), IMAGE_RUNTIME + IMAGE_RUNTIME_LABELS (the shared torch venv vs. the configurable mflux interpreter), IMAGE_RUNTIME_REMEDY (the one action that fixes each unavailable state), and IMAGE_RUNTIME_UNAVAILABLE_CODE. services/imageGen/localRuntime.js builds the diagnosis from these, services/imageGen/local.js tags its pre-flight render refusal with the same remedy, and client/src/lib/imageGenModes.js re-exports them so no component hand-copies a remedy kind.
renderModeLadder.js resolveRenderPins and resolveRenderTargetPins share backend-scoped model candidate inheritance across browser and server. Image-gen mode resolution ladder (#6815), a dependency-free leaf beside generationModes.js/renderTargets.js so the client imports it directly instead of hand-copying it: isModeUsable(settings, mode) (queueable + enabled gate, no per-provider spec lookup), pickUsableMode(settings, candidates) (first usable candidate, falling through disabled pins to the cloud-then-local tail), renderTargetDefaults(settings, target) (the normalized settings.renderDefaults[target] pin), and imageModeCandidates(settings, target, record) (the shared [recordPin, targetPin, installDefault] candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). services/imageGen/cloudProviderConfig.js re-exports the first three for its existing callers.
fableLoomBoard.js FableLoom Board view: fableLoomBoardPath walks one path from an episode's start scene (first choice at each fork unless a picked transition in via) into storyboard beats of panels with each fork's choices, stopping at an ending, a loop or a dead end; fableLoomBoardPick swaps a fork's pick. Browser-safe.
fableLoomLimits.js FableLoom record caps (LOOM_LIMITS) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both.
fableLoomMediaProfiles.js Versioned portable media presets with resolution, bitrate, frame-rate and loudness targets.
fableLoomExport.js Portable package schema/limits, graph/outline/production preflight, canonical cast and approved-voice projections, required media roles and explicit path-free playback/occupancy projections.
cameraMovements.js Shared camera-movement vocabulary (#10589): CAMERA_MOVEMENTS (stable ids with family, energy, snap/still flags, start/end framing and the four-part movement/speed/framing/end prose), normalizeCameraMovement/cameraMovementId/cameraMovementFromText, shotCameraPrompt(camera) (the four-part i2v camera block for a structured shot camera) and cameraMovementCatalogForPrompt. Used by FableLoom, Music Video planning/review and the layered template's cameraRig.js.
fableLoomCameraMovements.js FableLoom names for the shared cameraMovements.js catalog (generated cut direction and the manual scene editor selector); persisted ids are unchanged.
fableLoomPlayback.js FableLoom runtime version, node playback modes, audio occupancy and evaluateFableLoomLiveInput: shared live-input admission for connected decision holds, offscreen presence and safe audio, with legacy playback defaults.
fableLoomParticipation.js FableLoom audience roles (helper vs protagonist), per-scene connection availability, prompt contracts, and backward-compatible defaults.
fableLoomFormats.js FableLoom scene formats (LOOM_FORMATS, asLoomFormat, sceneFormatContract, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage.
fableLoomProduction.js FableLoom production batch planning and topological orchestration: shared still/video render-format presets and story-level image/video provider preferences (16:9 default), ordered episode storyboard gates, DAG resolution, asset enumeration, execution stages, and exact-input provenance verification.
fableLoomContinuity.js FableLoom episodic continuity review: multi-vector deterministic checks for visual entity bindings, convergence clarity, voice profile consistency/drift, pronunciation anchors, and playback safety.
fableLoomOutline.js FableLoom story-first episode beat outlines: bounded log-lines, deterministic arc validation, and compact prompt rendering before teleplay expansion.
fableLoomPlaytest.js FableLoom branching-playthrough harness: bounded exhaustive path enumeration, ending/loop/coverage diagnostics, aggregate loom reports, and compact traces for narrative-quality review.
fableLoomVisualPrompts.js Pure buildFableLoomVisualPrompts render-text composition from resolved scene bindings and allocated references, including shared visual style, continuity, negative tokens and complete Reactor shot validation.
postCognitiveConfig.js Browser-safe limits and joint constraints (COGNITIVE_PAIR_CONSTRAINTS, validateCognitivePair, dependentMin) for the POST cognitive drills with related manual pairs — digit-span start/max length, reaction-time delay window, Go/No-Go stimulus/deadline — shared by the config UI, route validation, and generators.
postDrillTypes.js MeatSpace POST drill vocabularies (LLM_DRILL_TYPES, CACHEABLE_TYPES, COGNITIVE_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator).
speechMatch.js compareSpeech(script, heard) / normalizeSpeech — normalize case, punctuation and number words, then score word-level (character-level for CJK) edit distance; matched at similarity >= 0.90. Used to verify rendered voice-over lines against a speech-to-text pass.
spriteVocabulary.js Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, TURNAROUND_ID, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services.
spriteChromaKey.js Chroma-key selection color math (CHROMA_KEYS, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY, hue-distance picking). Pure color math, no image I/O — that lives in services/sprites/normalize.js.
spriteAnimationTracks.js The animation-track registry (ANIMATION_TRACKS, WALK_TRACK, TRACK_BOUND_TRIPLES, AUTHORED_TRACK_FIELDS) — a zero-import table of per-track frame/fps bounds.
spriteAnimationTrackStore.js The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built.
agentFinalVerdict.js resolveAgentFinalVerdict — the completion outcome finalizeAgent persists, as one pure function of its evidence: the drift > PR > goal-fidelity > output-hook > reported precedence ladder, returned as a frozen { source, success, errorAnalysis, error, completionReason }. A permanent hook rejection escalates an already-failed run only through the caller's pure failureIsTerminal predicate, so the side-effecting retry resolution runs once.
agentOutcome.js Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? isAgentHandoff(agent) — result.resumed === true, what resumeAgent/relaunchAgent stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit. Every consumer that read result.success as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to error — so the rule task-learning already applied lives here once. Reads only result, so completeAgent's stats writer can ask it before the record exists. Keyed on a field resumeAgent has always written, so archived relaunches reclassify retroactively with no migration. Also carries agentHandoffReason(agent) — metadata.pauseReason when a continuation was queued, else result.error, so an abandoned run is not captioned as a deliberate provider swap — and isQueuedContinuation(agent), the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: isAgentHandoff alone is not proof a continuation exists (a stranded pause retirement also stamps resumed: true with nothing requeued), so use this one there. client/src/lib/agentOutcome.js re-exports this file rather than copying it. 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.
cosAgentCompletionOrder.js Wire format + projection rule for the CoS archive completion-order sidecar (data/cos/agents/index.order.json). projectArchivedAgent reduces an archived record to its completion timestamp plus a completed / still-needs-feedback bitfield; encodeCompletionOrder / decodeCompletionOrder round-trip the versioned document, decoding anything unrecognized as empty so the readers repair it by re-reading the day. Shared by the runtime index and the one-shot backfill migration so the two cannot drift.
cosAgentFeedback.js Pure shared eligibility, rating, update-target, and archive-locator predicates for durable CoS feedback actions; mirrored to the client so the queue and Agents tab use the server contract.
agentOutputMarkers.js Status lines PortOS itself appends to an agent's output buffer: SENTINEL_COMPLETION_MARKER (the line ingestDoneSentinel writes just before the agent's .agent-done summary), LIFECYCLE_LINES (every TUI lifecycle line, declared once as a tagged template — the emitter writes LIFECYCLE_LINES.<id>(values) and the reader's pattern derives from the same text), plus isAgentLifecycleLine(line)/stripLifecycleLines(lines), which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with ✅). Pure — shared by the emitters (services/agentTuiSpawning.js and its agentTuiSpawning/ modules) and by readers that must show only the agent's own words (notably the generated PR description).
agentRunEvents.js CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in services/agentRunEventLog.js. AGENT_RUN_EVENT_KINDS (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), agentRunEventSchema (Zod, .strict()), buildRunEvent() which redacts then mints a CONTENT-derived eventId (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, redactRunEventData() (drops prompt/description/output/result-class keys to a { redacted, chars } stub, scrubs the home-dir prefix out of every remaining string via scrubHomePath, runs redactOutput, and caps string/array/key/depth per RUN_EVENT_LIMITS), and projectRunStates() — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one.
agentRunReconcile.js CoS run reconciliation (#4540) — pure diff between a ledger projection (projectRunStates) and the durable run record. Closed finding vocabulary RUN_RECONCILE_FINDINGS (record-open, record-missing, verdict-mismatch, ledger-open), diffRunRecord(), reconcileRunRecords() with a zero-filled per-kind summary, and planRunRecordRepair() — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: services/agentRunReconciler.js.
agentRegistrationRecord.js The registerAgent payload one spawn writes, projected from its task — buildAgentRegistration({ task, provider, … }) plus resolveExecutionMode({ spawnHeadless, useRunner }) (direct / runner / tui / runner-tui, replacing a nested ternary chain). agent.metadata is a HAND-PICKED projection of task.metadata, never a spread: every downstream reader (run cards, perpetualRefillPlan, declaresNoCommitCriterion, the quota-burn continuation, featureAgents) sees the agent record alone, so an unlisted field does not survive the spawn — which is how quotaBurnStepId shipped persisted but unprojected (#6406) while this list was maintained inline in a 900-line orchestrator. Pure and synchronous: primaryCheckoutBaseline and providerEndpoint arrive as VALUES (both were await/service calls inline) keeping this leaf out of the agent-state and local-endpoint graphs.
agentScratchPaths.js Runtime scratch PortOS itself writes into an agent worktree and never commits — PUBLIC_REVIEW_INPUT_FILENAME / PUBLIC_REVIEW_PATCH_DIRNAME (the public-review bundle materialized by services/modelAbuseGuard.js), the AGENT_SCRATCH_PATHS list, prefix-aware matchesScratchRoot(path, roots) and isAgentScratchPath(path). classifyWorktreeDirt (services/worktreeManager.js) subtracts these for EVERY caller and uses the same matcher for its per-call ignoredPaths, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by removeWorktree, held by reapMergedWorktrees, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like .agent-done-<agentId> (agentSentinel.js) is passed per call instead.
agentSentinel.js The .agent-done completion sentinel: DONE_SENTINEL_NAME, doneSentinelName(agentId) → the per-instance filename .agent-done-<agentId> (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), doneSentinelCandidateNames(agentId) → the canonical name plus the bounded one-character truncation recovery candidate for generated ids, doneSentinelPath(workspacePath, agentId) → the canonical path every producer resolves, doneSentinelAgentId(filename) → its inverse ('' for the bare unscoped name, null for a non-sentinel), so the stale-sentinel sweep in services/agentSentinelSweep.js matches leftovers to runs the same way the producer named them, + pure parseSentinelPayload(contents) → { summary, payload }. Back-compat — a plain-markdown sentinel yields payload: null; a JSON object yields its structured payload for a programmatic-I/O task type's processTaskOutput hook. salvageSentinelPayload(contents) (async) is the lenient second tier — runs jsonExtract over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its payload instead of being dropped. extractSentinelPayloadFromTranscript(transcript, isPayload) (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). PROGRAMMATIC_OUTPUT_COMPLETION_HEADING names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know.
persistentMind.js Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. Staleness alone never kills a turn: services/persistentMindSupervisor.js tracks each turn's in-flight provider calls and, before interrupting a stale heartbeat, checks liveness (an open call, and for Ollama-backed providers /api/ps still showing the model loaded); a live thought waits with no fixed cap, while a turn with no open call (e.g. after a process restart) or a gone provider is interrupted as before.
persistentMindAttachmentOwnership.js Reserved screenshot filename and pending-marker ownership shared by Mind uploads, screenshot retention, and manual purge.
persistentMindCapabilities.js Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes).
executionDurationKey.js Shared pure execution-duration key composers/parser, separator and absent-effort sentinel, and minimum execution sample threshold; preserves persisted keys for server writers and browser lookups.
cosAgentListProjection.js What a CoS agent LIST response may carry. toAgentListItem / toAgentListItems drop the transcript and bound metadata.taskDescription to AGENT_LIST_DESCRIPTION_CHARS (2000, on a clause boundary via textUtils.clampToCharLimit), stamping taskDescriptionTruncated + the original taskDescriptionLength so the UI can hydrate the rest from GET /api/cos/agents/:id. That one field was 68% of the Agents tab payload — p50 is 75 characters but a pasted-prompt description runs past 50 KB, and GET /api/cos/agents sits on the first-paint critical path of every /cos/* tab and re-reads every 30s. Applied at the ROUTE layer only: getAgents/getAgentsByDate also feed the weekly digest and CoS reports, which need the whole text.
cosSpawnWindow.js The one settlement for the window in which a CoS task is BOTH pending and active. spawnAgentForTask registers an agent as running before it flips that agent's task off pending, so a surface counting the task list and the agent list independently reports the same task as queued AND active — "1 pending, 1 active" for a queue of one, clearing only on a later poll. Reversing the two writes would not close it (two stores, and the UI joins the lists from two separate HTTP reads anyway). runningAgentsByTaskId(agents) → Map<taskId, agent> (keyed by taskId or metadata.taskId, matching agentManagement.js), isSpawningTask / withoutSpawningTasks / countSpawningTasks / unclaimedTaskIds (the id-list form) and settleTaskSourceSpawnWindow(source, …), which stamps spawning and moves the task from grouped.pending to grouped.in_progress for a RESPONSE — that is how GET /api/cos/tasks spares its consumers from knowing the window exists, while the dispatch readers of getAllTasks() keep the raw truth. Bounded by SPAWN_CLAIM_GRACE_MS (60s, shared with services/cos.js#forceSpawnTask): past it a pending task under a running agent is a zombie, and settling it as active forever would hide the stuck task from every count AND from the list that renders its "Run now" recovery. Pure leaf with no imports, so client/src/lib/cosSpawnWindow.js re-exports it.
cosToolContracts.js Provider-neutral portos_tool catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape.
persistentMindIssues.js Persistent-mind forge-issue contracts: bounded list/file schemas, the required-both dispatch axes, the closed category-label vocabulary with its lazily-created colors, the persistent-mind attribution label, and the title key the duplicate guard compares on.
persistentMindJournal.js Persistent Mind decision journal: typed addressable event kinds (decision/commitment/open_question/risk/goal/preference), the closed append/supersede/resolve extraction contract, the deterministic reducer that rejects unsourced operations and retires by status flip rather than deletion, bounded retention, the untrusted-evidence prompt rendering, and the active-only digest the rollup compacts from. Pure.
persistentMindTrajectory.js Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, bounded strictly-allowlisted per-provider-call execution receipts (route, run id, elapsed time, outcome, usage that stays unknown rather than zero) with their safe public projection, and hard-budget context assembly with explicit empty/missing/failed/stale summary states.
persistentMindProfile.js Versioned, default-off persistent-mind provider profile (enabled, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch.
persistentMindMemory.js Persistent Mind memory protection schema, durable tag encoding, public projection, and protected-first context ordering.
persistentMindPrompt.js Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference.
persistentMindPlaybook.js Continuous-play / explore→interact→reflect→invent Persistent Mind operating modes and prompt framing. Pure.
persistentMindPlaybookPhase.js Maturity-aware continuous-play phase picker (explore/construct/maintain/coordinate) from bounded Eidoverse world signals — density, recent failure rate, active peers. Pure.
metadataFlags.js The one owner of the persisted metadata-boolean rule — isTruthyMeta(v) (true/'true' = set) and isFalsyMeta(v) (false/'false' = cleared); anything else is unset. TASKS.md round-trips flags as strings, so a bare if (metadata.x) is a bug. Pure leaf; import directly, never inject.
mindBundleCrypto.js Persistent Mind portable-bundle container (#7621) — sealMindBundle / openMindBundle / readMindBundleHeader, scrypt-from-passphrase + AES-256-GCM with the cleartext header as AAD. Passphrase-derived, never PRIVACY_VAULT_KEY: that key is machine-bound and a bundle sealed with it could not open on the destination install. Format names live in mindBundleFormat.js.
mindBundleFormat.js Mind bundle format vocabulary, free of node builtins so the browser reads the same definitions (client/src/lib/mindBundle.js) — magic/versions/extension, scrypt parameters, export scopes (PERSISTENT_MIND_BUNDLE_SCOPES), import groups and their source scopes (PERSISTENT_MIND_BUNDLE_GROUPS, MIND_BUNDLE_GROUP_SCOPES, MIND_BUNDLE_GROUP_CHOICES), size/passphrase bounds, and the named refusal reasons (MIND_BUNDLE_REFUSALS, mindBundleRefusal).
mindLocalContextClamp.js RAM/GPU safety ceilings for mind-driven local numCtx adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure.
moltworldExplore.js Pure helpers for server/scripts/moltworld-explore.mjs: pickMoltworldAccount, buildQueueUrl (keyed by the PortOS personality id, never the Moltworld credential), explorerBanner, portosAuthHeaders.
modelInput.js What a model actually received beside what the user wrote (#11317): promptAddition, sentPromptRecord, carriedPromptAdditions, agentInstructionsAddition, and the promptAdditionsSchema request field. Records sentPrompt / sentNegativePrompt / promptAdditions on every render.
motionSkills.js Optional motion-design agent skill packs (HyperFrames, Remotion, Claude Animation) — MOTION_SKILL_PACKS catalog shared by npm run setup:motion and the launch-video form, detectMotionSkills() finds installed skills under ~/.agents/skills / ~/.claude/skills.
persistentMindPublic.js publicPersistentMindState(state) — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. Non-user pause reasons pass through (credential-scrubbed) instead of reading "Paused by user", and lastError (coarse last-wake failure: killed/OOM, canceled, …) stays separate from pauseReason.
persistentMindThinkingPresets.js Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference.
persistentMindChosenName.js Validate and resolve an authoritative chosen-name identity memory, frame first-wake naming, and extract legacy chosen names from protected identity memories (extractPersistentMindChosenName, resolvePersistentMindChosenName) to drive the Eidoverse CoS join id (e.g. Helm). Presence reconnects on its next world action when the chosen name changes.
persistentMindUsageLimit.js Hard provider usage-limit / quota classifier for Persistent Mind wakes (classifyPersistentMindProviderError, isHardProviderUsageLimitError), the dedicated autopause reason string, and probe-backoff helpers so a usage-limit pause can auto-recover when the pinned provider is usable again without treating user pauses the same way.
persistentMindContextBudget.js Local context-budget / known-window-below-request-budget classifier for Persistent Mind wakes (isContextBudgetFitnessError, publicContextBudgetReason), plus actionable pause copy that keeps token counts and a numCtx recovery hint without exposing prompts or secrets.
persistentMindToolActivation.js Pure lease-state helpers for progressive Persistent Mind tool exposure: the TOOL_ACTIVATION_FAMILIES vocabulary, tools.activate/tools.deactivate input schemas, and default/normalize/age/activate/renew/deactivate over a {family: turnsLeft} lease map. Retention is a selection hint only — every consumer still re-checks the real capability grant.
heavyJobClaim.js Cross-process, machine-wide accelerator claim: claimHeavyLocalJob({ kind, id, timeoutMs? }) either acquires an ephemeral data/ lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart.
agentValidation.js Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions.
autonomousJobTask.js generatedJobTaskFields — (+ isExpectedUnpersistedMiss: a scheduled fire never persists its task, so the spawn/finalize status writes miss by design and stay quiet) flattens a generateTaskFromJob result into the top-level keys the non-raw cos.addTask path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure.
qualitySchedulePlan.js Lays a managed app's schedulable quality audits out across a week. planQualitySchedule({taskTypes, fileIssuesByType, busy, options}) → one weekly cron per check plus ONE daily cron for the issue-claim drain that follows each check by claimOffsetHours (placed forward-only, so a drain never precedes the audit it works for); orderQualityChecks topologically sorts the selection by AUDIT_SUGGESTED_AFTER; buildBusySlots(occupancies, options) turns expanded crons into the occupied "<day>:<hour>" cells the placement avoids (which is how a 03:30 release job keeps audits out of its window); resolveQualityScheduleOptions is the ONE default/window/claim-type resolver the planner and its service caller share. Which repo shape each audit needs is catalog-owned (auditCapabilityRequirement), not declared here. Pure: no schedule read, no repo read, no clock.
quotaBurnConfig.js Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, QUOTA_BURN_BOUNDS (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (normalizeQuotaBurnConfig). Owns the dispatch-cap sentinel too (QUOTA_BURN_UNLIMITED_DISPATCHES / isUnlimitedDispatchCap) — -1 means the window is not counted, and is the default. Also owns the retired executor's task-description parser (QUOTA_BURN_TASK_PREFIX / quotaBurnFamilyOfDescription), kept for migration 225, and the run once vocabulary (quotaBurnJobKey / jobIsSpent, plus the two family predicates familyIsConfigured and familyHasRunnableJobs). Pure — no storage, no provider I/O.
quotaBurnDispatchCap.js Leaf (no imports) for the quota-burn dispatch-cap sentinel: QUOTA_BURN_UNLIMITED_DISPATCHES (-1) and isUnlimitedDispatchCap. Shared with the client quota-burn form; quotaBurnConfig.js re-exports both.
quotaBurnLegacyConversion.js The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only jobType) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. planQuotaBurnStepConversion decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (AUDIT_TASK_TYPE_BY_PRESET_ID, inverted from auditCatalog.js), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a buildQuotaBurnCustomJob on-demand custom task addressed by the deterministic quotaBurnCustomJobId (which is what makes a repeated or resumed conversion create no duplicate). legacyAgentTaskMetadata reproduces the retired executor's dispatch posture; applyQuotaBurnStepConversion rewrites the step, preserving id, label, enabled and run-once state. Recognition is matchStoredAuditPreset, never a label or a partial match.
quotaBurnOrigin.js Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. normalizeQuotaBurnProvenance reads the request block (burn-step id always required, plus an attribution — the family whose window is spent, OR the manual maintenanceRunId alone when the run is pinned outside every subscription family — the limiting-window reset and the provider/model/effort overrides); QUOTA_BURN_PROVENANCE_FIELDS is the ONE block definition every persistence and projection hop derives from, spread by quotaBurnTaskMetadata (flat task-metadata keys), quotaBurnAgentMetadata (the agent projection) and read back by quotaBurnProvenance / hasQuotaBurnProvenance, which accept both the flat keys and a nested quotaBurn block; burnPlanOwnsTask / burnPlanOwnsAgent are the ONE rule for whether the family plan (not a manual maintenance run) owns a burn-provenanced task. isManualOnDemandRequest distinguishes explicit runs from automated cadence gates. onDemandRequestMetadata is the single spread both on-demand engines apply. Import-light on purpose — taskScheduleConstants.js declares the origin string and must not drag the quota-burn config graph.
quotaBurnPresets.js FROZEN compatibility-and-migration input (#6381). QUOTA_BURN_PROMPT_PRESETS — ready-made single-focus audit prompts for agent-prompt burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. findQuotaBurnPreset(id); matchStoredAuditPreset is migration 305's recognition rule (match the MISSION half, gated on the shipped contract anchors + headings) and upgradeStoredAuditPrompt is the refresh built on it.
auditSourceEvidence.js Best-effort server-owned audit launch revision and committed-tree inventory digest/count. Mutable workspace state is observed separately; this is not reviewed-file coverage or score certification.
auditCatalog.js getAuditScheduleMetadata derives upgrade-safe display names and cluster labels; AUDIT_RUN_GUIDANCE supplies advisory sequencing. Shared catalog of scheduled AUDIT task types (AUDIT_DEFINITIONS / AUDIT_TASK_TYPES) that can either implement a fix or file tracker issues. Filing presets carry issueLabel (category) plus metricLabel/extraLabels so forge issues can be filtered by focus without putting ids in titles. DO_BETTER_SCOPE_COVERAGE maps scheduled task types to the bundled slashdo scope table; DO_BETTER_LENS_COVERAGE remains a compatibility alias. metricLabelFromSlugPrefix, isFileIssuesMode, isExplicitFileIssuesRequest, FILE_ISSUES_DELIVERY_SETTINGS (the one delivery posture every file-issues lane stamps), auditDoWorkRequiresWorktree, getAuditFilingPreset, modeContractFor, applyAuditModeWrapper. Each quota-burn audit preset maps to a scheduled type here (guarded by auditCatalog.test.js). Pure — no I/O.
auditFindings.js Audit finding register schema, stable root-cause keys, per-agent checkpoints and fix-or-track delivery instructions.
quotaBurnTaskRef.js The quota-burn STEP model: a discriminated scheduled-task reference (builtin task type + validated target app, or custom app-job id whose own scope is authoritative) plus the per-invocation overrides bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). normalizeQuotaBurnTaskRef / normalizeQuotaBurnOverrides / normalizeQuotaBurnParams, the QUOTA_BURN_UNAVAILABLE reason codes, resolveQuotaBurnStepAvailability (catalog passed IN, so this stays pure) / applyQuotaBurnAvailability, quotaBurnStepIsDispatchable, and evaluateOnDemandEligibility — the ONE on-demand gate ladder (enabled / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with taskSchedule.triggerOnDemandTask, with enabledAppIdsByTaskType deriving its per-app input.
quotaBurnValidation.js Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, run once re-arm body).
quotaReset.js parseHumanReset turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); normalizeResetAt/hoursUntilReset compute time remaining without treating unknown values as imminent resets; parseObservedReset pulls the reset a provider stated in its own refusal text, and isObservedBlockActive is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses.
quotaWindows.js Classifies a quota window by PERIOD (windowPeriodHours); classifyWindows splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. windowLabelOf names a window. staleThresholdMs / isLimitStale judge a reading's age against 10% of ITS OWN window period (floored at 5min) — the period-relative "is this reading too old to trust" verdict every quota card stamps. Pure.
cronFields.js Cron FIELD semantics (pure, browser-safe): matchesCronField(value, expr, fieldMin) — the matcher services/eventScheduler.js walks minute by minute with — plus expandCronField(expr, min, max) and cronWeekdayHours(expr) → {days, hours}, the weekday/hour OCCUPANCY view a scheduler planner needs. Sibling of cronValidation.js (syntax/range only); one matcher so a planner reading an hour as free and the walker firing in it cannot disagree. cronWeekdayHours over-approximates on purpose — a dayOfMonth/month restriction lands on an unpredictable weekday, so it reports the whole week.
cronValidation.js Cron syntax + field-range validation (pure, import-free, browser-safe). isValidCronExpression / findCronExpressionError (a user-facing reason string) / isValidCronField / isCronShaped (5-token SHAPE only — the named-cadence detector, never a stand-in for validity), plus CRON_FIELD_NAMES / CRON_FIELD_BOUNDS. ONE implementation shared by services/eventScheduler.js, the CoS schedule + per-app task-type save routes, the app-override schema in validation.js, and the browser cron editor via client/src/utils/cronHelpers.js (#6634). Syntax validity is deliberately separate from whether an occurrence exists in the scheduler bounded search window — a leap-day cron is valid.
recurrenceValidation.js Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron.
appleHealthValidation.js Apple Health import payloads.
appleHealthPoints.js healthPointOrigin and healthPointKey: legacy-aware importer/source identity shared by health ingestion and daily source selection.
brainValidation.js Brain/memory route schemas (search, ingest, edit).
catalogExtractionDraft.js Extraction-only six-type graph schema, strict grounded-output parsing, and conservative chunk identity/edge reconciliation.
catalogIdentityValidation.js Bilateral canonical catalog identity operator and peer evidence schemas.
catalogValidation.js Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope).
catalogMediaLibrary.js Casting reference library helpers: normalize variant/tags/guide, filter by age/era/look/tag, pick up to 4 render guides.
cosValidation.js Chief-of-Staff task/job/loop/learning schemas, the Code-Review settings slice, and the task-metadata sanitizer. createCosTaskSchema's metadata-bound fields are carried onto the task by services/cosTaskIntake.js (parity-checked by its test). The Review-Loop reviewer vocabulary lives in reviewerConfig.js (#5702) and is re-exported flat from here.
creativeBriefLimits.js COMMISSION_NAME_MAX / COMMISSION_INTENT_MAX / COMMISSION_STYLE_SPEC_MAX / COMMISSION_BRIEF_TAG_MAX and CREATIVE_DIRECTOR_GOAL_MAX — the creative brief caps creativeCommissionValidation.js and creativeDirectorValidation.js enforce and the browser forms use as a silent input maxLength. A pure leaf (the schemas pull zod) so client/src/components/creative-commission/commissionForm.js and client/src/lib/creativeDirectorPlan.js re-export one definition instead of copying the numbers.
creativeCommissionSpec.js GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC / resolvedDefault and the quality / aspect-ratio / image-mode / video-mode enums — the generation-param spec creativeCommissionValidation.js builds its Zod schema from and the ability adapters sanitize against. A pure leaf (like creativeBriefLimits.js) so client/src/components/creative-commission/commissionForm.js derives its fields/bounds/defaults from it directly instead of hand-copying them (#6816).
creativeCommissionValidation.js Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. The brief field caps it enforces come from creativeBriefLimits.js; the generation-param spec comes from creativeCommissionSpec.js.
creativeDirectorValidation.js Creative Director project/treatment/scene, inert Video draft preferences, and Create-Suite importer schemas. The directive goal cap it enforces comes from creativeBriefLimits.js.
digitalTwinValidation.js Digital twin document/category schemas, including documentFilenameSchema for safe Markdown basenames across imports, federation and stored document access.
eidoverseValidation.js Eidoverse world-projection schemas — the EIDOVERSE_PROJECTION_SOURCE_KEYS allowlist, the V1/V2 projection recipe union (includes/assets/terrain/scale/districts/environment, with the ..-escape guard on every asset path), and the world augment/say/config-patch route bodies (incl. the 8KB augment-argument cap). Split out of validation.js (#5698), which re-exports it.
filmStyleGrammarValidation.js Zod contract for a film style grammar record (filmStyleGrammarSchema), its field caps (FILM_STYLE_LIMITS), categories, renderable FILM_STYLE_PARTS, the parts selector, and the /api/film-styles/:id params and ?parts= prompt-preview query schemas.
fableLoomValidation.js FableLoom branching-narrative route schemas (loom/episode/node/transition CRUD, weave/branch/review, play turns).
genomeValidation.js Genome upload + search schemas.
identityValidation.js Identity section + chronotype + scheduling schemas.
meatspaceValidation.js Meatspace (location/health log) schemas.
mediaValidation.js Media-generation & local-model infra schemas (LoRA training, local-LLM/Ollama/LM Studio management, media-collection bulk ops).
memoryValidation.js Memory record + retrieval schemas.
modelPersonalityValidation.js LLM personality self-profile test schemas: trait taxonomy (versioned), self-eval + twin-alignment response schemas, run/settings route inputs.
moodBoardValidation.js Mood board + board-item create/update schemas.
musicVideoValidation.js Music Video project/scene/reorder + cached audio-analysis schemas.
notesValidation.js Notes route schemas + safe-relative-path guard.
peerSyncValidation.js Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata).
pipelineValidation.js Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query).
postLlmContracts.js Versioned POST LLM generation/scoring schemas, semantic-verdict validation, and secret-free generator/scorer provenance with explicit legacy normalization.
postRhetoric.js Shared rhetoric evaluator rubric, mode/drill ids, structured evaluator prompt/response validation, and the 40-item fictional gold-reference corpus used by POST background reports and local-model performance checks.
postValidation.js MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log.
privacyValidation.js Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (ssn/passport/drivers_license/financial_account) useForScans hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the PRIVACY_BROKER_CASE_STATES vocabulary.
roundsValidation.js Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — sanitizeRound(raw, builtinIds) and the length/count limits shared with routes/rounds.js.
roundsBounds.js Leaf (no imports) for the rounds tempo band (TEMPO_MIN / TEMPO_MAX) and the partner / harmony-part caps (PARTNERS_MAX / SCORE_PARTS_MAX). Shared with the client rounds editor and metronome; roundsValidation.js re-exports them.
socketPayloadLimits.js Shared 8 MiB media cap and transport ceiling accounting for polling base64 encoding plus 64 KiB framing headroom.
socketValidation.js Socket event payload schemas.
spriteValidation.js Sprite Manager Zod schemas — record import/create/update, reference generate/lock/unlock + fork, walk-cycle generate/approve/reopen/trim, per-track generate/approve schemas built from the animation-track registry, publish binding + runtime contract, atlas publish/compile, and user-defined animation-track create/update. Split out of validation.js (#3873), which re-exports it.
styleSourcePrompt.js universeStyleLines(universe) / moodBoardSection(board) — a resolved universe style guide or mood board (services/creativeStyleSources.js) as prompt text; shared by Code Animation and Creative Commissions.
storyBuilderValidation.js Unified Story Builder session/step schemas.
storyboardValidation.js Storyboards route schemas (board, beat, panel, move, take) built from storyboardVocabulary.js caps; over-limit text is refused, never cut.
telegramValidation.js Telegram bot config + test schemas.
terminalReplay.js stripTerminalQueries(text) — remove response-soliciting terminal sequences (DSR ESC[6n, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits ESC[6n on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (56;3R56;3R…) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT ansiStrip.js, which removes every sequence to recover plain text. createTerminalModeTracker() — observe(chunk) follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and preamble() re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. createReplayBuffer({ maxBytes }) is the export callers want — the ring buffer that owns the bytes and applies both corrections to them (push(chunk) records and evicts, render() returns what an attaching client is handed); services/shell.js holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand.
brainLinkLocalFields.js BRAIN_LINK_MACHINE_LOCAL_FIELDS / stripLinkMachineLocalFields(record) / mergeIncomingLinkRecord(incoming, existing) — the Brain link fields (localPath, clone state, repoIntake, scan/study state) that stay on the machine that wrote them: stripped from synced links, kept from the local copy when a peer record lands.
brainThreads.js Brain THREAD rules (#7664) — the pure half of the bullet journal (a thread is a tracked open loop, never a message thread): THREAD_STATUSES / THREAD_PRIORITIES / THREAD_TERMINAL_STATUSES / THREAD_ACTIVE_STATUSES, isTerminalThreadStatus, isThreadOverdue(thread, now) (never true once finished), threadNextLine (the row's "Waiting on X" / next-action line) and the list comparator compareThreads (pinned, soonest-due, most recently touched, id — NaN-safe for two undated threads). brainValidation.js builds its enums from the arrays, routes/brainThreads.js sorts with the comparator, and client/src/lib/brainThreads.js re-exports the whole module so the tab, the widget and the server agree.
humanActions.js Scheduled human action steps — the pure half: humanActionPlanSchema (a plan of dated steps with explicit instructions, ready-to-paste content and links), humanActionThreadFields (a step as the Brain thread it is stored as, tagged human-action + plan:<key>), buildHumanActionNotes, and humanActionReminderDecision (fire / arm / nothing for one thread, keyed on remindedFor).
threadRefKinds.js Brain THREAD ref vocabulary + route table (#7664) — the one (kind, id) → label/URL registry in the repo. A thread is a tracked topic or commitment (an open loop), never a message thread. THREAD_REF_KINDS is the frozen row-per-kind table (brain records, catalog scraps/ingredients, the five app-native creative kinds, goals/apps/messages/CoS tasks, and the external GitHub/GitLab/JIRA/URL kinds); threadRefUrl(kind, id, context) builds the deep link and threadRefLabel(kind) the chip text, both degrading to null/the raw kind for a kind this build does not know so a peer-sourced ref never throws. isSafeExternalUrl scheme-guards an external id before it can become an href. Pure (no zod, no db, no services) and re-exported by client/src/lib/threadRefKinds.js, which is how pages/CatalogIngredient.jsx renders its inbound-ref chips through the same table. Existence/title lookups live in services/threadRefs.js; a drift guard fails CI when a kind here has no resolver there.

Story & narrative

Module Purpose
editorial/ Extensible editorial-check registry (#1284) — EDITORIAL_CHECKS + fail-fast guards + lookup/state helpers. See editorial/README.md. The runner that executes checks lives at server/services/pipeline/editorial/checkRunner.js.
fableLoomGraph.js FableLoom branching-narrative graph analysis: analyzeEpisodeGraph (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), computeGraphLayers (BFS layering), describeGraphForPrompt (compact text rendering for LLM stages), GRAPH_ISSUE_CODES.
storyBible.js Canonical Character / Place / Object shapes; re-exports BIBLE_LIMITS from bibleLimits.js. Also the reveal-gated canon / spoiler-scoping helpers (#2178): filterCanonForIssue / filterCanonListForIssue / isCanonEntryGatedForIssue (hide or surface-substitute a gated entry in a drafting prompt), canonHasRevealGated + revealGatedCanonRows (for the continuity.premature-reveal check gate/summary).
characterAugmentValidation.js Zod schemas for selective character augmentation (#6417): characterAugmentProposeSchema and characterAugmentApplySchema, both pinned to AUGMENTABLE_FIELD_PATHS. Shared by the Universe cast routes and the Writers Room work-bible routes so the two surfaces cannot drift on which field paths a proposal may name.
characterEvolution.js The OPTIONAL five-stage character evolution lens (#6440): EVOLUTION_STAGES / EVOLUTION_OUTCOMES / EVOLUTION_STAGE_LABELS / CHARACTER_EVOLUTION_LIMITS, sanitizeCharacterEvolution + sanitizeCharacterEvolutionList (null when unauthored, unknown stage/outcome rejected not coerced), evolutionEvidenceStatus (derived on read — only anchored counts as verified, a pointer to a deleted beat reports stale), isDeclaredEvolution, renderCharacterEvolutionForPrompt + renderCharacterEvolutionListForPrompt (a whole cast as one prompt block), and the per-character story-list primitives the three hosts share (isCanonCharacterId, isStoryBeatId, characterIdentityKey, optIssueNumber, EVOLUTION_EVIDENCE_FIELDS — Pipeline series, FableLoom, and the Writers Room segmentId + anchorQuote pair whose quote is what keeps a positional segment anchor from reading as verified after a draft edit). A pure leaf over bibleLimits.js + textUtils.js so client/src/lib/characterEvolution.js mirrors it into the browser bundle.
characterEvolutionCoverage.js Branch coverage for the evolution lens (#6444): analyzeCharacterEvolutionCoverage walks every bounded playthrough and flags EVOLUTION_UNEARNED_INHERITANCE — a stage proved on one incoming branch of a reconvergence and not another, so a viewer inherits a change they never watched be earned — plus unproven declared endings, out-of-sequence stage anchors and dead evidence pointers (EVOLUTION_COVERAGE_CODES). Introduces unreviewed (EVOLUTION_COVERAGE_STATUSES): a bounded-out enumeration, a cycle or an unresolvable anchor is explicitly NOT verified and NOT a defect. Deterministic and provider-free; returns null when no lens is authored, so a loom that never opted in is byte-identical.
characterEvolutionValidation.js Zod schemas for the evolution lens — characterEvolutionSchema (one lens), characterEvolutionStageSchema, characterEvolutionEvidenceSchema and characterEvolutionListSchema (the FableLoom plan's per-character list). Its own module rather than a sharedSchemas.js fragment so validation.js (which nearly every suite reaches) doesn't grow an eager edge for a shape only two hosts validate.
characterFramework.js The narrative-character framework as one definition: CHARACTER_ARC_TYPES, CHARACTER_FRAMEWORK_TEXT_FIELDS / CHARACTER_FRAMEWORK_FIELDS (the Ghost→Wound→Lie→Need→Want chain plus motivations, arc type, secrets, relationship links, the psychology profile and the Three Sliders), CHARACTER_FRAMEWORK_LIMITS, the psychology/slider/link vocabularies re-exported by storyBible.js (PSYCHOLOGY_DRIVE_AXES, PSYCHOLOGY_ASSESSMENTS, CHARACTER_PSYCHOLOGY_TEXT_FIELDS, CHARACTER_PSYCHOLOGY_LIMITS, CHARACTER_SLIDER_AXES, RELATIONSHIP_LINK_TYPES), and pickCharacterFramework / pickCastFramework (framework-only projection for an author-side review prompt, empty entries dropped). A pure leaf over bibleLimits.js so the store editableFields, the Zod schemas, and the client editors share one list (#6417).
characterIntegrityVocabulary.js The vocabulary the cast-integrity contract (#6415) reports in, as a pure leaf: INTEGRITY_FINDING_KINDS (missing / underspecified / contradictory) and the machine-repairable AUGMENTABLE_FINDING_KINDS, the five INTEGRITY_DIMENSIONS (+ INTEGRITY_DIMENSION_IDS), CHARACTER_REVIEW_STATUSES (passed vs not-reviewed / truncated / stale) and the INCOMPLETE_REVIEW_STATUSES that can never read as clean, INTEGRITY_DEPTHS, and castIntegrityPassed(report). Split out of characterIntegrity.js (which reaches crypto through storyBible.js) so client/src/lib/characterIntegrity.js re-exports one definition for the report UI.
characterIntegrity.js The shared cast-integrity contract (#6415), stated in characterIntegrityVocabulary.js's terms: characterIntegrityDepth (minor roles / flat arcs / an explained unknown psychology get lighter requirements), the no-provider characterCompletenessFindings / buildCastIntegrityReport, the validating mergeSemanticFindings, and characterFingerprint (reports are derived, never persisted — the fingerprint is what makes a stale one detectable).
castIntegrityPrompt.js The prompt-facing render of a characterIntegrity.js report (#6415): renderCastIntegrity (gap rows first, header always kept, so a budget-truncated block can never read as a clean cast) and INTEGRITY_DEPTH_NOTES (the explained / light / full rulings in the reviewer's own words). Shared by the Series foundation judge and the FableLoom whole-series editor so the two cannot drift on what a light character owes.
bibleLimits.js BIBLE_LIMITS — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of storyBible.js (which pulls crypto + fileUtils) so catalogTypes.js and the browser bundle can read the numbers alone.
storyboardBeatExtract.js Beats from a plot summary: beatExtractInstructions (the visible block sent ahead of the plot), beatExtractPrompt, parseExtractedBeats (a model's JSON answer reduced to beats and panels a board holds), BEAT_EXTRACT_LIMITS. Browser-safe.
storyboardFit.js Fit to song: fitStoryboardToSong places a storyboard's beats on a music video's analyzed song (snapped to sections, sung lines or downbeats; picked starts win) and returns one shot per panel with its panelId/panelRev; storyboardFitSong reads the song from a project; storyboardPanelRev fingerprints a panel, storyboardPanelArt gives its selected art as a gallery image (the shot's frame reference), and storyboardShotPanel reads a fitted shot's panel as current, changed or missing; STORYBOARD_FIT_MIN_SHOT_SEC. Shared by the Plan step preview and the write. Browser-safe.
storyboardSongBrief.js A storyboard's beats as a song map: storyboardSongSections (role, target length, energy, mood, lyric theme per beat), storyboardSongBriefText (the paste-ready brief), storyboardTimeline (the animatic's timing: panel holds, beats pinned to temp-track marks, the runs before them fitted) / STORYBOARD_DEFAULT_HOLD_SEC. No model call. Browser-safe.
storyboardRecipe.js Storyboard panel maker recipes: node types and ports (RECIPE_NODE_PORTS: text, system, llm, references, image, panel), defaultPanelRecipe (Text → Prompt writer + System prompt → Image + References → Panel), sanitizeRecipe (edges join matching ports, no cycles), recipeRunOrder, nodeInputValue / nodeOutputValue (what flows into a node for one panel), sanitizePanelMake (per-panel run state), STORYBOARD_RENDER_SIZES. Browser-safe.
storyboardRecord.js Shared Storyboard record (Create › Storyboards): sanitizeStoryboard (beats → panels → art takes, catalog refs by id), sanitizeTake, summarizeStoryboard (with runtime), sanitizeSavedRecipe (a saved recipe library entry).
storyboardVideo.js Start a Video from a storyboard: storyboardVideoPlan turns a board's panels into Video (Creative Director) treatment shots (intent, prompt from action/framing/camera, whole seconds capped at 10, catalog ids) with the treatment text and a problem when the board can't make a Video; STORYBOARD_VIDEO_LIMITS. Shared by the drawer preview and the write. Browser-safe.
storyboardVocabulary.js Storyboard ids (isValidStoryboardId, newStoryboardId, isValidStoryboardRecipeId), vocab (STORYBOARD_MUSICAL_ROLES, aspect ratios, art styles, framings, take sources) and STORYBOARD_LIMITS. Browser-safe: the client editor imports it.
storyArc.js Canonical Arc + Season + Reader-Map shapes, plus sanitizeSeriesDesign/renderSeriesDesign for author-owned series intent.
storyArcLimits.js Pure canonical length/count caps and series-design field/mode contract shared by sanitizers, schemas and browser editors.
styleGuide.js Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): sanitizeStyleGuide + renderStyleGuide generation block + enums.
storyBuilderSteps.js Unified Story Builder ordered step definitions + helpers (STEPS, STEP_IDS, STEP_STATUSES, isValidStepId, stepIndex).
storytellingCraft.js The storytelling rubric the autobiography feature scores a story against — pure (no I/O, no clock, no provider call): STORY_CRAFT_MOVES (the seven moves — curiosity, tension, specificity, pace, the unexpected, the warmth-closing personal detail, the takeaway), CART_STAGES (Context/Action/Result/Takeaway), buildStoryCraftEvaluationPrompt({question, story}) and normalizeStoryCraftEvaluation(parsed). Rubric source: Shannon Jenkins, How to Tell Stories Better Than 99% of People. The normalizer emits every move and stage in canonical order whether or not the model returned it, so a truncated answer reads as uncredited rather than silently shortening the rubric.
streamLines.js createLineReader(onLine, {splitRe?, maxCarry?}) + createOutputTail({budget?}) — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across data chunks and flush()es the final unterminated line on close; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). splitRe: /[\r\n]+/ handles torch/tqdm bare-\r progress redraws. createOutputTail is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — used by streamingSpawn.js.
storyBuilderIntegrity.js Pure staleness hashing for the Story Builder (hashUpstream, computeStaleSteps, computeSyncDrift).
projectStoreKit.js Shared project-store sync normalization, LWW batch decisions, and tombstone selection for file and PostgreSQL adapters.
canonPrompt.js Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; flattenCanonDescriptorFragments / mapCanonDescriptorFragments / descriptorForCanonEntry.
scenePrompt.js Scene-prompt composer + bible matchers (chars/places/objects in text).
proseExportSettings.js Per-series prose-export settings (#2181): sanitizeProseExportSettings + resolveExportSettings + TRIM_SIZES/INTERIOR_FONTS for the manuscript/ePub/PDF exports.
shotGrammar.js Pure shot-grammar vocabularies (SHOT_TYPES, SCREEN_DIRECTIONS) + normalizers (normalizeShotType, normalizeScreenDirection) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the visual.shot-continuity editorial check (#1315).
storyboardScenes.js Durable ids + id-first addressing for stages.storyboards.scenes[] (#3413). ensureStoryboardIds(scenes) stamps a deterministic scene-NN / shot-NN id on any entry lacking one — and re-stamps later copies of a DUPLICATE id (collision-escaped with a -2 suffix, so peers and concurrent readers derive identical ids); resolveStoryboardTarget(list, { id, index }) → { index, record, matchedBy, stale } resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting stale: true (409, never an index retarget) when a captured id is gone.
seasonStructure.js Season/episode structure recommendation.
seriesAutopilotDefaults.js SERIES_AUTOPILOT_DEFAULTS, the immutable pipelineEditorialChecks defaults shared by Series Autopilot's runtime resolvers, foundation judge, and options panel.
seriesCharacterArc.js Per-character story-arc shapes (series.characterArcs[]): want/need, start → end state, transition beats. CHARACTER_ARC_LIMITS / TRANSITION_KINDS + TRANSITION_KIND_LABELS / CHARACTER_ARC_STATUSES (a pure leaf — the arc editor in PipelineSeries.jsx imports the caps, kinds and labels, so no Node built-in here; ids come from uuid.js). Sanitizers + renderCharacterArcsForPrompt for the arc.transitions editorial check, characterArcEvidenceRefs (the transition-id set a lens anchor resolves against), and renderCharacterEvolutionsForPrompt — the cast-level render of characterEvolution.js's five-stage lens the character-arc checks and the arc planner share.
layeredIntelligenceRejectionLabels.js REJECTION_REASON_LABELS — the one token→prose gloss table for the Layered Intelligence proposal-rejection taxonomy, shared by services/layeredIntelligenceRejections.js (prompt blocks) and the client outcomes dashboard (utils/layeredIntelligenceReasons.js). Pure leaf.
llmRoutePin.js The per-record LLM route pin { providerId, model, effort } — LLM_ROUTE_PIN_LIMITS + llmRoutePinSchema (door check, effort as the shared EFFORT_LEVELS enum), sanitizeLlmRoutePin(raw) (trim/cap, null for an all-empty pin), and resolveLlmRoutePin(pin, perCall) → { providerId, model, effort, providerMatchesPin }. Owns the never-cross-providers rule once, in its two shapes: resolveLlmRoutePin merges a record pin with an independent per-call pick per FIELD (guarded by a provider-id comparison), while pickLlmRoutePinLayer(...layers) + llmRoutePinNamesProvider(layer) take the most specific layer WHOLE for pins whose provider and model were chosen together in one control (falling through to the base layer). Consumed by seriesLlmOverride.js, FableLoom's play pin, and the Creative Director stage pins.
seriesLlmOverride.js Pure resolveSeriesLlmOverride(series, { overrideProvider, overrideModel }) → { provider, model, providerMatchesSeries } — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches.
catalogBulkParsers.js Dependency-free markdown/CSV/JSON parsers for POST /api/catalog/bulk-import and YAML/markdown serializers for GET /api/catalog/export.
catalogChunking.js Pure lossless scrap-text chunker (chunkRawText, CATALOG_CHUNK_MAX_CHARS) — splits a long paste into ≤maxChars chunks on paragraph/newline/sentence/whitespace boundaries so the catalog extractor processes each child and unions results.
catalogSourceKinds.js Catalog scrap SOURCE-KIND registry — one { id, label, factual } entry per ingest path that mints a catalog_scraps row. A pure leaf (no zod, no db) so the extractor can read a path's lens without pulling the validation layer in behind it. SCRAP_SOURCE_KIND_IDS is the id list catalogValidation.js builds its local-ingest Zod enum from; isFactualSourceKind(id) answers "is this lived material rather than invented fiction?" and gates the {{#factual}} sections in the four catalog extraction prompts — an unknown kind (including one a newer peer synced in) reads as non-factual, which is the pre-#7609 behavior. The universe record carries its own federated factual flag (#7616, set on the shipped universe-reality world); it becomes the primary signal once ingest is bound to a universe (#7615). Declaring the lens beside the id is what stops a new ingest source silently extracting a memoir as fictional role tags.
catalogTypes.js Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record payloadSchemaVersion + upgraders, per-type defaultTags. Also exports the relation-kind registry and the tag-taxonomy helpers (canonicalTagKey, tagIdForKey, defaultTagsForType). The client projects its UI registry from this one (client/src/lib/catalogTypes.js) rather than copying it.
catalogUniverseTags.js Pure transform that rewrites legacy machine universe tags (from-universe, universe:<id>) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured catalog_ingredient_refs link. Used by the boot-time repair and the bible→catalog backfill.
comicScriptParser.js Marvel/DC-format comic script parser.
aspectRatio.js Describe a pixel canvas as the ratio phrase a prompt can use — aspectRatioTerms(w, h) (bounded best rational approximation, so 1096x1536 reads as 5:7 rather than 137:192) and aspectRatioPhrase(w, h) → "5:7 portrait" / "16:9 landscape" / "1:1 square". Use it wherever a prompt has to state a framing the canvas already fixes, so the sentence and the canvas cannot drift. Pure.
audioBeatDsp.js Shared beat/tempo DSP core (#9424) used by both beatGrid.js and services/musicVideo/audioAnalysis.js: decodeAudioToPcm (ffmpeg → mono f32 PCM, capped at MAX_ANALYSIS_SEC), Hann/FFT helpers, onsetEnvelope (spectral flux + RMS energy), estimateTempo (full-track autocorrelation over 70-180 BPM with a windowed, clustered fallback for tracks with a variable intro/outro), fitBeats, pickDownbeats. Exported as the audioBeatDsp namespace from the barrel.
audioFingerprint.js Loudness fingerprint of a stretch of a song (#9266): computeRmsEnvelope(path) decodes a file once to a 100 Hz integer-dBFS RMS envelope on the song's own frame grid, windowFingerprint(envelope, { startSec, endSec }) stores a window of it (base64 Int8Array, ≤3 KB for 30 s), and compareWindowFingerprint(fp, envelope) says whether a newer master still carries that window (Pearson ≥ 0.98 and mean |ΔdB| ≤ 1.5 above a −60 dB codec-noise floor). Lets a lip-sync take survive a re-master that changed audio outside its window. envelopeOffsetSec(reference, candidate) cross-correlates two envelopes and returns { offsetSec, correlation } (where the reference's sound starts inside the candidate, refined below a frame) or null on a weak match — used to line a padded provider clip up with its source window (#11210).
composeStyledPrompt.js Compose user prompt + negative with an optional style preset, or an array of presets layered in order. stylePromptAdditions(preset) lists what a compose folds in as labeled additions (#11317). Re-exported (unmodified) by client/src/lib/composeStyledPrompt.js.
scriptVideoCompiler.js Compiles a scene script + bible into beat-level continuous-video clip specs (duration/frame-grid snapping, byte-stable descriptor injection, chain-length fresh-cut rule).
creativeDirectorPresets.js Locked-at-creation aspect ratio + quality presets for the Creative Director.
creativeLatitude.js The IP-latitude clause every creative LLM request carries (withCreativeLatitude, CREATIVE_LATITUDE_TOKENS), plus the one creative-vs-operational table both stamp keys are matched against (isCreativeStage for stage names, isCreativeRunSource for run source tags).
universeBibleCompleteness.js Is a universe bible entry actually described? The shared per-kind expand-field vocabulary (BIBLE_EXPAND_FIELDS, BIBLE_CORE_FIELDS) and the core/full completeness predicates the quota-burn describe job scans with. Pure.
universeBibleLimits.js Universe bible field size limits shared between server (sanitizer, pipeline) and client (form inputs).
universeMarkdown.js universeToMarkdown(record) / parseUniverseMarkdown(text) for the Universe Builder's Markdown world-bible export and import, plus safe download filename helpers.
universePromptRenderers.js Renderers that turn a universe's categories map + canon into prompt context, including the authored character-engine block and the shared story canon digest.
universeExpandMerge.js Pure lock/preserve/dedupe merge of a Universe Builder expansion into a universe draft: mergeExpandIntoDraft(draft, result, {mergeInfluences, ensureDraftCategories}), extractPreservedFromDraft, mergeVariations, mergeCanonByName (existing wins; name/alias/slugline identity). The one definition shared by the Universe Builder client (client/src/lib/universeBuilderExpand.js re-exports it) and the Story Builder server step.
universeVisualStyle.js The style a universe contributes to an IMAGE prompt: buildVisualStyleClause(universe, {override, mode}) (curated influences.embrace tokens + a series stylePromptOverride, NEVER the free-text styleNotes, which is writing-stage direction), universeStylePreset(universe, series) (the {prompt, negativePrompt} preset composeStyledPrompt consumes — the one definition shared by the browser and the FableLoom visual-canon compiler, client/src/lib/universeStylePreset.js re-exports it), universeAestheticLine (the labeled variant canon sheet/LoRA renders lead with), universeVisualStyleTokens, joinInfluenceList (thin trim+join over one chip-token list, re-exported by server/services/universeBuilder/compile.js), splitPromptTokens, stripStyleClause(text, clause) (removes the copy the browser already prefixed, so the compiler keeps the LEADING one — matched on the joined clause so a token with its own punctuation like M.C. Escher still matches) and mergeNegativePromptTokens (token-level union of comma-joined negatives).
writersRoomPresets.js Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS).
writersRoomStylePresets.js Curated style presets for storyboards + universe.

Prompt & AI

Module Purpose
aiToolkit/ Vendored toolkit (providers + runner + prompts + status). See aiToolkit/index.js. aiToolkit/endpointGuard.js is the public SSRF / key-exfiltration guard for provider endpoint URLs (evaluateSecretEndpoint / assertSecretEndpoint) — import it from there, not from internal/. aiToolkit/internal/ollamaBacked.js also declares clampToRuntimeContextWindow(provider, planned) — what an Ollama num_ctx means to a context window: an upper bound over every planning rung (a typed override included), and the answer when nothing else declared one. The budgeter (services/stageRunner.js), the pre-dispatch gate (aiToolkit/providerStatus.js#knownContextWindow), the untrusted-content abuse guard (services/untrustedContent.js, via knownContextWindow — a deep import kept off stageRunner.js's heavier closure since it sits on a request path) and the browser's provider-card meter all import it from there rather than restating it (#7466, #7473).
aiToolkitState.js Module-level singleton for the toolkit instance shared by the providers/runner/promptService shims — setAIToolkitInstance / requireToolkit (throws AI_TOOLKIT_NOT_INITIALIZED) / getAIToolkitInstance (no-throw for cleanup paths).
antigravity.js Antigravity (agy) CLI provider helpers — id/sentinel constants (ANTIGRAVITY_CLI_ID, ANTIGRAVITY_CONFIGURED_DEFAULT, LEGACY_GEMINI_*), isAntigravityCommand/isAntigravityCliProvider predicates, and ensureAntigravityPrintArgs(args, {model, effort})/ensureAntigravityTuiArgs(args, {model, effort})/stripAntigravityUnsupportedArgs argv normalizers. parseAntigravityModelList(stdout) parses agy models rows — accepts both the modern <id>\t<Label> shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's internal/antigravity.js; used by both the provider-catalog refresh and Image Gen's agy model picker). isAntigravityModelId(id) is the same id shape as a bare predicate, for spawn sites building an agy --model argv from a value no route schema bounded. The strip drops legacy Gemini --yolo/-m/--output-format but PRESERVES the long --model (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject --model/--effort from the per-run overrides, always ahead of the trailing --print marker whose value is the prompt.
llmText.js Pure LLM-output text helpers — stripCodeFences (unfence a model reply) and parseLLMJSON (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration.
providerCooldown.js Provider bench policy — resolveProviderBench(analysis) → null (don't bench) / a usage-limit marker / an unavailable marker with the per-category cooldown from COOLDOWN_MS_BY_CATEGORY. Declines to bench request/response-specific categories (isRequestSpecificCategory / isSchemaTypeCategory) so one bad model id or off-shape response can't take a healthy provider offline. Shared by services/promptRunner.js (prompt cascade) and services/agentFinalization.js (finished CoS agent run) so both bench a category for the same window. Pure.
reviewerConfig.js Review-Loop reviewer vocabulary (split out of cosValidation.js, #5702; Zod-free): the reviewer roster + aliases (REVIEWER_VALUES / REVIEWER_ALIASES / DEFAULT_REVIEWER), the local-LLM / PortOS-only / model-capable / effort-selectable subsets, the slug→CLI-binary map (REVIEWER_CLI_BINARIES, isCliReviewer, reviewerCliBinary), the keyed model/effort/max-rounds pin normalizers + resolvers (normalizeReviewers, normalizeReviewerModels, normalizeReviewerEfforts, resolveReviewerGroup — task reviewer overrides fall back through system tiers when paused, resolveReviewerConfig, resolveReviewPolicy — the whole reviewer config plus stop-mode and the public-forge reviewerApplies clamp as ONE frozen reviewPolicy the prompt builders take, resolveClaimReviewerConfig, KEYED_REVIEWER_PINS), the override-key rosters that say when a task has pinned its own reviewers (REVIEWER_OVERRIDE_KEYS — everything the picker writes and its reset clears; REVIEWER_LIST_OVERRIDE_KEYS / hasReviewerOverride — only the keys that can change the resolved LIST), and the emitters that render a reviewer set into slashdo argv (buildReviewWithArgs — which emits --reviewer-applies only alongside an APPLY_CAPABLE_REVIEWERS slug, the reviewers slashdo lets edit the tree, buildReviewersCsv) and into agent-prompt notes (buildReviewerPinNote, buildReviewerEffortNote). Re-exported flat by cosValidation.js, so existing validation.js imports keep resolving. Provider-backed identities use provider:<id> (isProviderReviewer, isReviewer, isToolFreeReviewer) and additive providerModels defaults; legacy scalar pins stay compatible. REVIEWER_CONFIG_FAULT_CODES / isReviewerConfigFault name the refusals a caller fixes by changing configuration (no model, missing/disabled provider, missing CLI command or unsupported explicitly restricted transport) rather than by retrying, so a reviewer that can never answer is not mistaken for a transient outage.
reviewerHealth.js Dependency-free activeReviewerGroupIndex (shared runtime/editor pause selection), bounded malformed-review diagnostics and finish metadata, reviewer configuration-fault vocabulary, reviewerCommandPermissionFailureCode for explicit headless command-permission refusals, and reviewerAccessFailureCode, which recognizes explicit structured OpenCode access refusals without treating generic HTTP or transport failures as permanent faults.
providerPrerequisites.js Can a provider run on this host AT ALL — providerPrerequisites(provider, { runtime, gatewayKeySet }) → { met, missing: [{ code, label }] } (CLI binary on PATH, API key stored for a public endpoint, the sibling key a gateway-backed wrapper inherits from the API record of its own gateway id unless it carries its own), plus providerRuntimeKey (null for an API provider, for a command carrying an explicit path, and for a provider with its own PATH in envVars — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), isPrivateNetworkEndpoint (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/.ts.net/single-label hosts need no key) and describeMissingPrerequisites. runtime: null = NOT PROBED and never counts as missing. Feeds BOTH GET /api/providers and the fallback chain in aiToolkit/providerStatus.js (via services/providerPrerequisites.js), so a NEEDS SETUP card and the router read one computation (#4611). ROUTING_BLOCKING_CODES/blocksRouting(missing) narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure.
tuiShellLaunch.js buildTuiShellLaunch(provider) → { commandLine, env } for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via tuiHandshake.js#buildTuiInvocation (so the vendor posture flags and --model/--effort injection match a real TUI spawn) and the env via cliChildEnv.js#composeProviderEnv. The env is why this is server-side and the deep link carries only a provider ID: a TUI provider's backend lives in envVars (ANTHROPIC_BASE_URL for an Ollama-backed or Bedrock claude, OPENCODE_CONFIG_CONTENT for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted '***' env reads truthy).
tuiHandshake.js Shared TUI invocation + paste-handshake constants. Also owns SUBMIT_KEY — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt.
tuiUsageScrape.js scrapeTuiUsage({ command, slashCommand, … }) + USAGE_SANDBOX_DIR — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels --print can't reach).
stageModelTiers.js The prompt-stage model/judgeModel tier vocabulary (#8149): STAGE_MODEL_TIERS (default + the shared MODEL_TIERS), STAGE_MODEL_TIER_OPTIONS (the picker rows every stage model select renders), LEGACY_STAGE_MODEL_TIERS (quick→light, coding→medium, still readable from older peers/backups), canonicalStageModelTier, isStageModelTier (tier vs model-id pin). Pure — the client re-exports it.
stagePinPolicy.js Run-scoped "ignore per-stage LLM pins" switch (AsyncLocalStorage) — withStagePinsIgnored(ignore, fn) marks an async subtree, stagePinsIgnored() reads it, and services/stageRunner.js#effectiveStage enumerates which stage-config fields it strips. Backs Series Autopilot's "use one provider/model for every stage" option.
promptSectionRenderer.js renderOrPrependSection(prompt, token, heading, block) — replace a token in a prompt template (with a function replacer for $ safety), or prepend the block with an optional heading when the token is absent; a fallback for customized prompts that dropped the token. Shared by the CoS user-action section renderers.
promptSystemStages.js Prompt-stage protection, split in two (#3335). CURATED (badging): SYSTEM_STAGE_USAGE (key -> usedBy[] feature-name copy), SYSTEM_STAGE_KEYS, isSystemStage(key), systemStageUsedBy(key) — what GET /api/prompts ships and the Prompt Manager badges/filters; adding a row is a per-stage product decision. DERIVED (deletion): STAGE_CALL_SITES / stageReferencedBy(key) from the generated manifest, unioned with the curated set into isProtectedStage(key) / PROTECTED_STAGE_KEYS — what the DELETE /api/prompts/:stage force-guard and canDelete consult.
promptStageCallSites.generated.json Generated stageKey -> [server source paths] index of every prompt stage server/ names by literal key (plus interpolated-prefix stages like pipeline-panel-${id}). Regenerate with node scripts/generate-prompt-stage-call-sites.js; scripts/generate-prompt-stage-call-sites.test.js fails on drift. Never hand-edit.
promptTemplate.js Mustache-flavored, dot-notation-aware prompt template engine.
promptPartials.js Mustache-style partial expansion.
promptFencing.js Fencing for untrusted text spliced into an LLM prompt. fenceBlock(label, text, maxChars) truncates, collapses every run of 3+ backticks to ''' so the content cannot terminate its own fence, and wraps the result as a labeled ```text block; neutralizeFences / clampText are the two halves on their own. UNTRUSTED_CONTENT_NOTICE is the standing "fenced content is data, not instructions" line a prompt places above its fenced sections — the fence stops delimiter escape, that line is what makes an in-band directive inert. UNTRUSTED_REFERENCE_NOTICE labels memory and twin store content as reference data. UNTRUSTED_PULL_REQUEST_NOTICE is its counterpart for a prompt that sends an agent to READ a pull request off the forge (nothing is fenced because nothing is embedded) — shared by services/prRemediationFollowUp.js and services/prDoReviewTask.js. Used by services/aiDetect.js, whose prompt splices a scanned repository's package.json/config/README into a prompt that yields an executed startCommands. neutralizePromptTags breaks <portos-…> delimiters inside untrusted text so a body cannot close its own block and forge the user-authored one that follows.
mediaModelBuckets.js Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — mlx (Apple MLX runtimes) vs cuda (plain torch+CUDA, which runs on Windows and Linux) — not by operating system, which is why activeVideoBucket() keys on process.platform === 'darwin' instead of on "is this Windows". readVideoBucket / readVideoDefault / matchesVideoBucket resolve the canonical key first and fall back to the pre-#4142 macos / windows / defaultMacos / defaultWindows spellings, so any registry written by an older install still loads untouched; canonicalizeVideoBuckets performs the one-time rename (migration 270 and the load-time twin in mediaModels.js). Kept separate from mediaModels.js so scripts/migrations/ can share the alias resolution without importing the registry loader, which seeds data/ as a side effect.
mediaModels.js Single source of truth for image/video model metadata. setMediaModelEnabled(id, enabled) persists availability; withLiveMediaModelsRestore(transfer) fences registry mutations and reloads the cache across a live snapshot restore (#9924); getters omit disabled entries unless includeDisabled is set. Entry fields are documented in the module docblock — note repoFiles[], which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA).
modelInventory.js Identity AND durable shape of a downloaded-model inventory row. modelInventoryId(backend, key) mints the hf: / lora: / ollama: / lmstudio: id and parseModelInventoryId splits it back on the FIRST colon (an Ollama tag like qwen3:8b carries one of its own). hfInventoryRow / loraInventoryRow / localModelInventoryRow build the row a backend contributes, and presentInventoryRow re-derives the live fields (residency, inventory-verified) that a STORED row can never answer. Shared by the scan that mints rows from disk (services/systemResources.js) and the manifest that records them at the install chokepoints (services/modelManifest.js) — a drifted copy of a row's risk, manage path or delete action is a delete button pointed at the wrong place. Pure and dependency-free, so the install services reach the builders without pulling the scan's module graph.
videoFailure.js normalizeVideoFailure classifies and scrubs local video causes; createVideoDiagnosticTail retains bounded stdout/stderr diagnostics without grouping bare exit codes.
maintenanceSequence.js The maintenance ladder shared by both runners: MAINTENANCE_TASK_ORDER / MAINTENANCE_ORDER_GUIDANCE, the interleaved MAINTENANCE_SEQUENCE_TYPES (a perpetual claim-issue drain between every pair of audits), maintenanceStepParams (audits file issues, documentation does the work), and buildMaintenanceSteps (fix mode runs audits directly with one final drain; issue filing can omit claim jobs) which emits quota-burn-shaped run-once steps so quotaBurnInvoke.js can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure.
meatspaceRowIdentity.js Cross-machine identity for MeatSpace health rows (#12432): rowIdentityKeys lists the keys a row answers to (its id and aliasIds, plus a legacy-<sha256> content key when it has no createdAt), mergeRowCopies collapses every group of rows sharing a key (transitively) to one row by per-row updatedAt LWW under its smallest minted id for the row-union snapshot merge, rowAnswersTo / retainContentKey keep edits and deletes addressed by retired keys working, normalizeLegacyRows stamps and dedupes legacy eye exams (also migration 429), and ROW_TOMBSTONES_KEY names the per-file deletion markers. Pure.
meetingUrl.js Selects the one cacheable join URL (selectMeetingUrl) out of a raw Google Calendar event — first http(s) video entry point, else hangoutLink — and owns the shared MEETING_URL_MAX bound. Three-state: undefined = the producer never described conferencing, null = described with none usable.
minimaxH3Memory.js The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. MINIMAX_H3_MEMORY_PROFILES maps entry id → { shippedRepo, shippedRevision, profiles }, each profile carrying an honest minMemoryGb host floor and (CUDA only) a minVramGb device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are resolve_offload_profile()'s own thresholds in scripts/generate_minimax_h3_cuda.py, the host floors are the entries' memoryGb — the sole new number being MINIMAX_H3_HOST_RESERVE_GB, a policy reserve held back for the OS. applyMiniMaxH3MemoryProfiles(list) is the load-time backfill (twin of migration 317) and guards BOTH repo and revision, like the speed-profile decorator. selectMiniMaxH3MemoryProfile({ model, totalMemoryGb }) picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); miniMaxH3MemoryDeclineReason() RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns null on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. validateMiniMaxH3MemoryProfileTable / sanitizeMiniMaxH3MemoryProfiles warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load.
videoContinuity.js How chunk N+1 of a chained video render is conditioned on chunk N. resolveContextFrames(requested) normalizes the tail-window size (absent → DEFAULT_CONTEXT_FRAMES = 22 ≈ 1s @ 24fps; an explicit 0 is preserved as "last frame only", NOT collapsed into the default) and clamps to MIN_CONTEXT_FRAMES..MAX_CONTEXT_FRAMES. resolveContinuityStrategy({model, contextFrames}) picks 'window' (LTX-2 extend_from_video conditioned on the prior chunk's last N frames — motion, not just a pose) or 'frame' (extract the last frame, run i2v), degrading to 'frame' on any runtime outside CONTEXT_WINDOW_RUNTIMES rather than rejecting. extendLatentFrames / extendedPixelFrames convert across the VAE's LATENT_FRAME_STRIDE (8 pixel frames per latent), contextPrefixFrames({totalFrames, extendLatents}) measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), tailWindowStartFrame gives the cut index for the window itself, and planExtendSplice({sourceFrames, outputFrames, extendLatents}) decides where a plain native Extend joins the ORIGINAL source to the render's new frames (null = layout doesn't verify, keep the model output). Pure — importable from prepareParams.js without dragging in local.js. Mirrored for the picker in client/src/lib/videoGenParams.js, pinned by videoContinuity.parity.test.js.
videoPromptLinter.js Deterministic lint pass for continuous-video clip prompts (part of #6217, independent of scriptVideoCompiler.js #6225 by interface — lints already-built prompt strings plus caller-supplied framing/reference metadata rather than a compiler-shaped clip). lintClipPrompt(clip, {bible, maxLength}) checks a single clip: a cutType: 'continue' clip must open with "Hard cut to <framing>:" and use a framing distinct from previousFraming; every references entry (`{kind: 'cast'
videoDisclosure.js Video Gen provenance/licensing + backend policy-scope facts (#3674). VIDEO_MODEL_DISCLOSURES maps each shipped video model id to { shippedRepo, disclosure } (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. applyVideoDisclosures(list) is the load-time backfill (twin of migration 237) with the same preservation guards: an existing disclosure key wins, a custom id is skipped, and a repo pointed at a fork keeps Unknown. VIDEO_BACKEND_DISCLOSURES / videoBackendDisclosure(id) state where inference runs (execution: local or hosted) and whose policy applies — execution facts only, never a restrictiveness ranking. APACHE_2 / GEMMA_TERMS are the shared license descriptors videoTextEncoders.js reuses, so a license-text correction reaches both tables from one edit.
videoDraftDecoders.js Preview-fidelity ("draft") video decode (#5423). VIDEO_DRAFT_DECODERS declares each entry id → a separately downloaded decoder asset, pin-guarded on repo AND revision; applyVideoDraftDecoders(list) is the load-time backfill and validateDraftDecoderTable / sanitizeDraftDecoders warn + strip a hand-edited row (missing pin, a multi-shard or path-traversing file list, a runtime whose builder emits no draft flags) so a full decode can never report itself as a draft one. DRAFT_DECODE_FULL ('full') is a deliberate NO-OP — isFullDecode(id) makes absence and that sentinel the same request, so a full-decode render builds byte-identical spawn args. draftDecodeDeclineReason({ model, decodeId, models, runtimeRevision, assetCached }) RETURNS (never throws) the reason a draft decode does not apply — the model is a delivery target in the finish graph (isDeliveryVideoModel), it declares no decoder, the installed runner checkout is not the revision the asset was verified against, or the weights are not downloaded — because a knob that only makes a render cheaper must degrade rather than 400 a submitted job; resolveVideoDraftDecoder() returns the concrete asset or null. publicVideoDraftDecodeOptions(model) is the picker payload (empty for a model with no decoder, so the client renders no control) and downloadableVideoDraftDecoders(list) the download targets. The table ships NO entry, and as of 2026-08-30 that is a decision rather than a gap (ADR): the shim substitutes one file into upstream’s checkpoint root under a STRICT key match, so a candidate must be a complete unquantized full-VideoVAE checkpoint — which every genuinely light decoder (TAE, quantized repack, decoder-only head) is not.
videoFinishProfiles.js Draft → delivery ("Finish") relationships between video models (#3696). VIDEO_FINISH_PROFILES declares each fast draft entry id → { shippedRepo, finishModelId }, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. applyVideoFinishProfiles(list) is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked repo skipped); validateFinishProfileGraph(list) returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and sanitizeFinishProfiles(list) warns + strips them at load so a typo can never surface a Finish button targeting nothing. finishTargetForModel(model, availableModels) resolves the delivery entry scoped to what this install can run.
videoSpeedProfiles.js Named, pre-validated sampler schedules a user can pick instead of hand-tuning steps/CFG (#4875). VIDEO_SPEED_PROFILES declares each entry id → { shippedRepo, shippedRevision, profiles }; applyVideoSpeedProfiles(list) is the load-time backfill (twin of migration 295) and guards BOTH repo and revision — unlike the finish-profile decorator, because a sampler schedule is revision-sensitive in a way a draft→delivery edge is not. SPEED_PROFILE_DEFAULT_ID ('quality') is a deliberate NO-OP so a default render builds byte-identical spawn args and stamps no extra history fields; isDefaultSpeedProfile(id) makes absence and that sentinel the same request. speedProfileDeclineReason({ model, profileId, mode }) RETURNS (never throws) the reason a profile does not apply — wrong mode, unpinned weights, samplerLocked model, unknown id — so a knob that only makes a render faster degrades instead of 400ing a submitted job, and resolveVideoSpeedProfile() returns the concrete override or null. resolveVideoSpeedProfileForModes({ model, profileId, modes }) lifts that decline check to a CHAINED render — a chain is one clip whose chunks run in different modes (chunk 0 the request's, chunks 1+ extend on a window-continuity chain or image on a frame hop), so the profile applies to every chunk or to none rather than seaming a fast chunk onto quality ones. resolveVideoSampler({ model, steps, guidanceScale, speedProfile }) is the SINGLE precedence rule (samplerLocked > profile > explicit request > registry default), shared by the render path and the chained-render ETA so the two cannot drift. validateSpeedProfileTable(list) / sanitizeSpeedProfiles(list) warn + strip a hand-edited profile (NaN steps, duplicate/reserved id, samplerLocked collision) at load rather than letting it spawn a broken render. What the RUNNER could actually apply — is the pinned pipeline new enough for enable_teacache, is the distilled adapter in the pack — is probed by scripts/generate_ltx2.py and reported back on a SPEEDPROFILE: line.
videoModeProfiles.js The shipped supportedModes fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ runtime comparisons. VIDEO_RUNTIME_MODES maps each runtime to the semantic modes its helper can actually render, including minimax_h3_ref2va as a2v-only; VIDEO_BASE_MODES remains the non-audio fallback for an unknown runtime. resolveVideoSupportedModes(entry) and applyVideoSupportedModes(list) provide the read-time decoration used by mediaModels.js#getVideoModels.
videoDurationProfiles.js Pure pinned duration/frame contracts shared by model-registry upgrades and migrations. LTX-2.5 A2V follows the full uploaded audio, rounds up to its 8n+1 temporal grid, and tops out at 1017 frames under the API's single-pass boundary.
videoReferenceModes.js The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. I2V_REFERENCE_MODES (anchor | inspire) + I2V_REFERENCE_MODE_OPTIONS (the label + the promise sentence the UI prints), I2V_REFERENCE_MODE_RUNTIMES (only ltx25 can honor inspire — it needs per-image conditioning strength), INSPIRE_DEFAULT_IMAGE_STRENGTH, plus normalizeI2vReferenceMode / isDefaultI2vReferenceMode / isKnownI2vReferenceMode / runtimeSupportsI2vReferenceMode / i2vReferenceModeLabel / resolveI2vReferenceStrength and the one rule i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage }) → { code, message } or null. Pure (no ServerError) because it is MIRRORED to client/src/lib/videoReferenceModes.js; videoGen/modeContract.js#videoReferenceModeError wraps it for the route + render boundaries.
videoTiling.js VIDEO_TILING_MODES — the one list of video tiling modes. The video-gen routes build their z.enum from it and the client renders its options from it (labels in client/src/lib/videoTilingOptions.js). Leaf, no imports.
videoStreamingMode.js Block-streaming request vocabulary for LTX-2/2.5 MLX local video renders (#6499) — VIDEO_STREAMING_MODES (auto | resident | stream), DEFAULT_VIDEO_STREAMING_MODE ('auto'), VIDEO_STREAMING_MODE_OPTIONS (label + description for the picker), isDefaultVideoStreamingMode / isKnownVideoStreamingMode / videoStreamingModeLabel / videoStreamingModeFromRecord. This module carries only the REQUEST-side enum — scripts/generate_ltx2.py#resolve_streaming_policy() inspects the pinned pipeline's actual constructor and this machine's physical RAM to decide whether auto streams, and an explicit stream request the pinned pipeline cannot honor (Extend) is a refusal there, not a downgrade here. Pure, mirrored to client/src/lib/videoStreamingMode.js.
videoTextEncoders.js Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the unnormalized hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and lm_head are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. TEXT_ENCODERS_BY_RUNTIME declares the shipped options per runtime (pinned repo/revision plus an explicit files LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale data/media-models.json can't name a file the runner can't map); videoTextEncoderOptions(model) returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to [] — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; TextEncoderPicker owns the hide-when-there-is-no-real-choice check), isStockTextEncoder(id) makes absence and the stock sentinel the same request, resolveVideoTextEncoder(model, id) returns null for the stock choice or throws VIDEO_TEXT_ENCODER_UNSUPPORTED (with the non-throwing supportsVideoTextEncoder + videoTextEncoderUnsupportedError split out so the request path can reject before staging uploads), and downloadableVideoTextEncoders() (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / downloadableVideoTextEncoder(id) feed the /api/video-gen/text-encoders/:id/(download|repair) lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: keyPrefixMap (model. → model.language_model., visual. → model.visual.) is applied to every checkpoint key by scripts/generate_minimax_h3.py BEFORE the pinned loader sees it — no fork of the pinned runtime — and finalNormKey names where the runner synthesizes a ones-filled norm.weight for a checkpoint published without one (correct upstream, since H3 reads the state before the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. publicTextEncoderOption(entry) is the client projection and deliberately drops both, so the UI can't reimplement the remap. The ltx25 table (#4320) uses a third mechanic, configOverrides, because an LTX-2.5 pack's OWN Gemma 4 tower wins over --gemma inside the pinned fork: the substitution is a standalone shim directory whose generated config.json is the substitute's own with these keys merged over it (only ever the model_type label a unified checkpoint gets wrong — never text_config/quantization), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / k_eq_v. verified gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are verified: false today. declaredVideoTextEncoders() is the UNFILTERED table for shape/invariant checks only — never the render or download path, and videoTextEncoderRuntimes() enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written.
pi.js Pi command identity, headless/TUI arguments, and positional prompt delivery.
providerModels.js Provider model resolution sentinels + helpers (CODEX_CONFIGURED_DEFAULT / ANTIGRAVITY_CONFIGURED_DEFAULT / GROK_CONFIGURED_DEFAULT / KIMI_CONFIGURED_DEFAULT, resolveCliModel, filterSelectableModels, Bedrock/OpenCode model mappers, localRuntimeNamespace(provider) — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that cliChildEnv.js, localProviderRuntime.js and providerVendors.js all key on, CODEX_OSS_LOCAL_PROVIDERS / CODEX_OSS_MIN_VERSION / codexOssLocalProvider / codexUnsupportedLocalRuntime — the codex half of that same axis: which local runtimes Codex's --local-provider can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so providerPrerequisites.js classifies a codex record without importing codex.js (the argv emitter, buildCodexOssArgs, stays there), OPENCODE_PUBLIC_REVIEW_AGENT — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because providerVendors.js must not import opencodeConfig.js, parseOpencodeConfigContent — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus opencodeConfigIsLocalOnly / opencodeProviderIsLocalOnly, the ONE locality rule providerVendors.js (gate eligibility) and cliChildEnv.js (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, normalizeClaudeModelId / resolveClaudeCliModel — the Claude-argv chokepoint that rewrites a dotted first-party version (claude-fable-5.1) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. stripBrokenModelFlags and stripProviderPinArgs (explicit per-run selections override baked CLI pins), isCodexProvider, isKimiProvider, isAntigravityProvider, isCursorProvider) plus the agy catalog family, which reads an agy models list as base ids paired with effort tiers (splitAntigravityModel, antigravityBaseModels, antigravityModelEffortLevels, antigravityCatalogListsModel — is a stored pin still served? — and pickAntigravityRelayModel — the cheapest tier to relay one tool call on when a vendor retires the pin PortOS shipped) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (CLAUDE_EFFORT_LEVELS / CODEX_EFFORT_LEVELS / ANTIGRAVITY_EFFORT_LEVELS / CURSOR_EFFORT_LEVELS / EFFORT_LEVELS, effortLevelsForProvider, resolveCliEffort — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — clampEffortToLadder (that clamp over an explicit ladder; the client's own resolveCliEffort runs its published-field ladder through it), hasEffortFlag, buildEffortArgs — the one emitter of --effort <level> / -c model_reasoning_effort=<level>, and deliberately silent for cursor — and foldCursorEffortIntoModel, which carries a cursor level inside --model as Cursor’s own variant syntax (gpt-5[effort=max]) because cursor-agent has no --effort flag) plus codex startup-arg helpers (CODEX_EFFORT_KEY, CODEX_UPDATE_CHECK_KEY, hasCodexUpdateCheckConfig, buildCodexStartupArgs — the one emitter of -c check_for_update_on_startup=false, spread by every codex spawn builder to disable the blocking startup update modal) plus PORTOS_CLI_CONFIG_KEYS / isPortosSuppliedConfigKey — the exhaustive list of -c <key>=<value> config keys PortOS injects, read by the cli-config-invalid error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; isOpencodeLocalProvider (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and isCodexSubscriptionProvider (the ChatGPT-subscription readiness key, housed here so the browser re-export skips codexAccount.js's protocol tables)
providerVendors.js PROVIDER_VENDORS — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy gemini-cli row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): applyCommandDefaults/prepareCliPrompt (re-exported from tuiHandshake.js/cliProviderArgs.js), buildVendorCliArgs/buildVendorSpawnConfig (consumed by cliProviderArgs.js#buildCliArgs / agentCliSpawning.js#buildCliSpawnConfig), inferTuiCommand (re-exported from tuiHandshake.js), and injectTuiModelAndEffort — the shared antigravity-validates-the-pair-vs-everyone-else --model/--effort injection used by both tuiHandshake.js#buildTuiInvocation and agentTuiSpawning.js#buildTuiSpawnConfig, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in antigravity.js/grok.js/kimi.js/cursor.js/codex.js. Also toolFreeOneShotArgs / isToolFreeOneShotProvider / toolFreeOneShotRefusal (#9008): the one-shot-over-caller-text posture Ask and AI app detection run — every approval-bypass flag stripped, the vendor tool-disable switch applied where one exists (claude, grok, pi), and host control required for every other CLI. restrictedRepairArgs (#12487) is the autofixer repair posture: claude with Bash/web tools denied and edits auto-accepted only in the cwd, or codex in its network-denied workspace-write sandbox without user config, plugins or apps, built from fixed arguments so saved options cannot restore host tools; null for any other CLI. Dependency-light on purpose, mirroring those files.
publicReviewSpawnGate.js The ordered spawn-time preconditions a public-content review stage must clear before runAgentSpawn starts an agent for it — checkPublicReviewSpawnPreconditions returns the FIRST failing gate as { reason, category, emit } (or null), running them in the order that is the contract: publicReviewScanBlock (the model-abuse scan cleared at least one PR), publicReviewEligibilityBlock (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), publicReviewProviderBlock from providerVendors.js (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task null posture, the re-derivation #5866 got wrong), then the model itself. emit tells the caller how to announce it: warn-log for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, agent:error for a provider/model misconfiguration that should. validateModel is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub.
modelCapabilityTests.js Catalog + scoring for the CAPABILITY tests on /models/performance (run by services/modelCapabilityTests.js): CAPABILITY_TESTS (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), applicabilityFor + applicableTests (applicable / not-applicable / unknown — an UNCLAIMED capability is never a failure, and null capabilities mean the runtime reported none, which is distinct from []), scoreKeywords + VISION_FIXTURE_KEYWORDS (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), scoreStoryBeats + HEROS_JOURNEY_BEATS (coverage AND ordering, judged only over the beats present), scoreSandboxRepair (verdict from observed disk facts — editing the test instead of the module fails outright), formatAgentEvent (one agent stream frame → a transcript line), rollUpVerdict, and the verbatim CAPABILITY_TEST_PROMPTS / SANDBOX_TASK_PROMPT the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call.
modelPinMembership.js THE model-pin membership rule, and the local-daemon classification it rests on — modelPinIsOffered(provider, model) (may this provider be handed this model? a configured-default sentinel, an empty catalog and a local daemon's cached snapshot are all pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"; beyond those the match is exact, with two same-model-spelled-differently tolerances: agy compares on BASE ids, since --effort carries the tier and the spawner splits a suffixed pin into exactly that, and OpenCode's namespace/model form matches a bare pin, since pins are stored bare and namespaced at spawn), plus localRuntimeKind(provider) (the *Backed markers first, then the endpoint/name classifier; orcarouter excluded as a remote API) and localBackendForProvider. Split out of localProviderRuntime.js — which re-exports all three, so existing importers are untouched — because the browser needs this rule for a picker and must not pull that module's endpoint graph (opencodeConfig.js → zod, not a client dependency) to get it. Carries LOCAL_RUNTIME_MANAGE_URLS for the same reason (#7414): the route that manages each local runtime — Models → Runtimes for the servers, Models → LLMs for the weights catalog, null for the operator-owned compose projects — read by LOCAL_RUNTIMES[*].manageUrl and by the client surfaces that must name the same page. Consumed by cliProviderRun.js, routes/brainSettings.js, services/agentProviderResolution.js, modelPinReconcile.js and client/src/utils/providerModels.js — one answer for all five (#7327).
modelPinReconcile.js Retired-model-pin AUDIT over the shared membership rule (#7315) — providerCatalogListsModel(provider, modelId) (is a stored pin still served? modelPinIsOffered from modelPinMembership.js verbatim, plus the one case a retirement check answers differently from a spawn-time one: nothing is pinned at all. The agy base-id and OpenCode namespace tolerances used to be layered HERE above a stricter rule, which made the audit and the three spawn-time callers disagree about the same pin; they moved down into the rule in #7327), catalogOfferings (the listed ids with sentinels dropped, agy collapsed to base ids for a picker), reconcileModelPins(pins, providers) — which pin descriptors name a model their provider no longer lists — and, since #7339, the two helpers that make a pin's provider field singular-or-plural-agnostic: pinProviderIds(pin) (THE coercion from providerId / providerIds to a trimmed id list, called by the audit's descriptor builder too so the two layers cannot drift) and pinProviderNames(pin, providers) (how a surface names those records — shared by the warnings panel and the notification card so they cannot describe one pin differently). A reviewer pin names a BINARY several records front, so it is stale only when EVERY named record stops listing the model. Every UNKNOWN case (no pin, empty catalog, unresolved provider) answers "still listed": a false "your pin is gone" tells the user to change a setting that works. Derived on read, never persisted — see services/modelPinAudit.js.
reviewerProviderMatchers.js Which PROVIDER RECORDS front each model-taking reviewer's binary — REVIEWER_PROVIDER_MATCHERS (slug → record predicates, in preference order), providersForReviewer(reviewer, providers) (every match, de-duped, preference-ordered so [0] is the record whose default a picker shows) and reviewerProviderIds. A reviewer slug names a BINARY and PortOS ships more than one record per binary (claude spans claude-code + claude-code-tui, grok spans grok-cli + its TUI), so both the picker's option list and the retired-pin audit union every match: sourcing from one record makes the answer hostage to that record's staleness, and judging a pin against one produces a false retirement for a model the other still lists. Deliberately excludes Bedrock/Vertex and the opencode-<backend> presets (ids that resolve only under another record's environment). Imported directly by client/src/hooks/useReviewerModelOptions.js — one table, no mirror to drift (#7339).
modelPricing.js Per-model API billing rates for informational cost estimates — resolveModelRates(providerId, model) (exact → family regex → provider default → blended fallback, with a matched tier; also derives cache tiers), pricingAsOfForModel(model), isFreeProvider, estimateCostUsd(tokensIn, tokensOut, rates, cache?) (uncached input plus separately priced cache tokens), estimateGrokImagineCost(model, units) (published Imagine image / second / input-image rates; longest model id wins), estimateAgyImageCost(model, units) (published Imagen rates for Antigravity-driven generation), GROK_LONG_CONTEXT_PROMPT_TOKENS (200k — the usage report adds one extra base-rate charge for that per-request subset), and baseline PRICING_AS_OF. Subscription allowance and local inference bills remain unknown; batch discounts and non-Grok long-context tiers are not modeled.
chatCompletionUsage.js normalizeChatCompletionUsage(usage, { model, endpoint }) splits an OpenAI-compatible chat-completions usage body. Cached tokens are removed from fresh input. xAI (api.x.ai, us.api.x.ai, or a grok* model when the endpoint has no host) adds reasoning_tokens to output; every other host keeps output as completion_tokens only, even for a grok-named model. A prompt at GROK_LONG_CONTEXT_PROMPT_TOKENS sets longContext for xAI only.
usageRange.js resolveUsageRange({ period, from, to }) — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; all unbounded; default 7d).
subscriptionPlanTiers.js Which TIER of a subscription plan the user is on ("Max 20x", "Pro"), as a short free-text label per provider family — MAX_PLAN_TIER_LENGTH (the cap the Zod schema enforces), normalizePlanTier / normalizePlanTiers (trim, cap, and collapse empty/non-string to null = not recorded). Deliberately free text: tiers are vendor marketing names that change off the PortOS release cycle. Pure; persistence lives in services/subscriptions.js.
subscriptionSavings.js Subscription-vs-API savings math for the usage page — resolveSavingsWindow (clamps an open-ended report range to today / first activity day), prorateMonthlyCost (monthly plan price → this window's share, DAYS_PER_MONTH, capped by MAX_MONTHLY_COST), savingsPercent / costMultiplier (null, never 0, when the comparison is undefined), attributeReportCostToFamilies (groups report rows by their stamped family), roundCents (the one money rounder), and buildSubscriptionSavings({ entries, range, unmatchedApiCost }) → per-family rows + totals. Pure.
credentialRegistry.js Pure catalog of PortOS credentials (CREDENTIALS, CREDENTIAL_IDS, CREDENTIAL_TIERS) — one entry per key/token an install can use (id, label, unlocks, tier, getUrl, envVars, settingsPath, configurePath, optional feature). Sits beside instanceFeatureRegistry.js so the two lists stay greppable together. Runtime resolution (settings / repo .env / inherited process.env / CLI / instance config) lives in services/credentialInventory.js. The Settings > Credentials page never receives a value or masked prefix.
instanceFeatureRegistry.js The registry of optional per-install features (INSTANCE_FEATURES, INSTANCE_FEATURE_IDS, APP_FEATURE_IDS) — pure data, so validation.js derives its feature schemas from it and navManifest.js can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → defaultEnabled) lives in services/instanceFeatures.js. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off.
providerFamilies.js Subscription-quota FAMILY identity — PROVIDER_FAMILIES ({ id, label, idPattern, matches } for claude/codex/agy/grok), PROVIDER_FAMILY_IDS, familyLabel, familyForProvider(config), familyForProviderId(id) (the weaker id-only classifier a Zod schema can use, null when the id names no family) → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry services/providerUsage.js attaches quota fetchers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from providerVendors.js, which is argv-shaped and includes vendors with no subscription quota.
fleetHostUsage.js The INBOUND side of the dedicated inference host — who is spending this machine's GPU. createFleetHostUsageLedger({ now, maxClients, maxRecent, retentionDays }) → beginRequest / endRequest / snapshot / toJSON / hydrate: a bounded per-client ledger keyed by the socket's remote address (the gateway authenticates every peer with ONE shared host key, so the wire carries no per-peer identity), holding request/error counts, observed token totals, 30 days of daily buckets and the last 50 completed requests. findReportedUsage(text) lifts the LAST usage object out of an OpenAI-compatible body, searched backwards because a stream_options.include_usage stream emits "usage": null on every frame before the populated one; createUsageSniffer() is the bounded 64 KB tail buffer the gateway taps a response stream with. Tokens are recorded only where the upstream reported them — tokenReports counts how many requests carried a reading, so the report can say "12 of 40" rather than implying the rest were free. No prompt or completion text is ever held. Peer NAMES are resolved at report time by services/fleetLlmUsage.js; contrast fleetQuotas.js, which merges this install's OUTBOUND subscription quotas.
fleetQuotas.js Unifies subscription-quota readings across federated instances — one plan, several machines, each able to read only its own local CLI. sanitizeQuotaCards bounds a peer-supplied payload to the wire shape; mergeFleetQuotaCards(localCards, peerEntries) folds every peer's reading into this install's cards, taking the FRESHEST reading per limit key (the meters are account-wide, so summing them would multiply one allowance) and SUMMING activity counts (those are per-machine, which is why the provider captions them "does not include other devices"); fleetNote writes the caption naming what was combined. metrics[] is left local — its values are prose, not addends. Fed by services/providerQuotaShare.js (this machine's readings, persisted) and services/peerUsage.js (the usage sync category that carries them).
harnessOutput.js Parsers for what a coding-agent HARNESS prints about itself: parseHarnessVersion(stdout) (the one semver run in a --version banner, null when unparseable), compareHarnessVersions(a, b) (the null-guarding wrapper around versionUtils.js#compareSemver — null when either side is unparseable, so a version that did not parse never reads as "out of date"), parseHarnessModels(harnessId, stdout) + HARNESS_MODEL_PARSER_IDS (OpenCode's provider/model lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to antigravity.js#parseAntigravityModelList / aiToolkit/internal/cursor.js#parseCursorModelList, which the provider-card refresh has used for far longer), MAX_MODELS, and parseNpmLatestVersion. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling --model takes — namespaces kept where the vendor keeps them. Consumed by services/providerRuntimeInstaller.js and services/harnesses.js.
providerGateways.js PROVIDER_GATEWAYS — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (orcarouter, openrouter, nvidia-nim), plus PROVIDER_GATEWAY_IDS, gatewayById, isGatewayNamespace(ns), gatewayForProvider(config) → row or null, isGatewayBackedProvider(config), and attachGatewaySiblingKey(provider, providers) — the synchronous twin of the toolkit's withGatewayApiKey for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's id is simultaneously the OpenCode provider namespace, the gatewayBacked marker value, and the id of the sibling api record that owns the key — so the sibling lookup is providers[gateway.id] and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the orcarouterBacked boolean + literal 'orcarouter' that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in cliChildEnv.js/localProviderRuntime.js). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (ollamaBacked, vllmBacked, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in aiToolkit/internal/gateways.js (the vendored toolkit may not import out) — providerGateways.parity.test.js fails when the two drift; client/src/utils/providerGateways.js re-exports this leaf rather than copying it. DERIVED (#7562) from the serviceDefinitions.js rows carrying a gateway column, so a gateway is one row in that table; the projected shape is unchanged. Dependency-light: imports only that leaf.
serviceDefinitions.js SERVICE_DEFINITIONS (#7562) — every backend a harness can be pointed at, as ONE table: subscription services (claude-subscription, codex-subscription, antigravity, grok-build, cursor), API-key services (anthropic, openai, google, xai, bedrock, kimi, the three hosted gateways orcarouter/openrouter/nvidia-nim, opencode-zen, cerebras, a generic openai-compatible endpoint), one local row per LOCAL_RUNTIMES id, and fleet-host. Each row: family, transports (anthropic / openai with a default base URL, or none for a local daemon whose port is an install fact), credential (env var names, key URL), the plans it may be declared under (SERVICE_PLANS), a catalog strategy with an optional per-plan filter (OpenRouter :free, OpenCode Zen *-free), and where relevant localRuntime, harnessOnly, gateway (the rows PROVIDER_GATEWAYS derives from) and piProvider (Pi's built-in name). resolveServiceInstance(input) is the pure instance shape the epic composes over (definition + slug + plan + resolved transports + raw credentials), serviceDefinitionById / serviceDefinitionForLocalRuntime look rows up, serviceError(code, message) mints the typed errors. Imports nothing, so providerGateways.js and the browser can reach it.
providerServiceInstances.js A connection read as a SERVICE INSTANCE (#7563, epic #7561) — the pure bridge between ai_connections rows and serviceDefinitions.js. definitionIdForKind / kindForDefinition translate a row's kind (ollama, gateway:<id>, api, vendor + its binding's harness) to a definition id and back; allocateServiceSlug mints base, base-2, …; serviceColumnsForConnection / planServiceColumnBackfill are the boot-time backfill (slug, definition, first plan) the reconcile pass applies to rows that predate the columns — row-derived, idempotent, never a seed; takenServiceSlugs is the set every allocation avoids; storedTransports is the transports map a new instance's row stores; applyServicePlanFilter narrows a listing to a plan; credentialSourceFor reports where an instance's credential comes from (settings, env-file, env, cli, config, none, the inventory's own precedence) without a value; instanceApiKeyFor(connection, definition, env) is the key it RUNS under (stored → the row, env → the definition's conventional variable, else none), shared by the catalog refresh and the composite resolver (#7564); toServiceDto (serviceDtoSchema, the connection DTO extended, strict) is the sanitized GET /api/providers/services row with a one-word readiness.
providerServiceMerge.js Folds duplicate SERVICE INSTANCES into one (epic #7561) — the graph import gave each harness its own connection, so opencode-nvidia-nim and nvidia-nim became two NVIDIA NIM services. planServiceInstanceMerges(graph, providers) groups rows by definition (a generic openai-compatible row on a named definition's default endpoint counts as that definition), folds those sharing an endpoint, credential mode, plan and non-conflicting credentials whose legacy routes stay contained, and picks the survivor and its label; presetPatchesForMerge re-derives the derived presets onto the survivor, keeping each preset's model list. Pure; the reconcile pass (providerGraph.js) applies it.
providerHarnesses.js Provider HARNESS identity for the connection graph (#6366) — PROVIDER_HARNESSES (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, plus direct — PortOS's own HTTP client, the harness of an api record (#7562) — each with its supported modes, wire protocol, the existing is*Provider predicate as its matcher, and its capability bindings: every way the program can be pointed at a service definition — subscription, protocol+baseUrl+credential, static-env service (Bedrock), codexOss, piProvider), PROVIDER_HARNESS_IDS, harnessById, harnessForProvider (direct for an api record, null only for an UNKNOWN harness), normalizeHarnessId / graphHarnessId (the one direct ↔ NULL translation for the graph's nullable column), compatibleBindings(harness, serviceInstance) / firstCompatibleBinding / isCompatible (which bindings reach a resolved service instance), CREATABLE_HARNESS_IDS (mintable from a bare connection) and harnessConnectionBlocker (the row's connectionBlocker: why not — no recipe at all, or a subscription/Pi row that composes onto named services only), harnessSupportsMode, ROUTE_MODES, plus the model-name adapters toExecutableModelName / toCanonicalModelName (the verified inverse of prefixOpencodeModel: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from providerVendors.js (argv-shaped), providerFamilies.js (subscription quota) and serviceDefinitions.js (the backends). Pure leaf — client/src/utils/providerHarnesses.js names a binding's harness through harnessById; the direct ↔ NULL translation is mirrored in aiToolkit/internal/harnesses.js behind providerHarnesses.parity.test.js.
providerContextWindows.js The context-window ladder for provider/model planning, split out of services/stageRunner.js so the browser shares it: the vendor constants (DEFAULT_LARGE_CONTEXT_WINDOW / CODEX_CONTEXT_WINDOW / GEMINI_CONTEXT_WINDOW / GROK_CONTEXT_WINDOW / KIMI_CONTEXT_WINDOW), knownModelContextWindow(model) (the known-model regex table), knownProviderContextWindow(provider) (the vendor window for a configured-default CLI/TUI provider) catalogModelContextWindow(provider, model) (the window the provider's own /models catalog reported, which outranks the table) and mergeObservedContextWindows(provider, observed) (folds a local daemon's LIVE /v1/models windows onto that catalog rung, so they outrank a stale refresh while an explicit contextWindow still wins; never persisted) and aliasServedContextWindows(provider, runtime, served) (re-keys a daemon's served windows by every spelling the provider could dispatch under, for a caller that already holds the listing). The Ollama num_ctx ceiling is deliberately NOT here — see aiToolkit/. stageRunner.js builds effectiveContextWindow on them; client/src/utils/providerContextWindows.js re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure.
providerConnections.js Provider CONNECTION identity for the connection graph (#6366) — providerConnectionProfile(provider) reads one record as the backend it describes (kind, protocol, transports, RAW server-only credentials, the owned field/env split, and reasons from CONNECTION_ISOLATION_REASONS when the config is dynamic, external, unparsable or endpoint-less). sameConnectionIdentity compares real credential values and refuses once any is the REDACTED_CREDENTIAL sentinel, so a sanitized record can never merge two connections; compareBackendEndpoints is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible /v1 conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). projectConnectionOwnedFields(provider, connection) projects a stored backend through the reader's protocol and env-ownership rules for the graph service; withoutConnectionOwnedFields / withConnectionOwnedFields are the lossless split/materialize pair that keeps a downgraded install runnable from data/providers.json alone. Pure: no I/O.
providerGraphPreview.js READ-ONLY import preview for the provider connection graph (#6366) — buildProviderGraphPreview({providers, activeProvider}) projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from providerModeGroups and surfacing a cross-harness daemon match as a suggestedLinks entry requiring an explicit link. toManagementPreviewDto sanitizes and validates the version-1 DTOs (managementPreviewSchema, PROVIDER_GRAPH_SCHEMA_VERSION) that GET /api/providers/management/preview returns; projectPreviewToProviders re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; providerGraphUniquenessViolations checks the UNIQUE constraints #6367 will enforce; routeModeEligibility is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch.
providerGraphRecords.js The DURABLE half of the provider connection graph (#6367) — the pure record layer over ai_connections / ai_harness_bindings / ai_route_bindings. graphFromPreview / importGraphFromProviders mint UUID-keyed rows from a #6366 preview while every executable providerId stays untouched; toManagementGraphDto (managementGraphSchema) sanitizes them for GET /api/providers/management (credential PRESENCE only, no projection snapshots); connectionOwnedSnapshot / applyProjections materialize connection-owned values back into providers.json so a downgraded install still runs; routeBelongsOnConnection answers whether a stored connection still CONTAINS the backend one route describes (the create-time and reconcile-time test, looser than sameConnectionIdentity); and planGraphReconciliation / reconciliationIsNoop are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call.
providerModelAliases.js HAND-AUTHORED canonical→executable model aliases for one provider route (#6369) — the correction surface for a modelMap a refresh could only fill with what it could VERIFY. Observed aliases (ai_route_bindings.model_map) and user overrides (model_alias_overrides) are stored apart and merged on READ by effectiveModelAliases ({ ...observed, ...overrides }), which is what lets a hand-authored alias outlast the next refresh; applyModelAliasPatch is the three-valued edit (absent preserves, a string sets, null is the only thing that removes); staleModelAliases reports — never repairs — an override naming a spelling the record no longer lists, and makes no claim at all about a route listing no models; connectionCatalogModels is the union an alias write re-derives the shared catalog from, so a correction actually reaches the model menus; modelAliasRevision is the stale-edit fingerprint, reusing routeSettingsRevision because ai_route_bindings has no revision column. Pure: no I/O.
providerModePairing.js May an existing record gain the OTHER execution mode of its harness (#7501) — tuiModeAddition(provider, providers, executionModes?) is the ONE verdict behind both the canAddTuiMode flag GET /providers decorates each record with (so the card offers "Add interactive mode") and the refusal POST /providers/:id/modes/tui answers with, so a card can never advertise an action the server rejects. Refuses a non-CLI record (the CLI id is the stem, so minting it from a TUI record would be a rename), a record storing no command, and a KNOWN harness declaring no TUI mode; an UNKNOWN harness passes with empty argv rather than a guess, while a known one starts from its recipe’s proven interactive line. Asks whether the harness already HAS its interactive mode (the record’s providerModeGroups group — the shipped grok-cli/grok-tui pair leaves grok-cli-tui unclaimed, so an id-only check would mint a third record beside it), and separately 409s on a taken <id>-tui rather than suffixing around it. Pure: no I/O.
providerPresets.js PRESETS (#7565, epic #7561) — a stored data/providers.json record read as a (harness, method, service) tuple plus the user's own defaults and overrides. A record carrying harnessId + method + serviceId is a DERIVED preset (isDerivedPreset in providerGraphRecords.js, presetKind): materializeDerivedPreset({record, harness, instance, catalog, bootstrap}) re-derives every connection-owned value (program, endpoint, credential, backend markers, inline bootstrap, models = plan-filtered catalog ∩ catalogNarrowing) through materializeRoute while keeping every per-preset field (name, argv with a binding's suffix preserved, timeouts, pins, effort, fallback, generation params, consent flags, unknown fields) and the record's own OpenCode inline config when it already reaches the service; refusedDerivedEdits(updates, derived, ownedEnvNames) names the connection-owned keys a direct edit would move (DERIVED_PRESET_OWNED_KEYS, plus env vars by name); derivedPresetDrift / derivedPresetPatch compare a record with its derivation; presetDerivable(record) is the editor's "offer the button" test; matchBootstrapApp / bootstrapInputFor map an inline credentialBootstrap to a configured app and back; planPresetBackfill({graph, providers, bootstraps, env}) is the boot-time stamp of every routed legacy record whose re-derivation is a FIXPOINT — additive keys only, every refusal reported with a reason. Pure; the store-backed half is services/providerPresets.js. impliedCatalogNarrowing is the narrowing that keeps a record on its current list once derived, and rederivePreset re-derives one derived preset from an instance (derived record + patch), shared by the backfill, rematerializeDerivedPresets and the service fold.
providerFallbackChainCache.js Import-free process cache of the user's single ordered provider fallback list (peekFallbackChain sync read for routing, setFallbackChainCache, normalizeFallbackChain). Filled by services/providerFallbackChain.js from settings providerFallbackChain; read by the toolkit's getFallbackProvider.
providerRef.js Provider REFERENCE grammar (#7564, epic #7561) — the two spellings a { providerId, model, effort } selection may name a provider by: a PRESET record id (PRESET_ID_RE, the slug createProvider mints) or a COMPOSITE `.<cli
providerRouteRecipes.js Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of providerConnections.js, which reads an existing record. buildRouteRecord({harnessId, mode, providerId, name, connection}) materializes a connection's endpoint, credentials and backend marker into a DISABLED data/providers.json record through PROVIDER_HARNESSES[].recipe; mintRouteIds allocates readable ids keeping the <stem> / <stem>-tui pairing providerModeGroups recognizes; bindingBlocker is the pre-write refusal (no recipe, unsupported mode, a transport the backend does not declare, a credential the program requires); CREATABLE_CONNECTION_KINDS / connectionKindLabel / connectionKindMarkers bound the backends a route can honestly describe (slotstream and vendor deliberately excluded); bindingProtocol names the wire a binding needs. materializeRoute({harness, method, serviceInstance, bootstrap?, selection?, overrides?}) (#7562) generalizes buildRouteRecord from a connection to a SERVICE instance: picks the harness's first compatible binding, writes base URL / credential / static env / backend markers / inline OpenCode config / Pi --provider per that binding plus the recipe's mode argv, stamps harnessId / method / serviceId / servicePlan, and — for a non-api method with a bootstrap app — the credentialBootstrap object composeBootstrapSpawn turns into <bootstrap> run <harness> -- <args>; throws typed errors (HARNESS_SERVICE_INCOMPATIBLE, SERVICE_ENDPOINT_REQUIRED, SERVICE_CREDENTIAL_REQUIRED, SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED) rather than minting a route that cannot run. materializeRouteOutcome(input) is the same body as a VERDICT ({ record } or { error } — the typed 400 without the throw) for the composite resolver (#7564), which reads a refusal as the reason to show beside a saved selection. routeDescribesService(profile, instance) is the round-trip contract: fed back through providerConnectionProfile, a materialized record classifies onto the service it was built for. Pure: no I/O, no spawn, no provider call.
providerRouteSettings.js The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (args, timeout, effort and the defaultModel/lightModel/mediumModel/heavyModel/ultraModel pins), mirroring what the toolkit's sharedModeUpdates already declares mode-specific. ROUTE_SETTING_FIELDS / ROUTE_SETTING_KEYS / routeSettingKeys(mode) name the set (args reaches cli/tui only); routeSettingsFor(provider) reads it off a record with absent and cleared collapsing to null; routeSettingsSchema is the wire shape GET /api/providers/management publishes; unsupportedRouteSettings rejects a key the route's mode does not accept; and routeSettingsRevision is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through /ai/edit/:providerId is caught too. Connection-owned values and execution consent (enabled) are deliberately absent. Pure: no I/O.
providerTranscriptUsage.js Parsers for the session files the coding CLIs write to disk (0 tokens to read) — parseClaudeTranscript (~/.claude/projects/<cwd-slug>/*.jsonl), parseCodexRollout (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl), parseGrokTurns/parseGrokChatHistory/decodeGrokSessionDir (~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/), parseAgyTranscript/parseAgyHistory (~/.gemini/antigravity-cli/), parseKimiWireLog/parseKimiSessionIndex (~/.kimi-code/sessions/.../agents/<id>/wire.jsonl, indexed by ~/.kimi-code/session_index.jsonl), claudeProjectSlug, totalTranscriptTokens. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a message.id, Codex's total_token_usage is cumulative and repeated, grok's turn_completed.usage has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its _meta.totalTokens is context occupancy and never billed. Antigravity parses measured tokens (input_tokens, output_tokens, cache_read_tokens) from planner responses when recorded, or falls back to chars for the caller to estimate from — including contextChars, the prompt each model call replays (priced as cache reads; omitting it made the plan read far cheaper than it was). Grok/Antigravity sessions PortOS never launched are billed by services/usageInteractiveScan.js. Kimi's usage.record lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one wire.jsonl per agent — a subagent's spend is never in its parent's file. Each parser returns per-model buckets (byModel) plus the message keys it counted (countedKeys), and accepts an exclude set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by services/usageReconciler.js.
opencodeCatalogCache.js Primes the on-disk catalog opencode models prints from — primeOpencodeCatalogCache() fetches OpenCode's api.json with Node's fetch and atomically writes $XDG_CACHE_HOME/opencode/models.json (~/.cache when unset). OpenCode refreshes that file from a forked task whose failures it swallows (opencode models --refresh still prints Models cache refreshed) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when OPENCODE_MODELS_PATH / a custom OPENCODE_MODELS_URL / OPENCODE_DISABLE_MODELS_FETCH means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way.
opencodeConfig.js OpenCode config builder — buildOpencodeEnvVars(provider, model) builds dynamic OPENCODE_CONFIG_CONTENT declaring model ids under the namespace the provider's marker selects: a local runtime (ollama / mtplx / llama / vllm / sglang, bare ids) or a hosted gateway from providerGateways.js (vendor/model ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins small_model to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a no-tool public-review profile it also applies hardenOpencodeConfigForNoTool — root permission: deny, an emptied tool map on every agent, tool_call: false on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (providerVendors.js pairs it with run --agent + OPENCODE_PUBLIC_REVIEW_AGENT). The harden step also copies agent.build's generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs.
localProviderRuntime.js Which LOCAL daemon a provider talks to, and where — LOCAL_RUNTIMES (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from opencodeConfig.js rather than re-typed, manage/docs links, model-download hint), localEndpointPort + isLocalInstanceHost, and re-exports of localBackendForProvider / localRuntimeKind / modelPinIsOffered — all three now live in the browser-safe leaf modelPinMembership.js (a picker needs the pin rule and must not pull the endpoint graph below to get it), so existing importers here are untouched — localRuntimeForProvider(provider) → the row with the endpoint the provider ITSELF configures (OPENCODE_CONFIG_CONTENT's baseURL, ANTHROPIC_BASE_URL, or endpoint), then the OLLAMA_URL/OLLAMA_HOST/LM_STUDIO_URL override the backend managers read, then the canonical default — and null when that resolved endpoint fails isLocalInstanceEndpoint (an API provider on another machine has no local daemon to check, whatever its name says) — plus normalizeOpenAiBaseUrl. Pure; the probing half is services/providerReadiness.js. Optional setupStateDetail overrides providerReadiness's per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); standbyWhenStopped marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup.
managedDaemon.js Shared mechanism for the local daemons PortOS runs as optional PM2 processes (services/llamaServerManager.js → portos-llama-server, services/mtplxServerManager.js → portos-mtplx, services/slotstreamServerManager.js → portos-slotstream). Owns their PM2 process names — LLAMA_APP, MTPLX_APP, and SLOTSTREAM_APP; the managers re-export those names. createDaemonWatcher({...}) supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. createDaemonLogBuffer({maxLines?}) is the bounded timestamped ring buffer of what PortOS logged around a launch, plus withPm2Logs(output) → that buffer followed by anything pm2 logs has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). pm2ArgValue(args, flag) reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; null means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared idle reaper, for a daemon that cannot release its weights any other way: registerIdleDaemon({name, getIdleMs, isPinned?, isRunning?, stop}) (seeds lastUsedAt to NOW, so a hand-started daemon gets a full window; isPinned exempts user-pinned servers), markDaemonUsed(name) — call on real traffic, NEVER on a status poll — daemonLastUsedAt(name), daemonReleaseReason(name), idleWindowMs(minutes) (minutes → ms; 0 = never, null = not configured, kept distinct), evaluateMemoryPressurePolicy({...}) (pure policy function evaluating current state, pressure reading, and recent history), reapIdleDaemons(now?, options?) → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and startIdleReaper({intervalMs?}) / stopIdleReaper() (ONE interval for all registrants, unref'd, idempotent). mtplxServerManager and slotstreamServerManager register: llama.cpp releases its checkpoint in place via --sleep-idle-seconds and must NOT be stopped for it. createOnDemandDaemon({appName, label, emoji, readSection, endpointFor, probe, start, stop, getStatusStrict, clearStatusCache?, exitTail?, resolveLaunch, getConfig?, sleep, getRelaunchReadyTimeoutMs, getRelaunchPollMs}) is the shared ON-DEMAND WAKE mechanism (#8105) — ensureRunning() (mark used → already online? → resolve the launch line via the manager's resolveLaunch(current, saved) → probe → start → wait), runStart(fn) (runs an explicit start/stop sequence in the same exclusive start slot as the wake, so a user-clicked Start or tuning relaunch queues behind an in-flight wake instead of deleting it, #12723; fn calls the raw start, never ensureRunning/runStart), registerIdle() (wraps registerIdleDaemon with the idle-minutes/keep-loaded reads, including the legacy pinned fallback and their own set*OverrideForTests seams), waitForReady(endpoint) (the death-detecting readiness poll, with exitTail folded in), servesPort(provider, managedPort) (the numeric port-match arm — Number(localEndpointPort(...)), fixing a === string/number mismatch that made the MTPLX arm permanently dead), and idleMinutes / keepLoaded / savedLaunch for a status card's reads. createPm2ExitTail({appName, execPm2, appendLog, lines?, tailLines?}) is the shared "what did the dead process print" diagnosis both waitForReady and a manager's own startup-window failure can share. Both mechanisms only — what a launch line means and when a daemon may start is exactly what differs between the two.
mtplxModels.js services/localCachedModels.js owns provider-refresh discovery and gates it on runtime readiness without loading the process manager. listMtplxCachedModels({command?}) → {models, error} from mtplx models --json (walks local directories — pulls no weights, loads no model, but see mtplxRuntime.js: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on describeMtplxRuntime().ready first) servableMtplxCachedModels(models) → the rows MTPLX itself calls complete, and pickMtplxCachedModel(models) → the one repo id to hand mtplx serve --model. models: null means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from [] (read, and empty), because services/localRuntimeSetup.js starts MTPLX on its own default in the first case and refuses with the mtplx pull command in the second. Exists because mtplx serve defaults --model to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (validation.ok !== false, so a half-finished pull is not served), preferring one with a recorded mtplx_runtime.json exactness contract. describeMtplxCache(cache) → {state: 'unknown'|'empty'|'partial'|'ready', model, count, error} folds both into the one value services/providerReadiness.js puts on the checklist and describeRuntimeSetup picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work.
mtplxRuntime.js describeMtplxRuntime(binaryPath, {env?}) → {ready, wrapper, venvPath} — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's mtplx is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and brew upgrade re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own VENV= assignment, honours $MTPLX_BREW_VENV the way ${MTPLX_BREW_VENV:-…} does, and tests <venv>/bin/mtplx for executability — the wrapper's own [ ! -x … ] guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports ready: true, wrapper: false, i.e. the status quo — never a block over a parse failure.
slotstreamCatalog.js SLOTSTREAM_CATALOG — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). resolveSlotstreamRepo(idOrRepo) maps a catalog id or an owner/name repo id to a repo (null for anything else), slotstreamModelDirName(repo) flattens it to the single-segment cache directory whose NAME is the id a start hands --model, and selectSlotstreamRepoFiles(siblings) picks the .safetensors/config/tokenizer files a checkpoint is made of while dropping mirrored original/, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path.
slotstreamModels.js isServableCheckpoint(dir) checks configuration, weights and indexed shards; SLOTSTREAM_INCOMPLETE_MARKER keeps interrupted downloads unavailable until retry completes. listSlotstreamCachedModels({cacheDir?}) → {models, error} from a local directory walk of the SSD-streaming MoE cache (no network, no model load), pickSlotstreamCachedModel(models, requested?) → the checkpoint id to hand slotstream serve --model, and planSlotstreamMemory({totalBytes?, overrideGb?}) → {targetGb, expectedPeakGb, expectedWarmDecodeToks, auto} so the LLMs row can show the memory plan instead of hiding it. models: null means the cache could not be READ and is deliberately distinct from [] (read, and empty), because a start never fetches weights.
recordedProjectDir.js Where PortOS remembers a container project it had to go and FIND — one .env line per stack in the INSTALL's root (PATHS.installRoot, so a worktree-booted server writes where the real install reads). readRecordedProjectDir(envVar, envPath?) / recordProjectDir(envVar, dir, envPath?) / projectDirIsSettled(envVar, env?, envPath?) / resolveRecordedProjectDir(envVar, defaultDir, env?, envPath?) are all keyed on the env-var NAME, so the vLLM and SGLang Qwen3.8-27B stacks share one implementation instead of drifting on the precedence rule — exported value (this run's decision) → the record (an earlier run's) → the stack's documented default. Read from the file on every call, never cached: a placement run writes it and the readiness poll in the same process must see it without a restart, and PortOS has no dotenv so .env reaches process.env for nobody. Writes are atomic and replace the key's line rather than appending (upsertEnvLine) — that file also holds the database password. envPath is a parameter so a test's sandbox answers instead of the developer's install. Written by services/wslProjectPlacement.js.
vllmQwenProject.js resolveVllmProjectDir() / inspectVllmQwenProject() → {dir, hasProject, composeFile, hasWeights, weightsRoot} for the syv-ai/qwen38-27b-rtx3090 compose project, plus vllmStartBlockedReason(project) → the prose refusal (or null), and vllmProjectSetupState(project) → ready/empty/unknown for the readiness checklist. hasWeights is tri-state: true found / false caches read and empty / null no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and services/localRuntimeSetup.js refuses to docker compose up on anything but true so the start button can never kick off the 20 GB prepare. Also owns WHERE the project lives, as this stack's keyed view of recordedProjectDir.js: readRecordedVllmProjectDir(envPath?) / recordVllmProjectDir(dir, envPath?) / vllmProjectDirIsSettled(), resolving VLLM_QWEN_PROJECT_DIR (this run's decision) → the record → `/qwen-serving; envPathis a parameter so a test's sandbox answers instead of the developer's install. Directory reads plus that one config line — never docker, never a registry. Other override:VLLM_QWEN_WEIGHTS_DIR`.
wslDistro.js Which WSL2 distro a native-Win32 PortOS should put Linux-side work in. detectWslProjectDir(leaf) → {dir, distro, home} or {dir: null, reason} (no-wsl / no-distro / internal-distro / unreadable-share), built from wsl.exe -e sh -c 'echo "$WSL_DISTRO_NAME"; echo "$HOME"' — the distro's OWN shell, because wsl --list prints UTF-16LE that a UTF-8 reader mangles while an executed program's stdout passes through byte for byte. Verifies the derived \\wsl.localhost\… path is readable from Windows before returning it (WSL running and its share answering are separate facts) and refuses a container engine's own distro (docker-desktop and friends are recreated on a reset). parseWslProbe / parseWslDistroList (NUL-stripping the UTF-16 bytes, for an error message only) are exported for their own tests; WSL_UNC_PREFIX names the share root for callers writing refusal prose. Exists so the vLLM stack places its ~20 GB of weights on the distro filesystem instead of asking a human to fill in a UNC template — every read from a C:\ checkout would cross a 9p share.
qwenAgentParsers.js The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. QWEN_AGENT_PARSERS maps runtime → {toolCallParser, reasoningParser, enableAutoToolChoice} (vLLM qwen3_xml + --enable-auto-tool-choice, SGLang qwen3_coder + --reasoning-parser qwen3, llama both null — a positive "no such flag today", not a placeholder). parserFlagsFor(runtime) returns the argv fragment (always an array, so no caller type-checks) and vllmExtraArgs() its string form for the compose project's .env EXTRA_ARGS; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with tool_calls: null, so the agent never touches a file. Spellings are empirical (docs/research/2026-08-21-qwen38-rtx3090-vllm.md, …-sglang-qwen38-27b.md); never auto-detect one from the chat template — that is how hermes got picked. Pure.
vllmQwenProvision.js The .env half of provisioning that same project: generateVllmApiKey(), isWsl2Engine() (win32 counts — Docker Desktop's engine IS a WSL2 VM), vllmEnvDefaults({apiKey, wsl2}) → the load-bearing tool-parser/pin-memory/alloc-conf settings, parseEnvContents(contents) → a key→value Map (keyed on mention, so a commented-out key reads as absent and KEY= as an intentional empty), and the two writers over one shared newline guard: mergeEnvFileContents(existing, defaults) → {contents, added, kept, effective} is additive only — an operator's existing key or tuning is never overwritten, and effective reports what the container will actually read — while upsertEnvLine(contents, key, value) REPLACES one key's line, for a value PortOS owns and re-derives (vllmQwenProject.js's recorded project directory); its replacement is a function, not a string, so a $-sequence in the value is written literally. Plus WSL2_PREPARE_MIN_BYTES / WSL2_PREPARE_CONFIG_HINT for the ceiling prepare needs (detected and warned about, never raised).
sglangQwenProject.js resolveSglangProjectDir() / inspectSglangQwenProject() → {dir, hasProject, composeFile, hasWeights, weightsRoot} for the operator's SGLang Qwen3.8-27B project, plus sglangStartBlockedReason(project) → the prose refusal (or null). Sibling of vllmQwenProject.js with the same tri-state hasWeights contract (true found / false caches read and empty / null no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in docs/features/sglang-qwen38.md rather than at a git clone. Also this stack's keyed view of recordedProjectDir.js — readRecordedSglangProjectDir(envPath?) / recordSglangProjectDir(dir, envPath?) / sglangProjectDirIsSettled() plus SGLANG_PROJECT_LEAF — so resolveSglangProjectDir() reads SGLANG_QWEN_PROJECT_DIR → the UNC path services/sglangQwenManager.js detected and recorded on Windows → ~/sglang-qwen38. Overrides: SGLANG_QWEN_PROJECT_DIR, SGLANG_QWEN_WEIGHTS_DIR.
sglangQwenRecipe.js The sglang serve launch line PortOS owns, per NVIDIA card class. buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port}) → {image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}, and sglangComposeYaml(recipe) renders the docker-compose.yml from it (one source of truth; a test pins the doc against it). mambaFullMemoryRatio(...) derives --mamba-full-memory-ratio from the cookbook formula (S + D) × state_bytes / (L × kv_bytes_per_token) — load-bearing, because the cookbook default 0.9 under-sizes the GDN state pool at CoS prompt lengths and silently clamps max_running_requests. Both Qwen parsers (--reasoning-parser qwen3, --tool-call-parser qwen3_coder — NOT vLLM's qwen3_xml) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. sglangCellForGpu(gpu) maps a cudaCapability.js compute-cap row to a cell (SM 9.x → h200, SM ≥10 → rtx6000/rtx5090 by VRAM, Ampere → null, which is a refusal: 24 GB stays on vLLM), and sglangUnsupportedReason({platform, status, gpus}) is the prose for every no — never collapsing a probe 'unknown' into "no GPU". Pure: no filesystem, no docker, no network.
opencodeStream.js OpenCode's --format json event stream — ONE parser, shared by services/localModelAgentBenchmark.js (which wants chars/tokens) and services/modelCapabilityTests.js (which wants a readable transcript). eventPart (accepts the flat {part} and nested {properties.part} envelopes OpenCode has both used), isToolEvent / eventText, parseAgentLine / parseAgentEvents (blank and unparsable lines yield nothing rather than throwing), formatAgentEvent (one frame → a transcript line a person can read, with the path or command the tool acted on), and summarizeOpenCodeEvents (assistant chars, tool calls, and output tokens — null, never 0, when OpenCode reported no usage; tool ARGUMENTS are deliberately not counted as answer text). Pure. The runner that produces the stream is services/opencodeTask.js.
openAiModelsProbe.js probeOpenAiModels(baseUrl, { timeoutMs, apiKey }) → { reachable, models, contextWindows, error } — the one GET {base}/models probe for the local OpenAI-compatible daemons, shared by services/observedContextWindows.js (and through it services/providerReadiness.js) and services/llamaServerManager.js. Distinguishes unreachable from reachable-but-unlistable (models: null) from up-with-nothing-loaded ([]). contextWindows keys each served model to the window the listing declared (max_model_len / n_ctx / loaded_context_length / context_length, smallest wins), carrying an entry only where one was declared so {} reads as unknown — without it a prompt too large for the endpoint was dispatched anyway and stalled until the provider timeout (#7441). It also names the real transport failure via describeFetchError (undici reports every one as a bare fetch failed), and cancels an unread body on a non-OK response. apiKey attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers reachable: true with error: 'authentication required' — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a timeout key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default.
openAiModelsProbeCache.js probeOpenAiModelsCached(endpoint, apiKey) and resetOpenAiModelsProbeCache() — the shared 15s TTL cache in front of openAiModelsProbe.js, keyed endpoint\napiKey (two providers on one authenticated endpoint must not inherit each other’s 401) and storing the PROMISE so N providers sharing a daemon share one socket. It lives BELOW its two readers — services/providerReadiness.js’s checklist and services/observedContextWindows.js’s pre-dispatch context gate — so a page poll and a run starting in the same window cost one listing and can never disagree about a daemon that restarted between them. An unexpected throw drops the entry rather than poisoning it for the TTL; expired entries are swept on every miss. services/providerReadiness.js#resetProviderReadinessCache clears it for the llama-server lifecycle routes.
openAiChatStream.js iterateOpenAiChat(...) → normalized async content/reasoning chunks and streamOpenAiChat(...) → the streamed text — one streaming POST {base}/chat/completions against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. streamOllamaChat(...) is the assessment-only native /api/chat transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports buildMessages, parseStreamFrame, parseOllamaStreamFrame, normalizeUsage (snake/camel/Ollama token-count keys → {completionTokens, promptTokens}, null = not reported), and resolvePartialOutput. Registering onStats on the OpenAI path asks for token counts; a daemon that rejects stream_options is retried once without it and remembered per endpoint. Sibling of openAiModelsProbe.js. Shared by Ask (services/askService.js), services/localLlmPlayground.js (provider-backed runs with a /runs record), and its runEndpointLlmTest (a bare loopback daemon PortOS holds no provider record for, which is how services/localModelAssessments.js measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with .partialOutput carrying what already streamed.
calendarSyncWindow.js overlapsSyncWindow(event, dateRange): whether a cached calendar event falls in the window a sync covered, so reconcile-prune never deletes history or far-future events a windowed fetch could not return. Shared by the Google and Outlook paths. Pure.
callerModePolicy.js The one caller EXECUTION-MODE policy: CALLER_MODE_POLICIES (agent-harness, cli-harness, direct-api, any-text) plus resolveCallerModePolicy / allowedModesFor / callerModeRejection / isCallerModeEligible / filterCallerModeEligible. Answers "may THIS caller run on THAT route mode?" for an explicit pin, activeProvider inheritance and every fallback candidate alike — allowedModesFor() is what rides on requestCapabilities.allowedModes into the toolkit's getFallbackProvider. Pure and dependency-light so the out-of-process autofixer can import it; enabled/benched state, prerequisites and text-transport consent stay with their existing owners. Unknown never becomes true: a record with no executable mode, and a required model capability with no positive evidence, are both refused.
cliChildEnv.js The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard }) returns a COMPLETE env for spawn: filters the inherited base to runtime essentials/provider auth, then layers baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra, pins PWD to cwd, strips CLAUDECODE, and (with guard: true) prepends the pm2 guard shim onto the final PATH. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. composeProviderEnv({ before, provider, model, extra }) returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: before sits UNDER provider.envVars (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), extra sits OVER it (TERM/COLORTERM for a PTY). cliChildEnv.test.js asserts the composed order per call site and discovers any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here.
agentApiToken.js AGENT_API_TOKEN_ENV (PORTOS_API_TOKEN) + AGENT_API_AUTH_CURL_ARG — the name of the loopback session token PortOS injects into a spawned agent's environment (services/agentApiAuth.js) and the quoted curl argument that spends it, so the prompt builders writing agent-facing curl snippets and the spawn sites injecting the variable cannot drift. agentApiCurl({ apiBase, path, payload }) and agentApiAuthNote({ alsoCovering }) assemble the whole call and the paragraph that must travel with it — one shape for every agent-facing API call in the tree, after two hand-written copies had already drifted on whether the install "gates" or "may gate" /api/* (it is opt-in and off by default). Pure, zero-import.
localReviewAttribution.js Worktree-private completed local code-review model receipts: resetLocalReviewAttribution, recordLocalReviewAttribution, and localReviewAttributionLabels. Stores normalized model slugs only; no roster, provider IDs, findings or credentials.
localReviewBridge.js LOCAL_REVIEW_BRIDGE_SCRIPT — absolute path of server/scripts/run-local-code-review.mjs, the stdin bridge into the local-review service (same reviewers and timeoutMs forwarding as POST /api/code-review/local, no HTTP and so no instance-password gate). localReviewAttributionErrorGate retains completed review evidence and blocks publication separately from reviewer availability when receipt persistence fails. localReviewBridgeRequest preserves claim-review isolation even if its redundant toolFree flag is cleared. Shared by the two prompt builders that hand it to agents, so renaming the script cannot break one while the other keeps working.
localReviewLifecycle.js localReviewLifecycle — durable pre-PR phase completion bound to the branch, origin, base and exact PR delivery; preserves its original reviewed head through later pushes.
agentExecutionProfiles.js Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (PUBLIC_REVIEW_EXECUTION_PROFILE, PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE); publicReviewPostureForProfile maps it to the enforceable POSTURE a provider must carry a maintained recipe for (no-tool or sandboxed-actions), which is how a pipeline stage stays vendor-agnostic. isPublicReviewRestrictedProfile covers both postures; isPublicReviewNoToolProfile / isPublicReviewActionsProfile separate them for the callers whose rule differs by posture (credential-bootstrap wrapping, child-env allowlist).
agentCompletionMode.js The ONE completion-contract decision behind every agent prompt: resolveCompletionMode(flags) returns a single COMPLETION_MODES key (tool-free, sentinel-payload, action-output, external-repository, discard-worktree, claim-flow, read-only, review-loop-follow-up, release-flow, audit-flow, reconcile-flow, checkout-recovery, tui-slashdo-free, tui, portos-merges, worktree-no-push, commit-and-push) from an ordered rule list, plus portosMergesBranchOnExit. Replaces the five independent flag ladders in agentPromptBuilder.js that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags.
localLlmConcurrency.js LOCAL_LLM_MAX_CONCURRENCY plus the per-endpoint local-LLM slot gate (acquireLocalSlot, releaseLocalSlot), in-flight activity predicate (isLocalEndpointBusy), scheme-optional port match (localEndpointsSharePort), and settle observer (onLocalEndpointSettled) — a dependency-free leaf so cosLocalEndpointSlots.js and managedDaemon.js avoid importing promptRunner.js.
localEndpoint.js Dependency-light local-instance URL predicates (isLocalInstanceHost, isLocalInstanceEndpoint, scheme-optional isLoopbackEndpoint — the one "is this a local daemon" answer, localEndpointPort) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers.
credentialBootstrap.js resolveBootstrapEnv(provider, { safetyProfile }) runs an optional envCommand argv for ordinary provider runs or a no-tool review, parses KEY=value output without evaluation, and caches credentials in memory for one minute — the alternative for a bootstrap that PRINTS credentials rather than exec'ing the harness; a record that only names the wrap form is credentialed by the wrap and gets {}. Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static apiKey PortOS stores — a provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? } record. hasCredentialBootstrap(provider) and applyCredentialBootstrap(provider, command, args) (pure) return the command+args PortOS should actually spawn: <command> <args...> <harnessId ?? command> [<argsSeparator>] <args...> — the bootstrap CLI in front of the harness invocation, naming the harness as harnessId when the bootstrap CLI uses its own identifier rather than the binary name, and inserting argsSeparator (e.g. --) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. resolveCliSpawn(provider, command, args, childEnv) composes that with Windows shim resolution (bufferedSpawn.js) for the three headless spawn sites that repeated the same sequence (runner.js, cliProviderRun.js, visionCli.js) — the argv analog of why cliChildEnv.js's buildCliChildEnv exists. Every call site keeps resolving provider.command/args unchanged for vendor detection, prompt-delivery convention, and the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal spawn/pty.spawn call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. The sandboxed-actions posture is never wrapped — it executes contributor-supplied code inside a sandbox spelled entirely in the recipe's argv, so nothing may sit in front of the harness and rewrite it; the no-tool postures (the tool-free reviewer among them) ARE wrapped, because spawned bare they carry no credential at all (#7720). The split lives in the helper, keyed on safetyProfile. The pure argv composition lives in aiToolkit/internal/credentialBootstrap.js (composeBootstrapSpawn / hasCredentialBootstrap, dependency-free), re-exported through here so the vendored toolkit's own catalog probes compose the same shape without importing out. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. Both also return wrapped, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: needsProcessGroup(wrapped) says whether to spawn detached and kill with { processGroup: true } (POSIX only — Windows' taskkill /T is already tree-wide), and processGroupKillable(child, processGroup) adapts a child for the aiToolkit runner's external-run registry, whose vendored killProcessTree has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. trackDetachedGroup(child, processGroup) / signalDetachedGroups(signal, logFailure) are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at npm start) from orphaning one.
cliProviderArgs.js Per-CLI argv conventions (buildCliArgs) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it.
cliProviderRun.js One-shot CLI provider invocation (pickCliProvider + runCliProviderPrompt) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional safetyProfile runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers.
cliStderrNoise.js isKnownCliStderrNoise(trimmedLine) — drops the real Anthropic claude CLI's harmless [claude-code:unrecognized_model] SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's ANTHROPIC_BASE_URL at a local Ollama model the SDK doesn't recognize.
codedError.js codedError(message, code) — dependency-free Error carrying a machine-readable code. The one shared form of the per-service makeErr: a service owns an ERR_* vocabulary, throws codedError(msg, ERR_X), and the route maps err.code to a status via createServiceErrorMapper (errorHandler.js). Reach for ServerError instead when the throw site already knows the HTTP status. A leaf so a service can raise one without pulling errorHandler.js into its import closure.
codex.js OpenAI Codex CLI (codex) provider helpers — the CODEX_COMMAND/CODEX_CLI_ID constants, the isCodexCommand and isVisionCapableCodexTuiProvider predicates, and ensureCodexTuiArgs (injects --dangerously-bypass-approvals-and-sandbox + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via argvHasFlag). Extracted from tuiHandshake.js (#3618) to match the one-file-per-vendor shape of antigravity.js/grok.js/kimi.js/cursor.js, which providerVendors.js consumes as registry rows. Also owns buildCodexOssArgs — the --oss --local-provider <ns> pair emitted from a record's ollamaBacked marker, so the Codex harness runs on a local model without rewriting the user's ~/.codex/config.toml (the record-classification half of that lives in providerModels.js, so providerPrerequisites.js can classify a codex record without importing a vendor argv module).
cursor.js Cursor Agent (cursor-agent) provider helpers — the CURSOR_COMMAND binary constant, the isCursorCommand predicate, and the ensureCursorHeadlessArgs (--print --force, folding any pinned reasoning effort into --model) / ensureCursorTuiArgs (--force) argv builders. --force is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its auto router is a real model id passed straight to --model.
grok.js xAI Grok Build (grok) provider helpers — id/endpoint constants (GROK_API_ID/GROK_CLI_ID/GROK_TUI_ID/GROK_API_ENDPOINT), isGrokCommand/isGrokCliProvider/isGrokTuiProvider predicates, ensureGrokHeadlessArgs/ensureGrokTuiArgs argv builders (grok reads its prompt from --prompt-file /dev/stdin, not raw stdin; model selection uses the GROK_CONFIGURED_DEFAULT sentinel in providerModels.js so PortOS omits --model like Antigravity), and prepareGrokPromptFile (Windows temp-file delivery fallback; cleanup({ throwOnError: true }) reports cleanup failure to an owning lifecycle).
filmStyleGrammars.js Curated film style grammar catalog (FILM_STYLE_GRAMMARS, eight code-rendered media with rendering, colour, type, motion, camera, sound and native-move guidance), getFilmStyleGrammar, summarizeFilmStyleGrammar (picker projection) and knownFilmStyleIdSchema (request-field id check) and renderFilmStyleGrammarPrompt(id, { parts }) — one prompt section capped at FILM_STYLE_PROMPT_MAX_CHARS; unknown id or bad parts is a 400.
falVideoModels.js Curated fal.ai VIDEO model catalog — FAL_VIDEO_MODELS (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, OmniHuman v1.5 audio-to-video (FAL_AUDIO_VIDEO_MODELS: kind a2v, plus the H3 Max and Seedance reference models that hear a song slice as an audio reference (falHearsAudioReference(), default FAL_MUSIC_VIDEO_DEFAULT_MODEL); the supplied audio drives the whole picture's motion; LTX audio-to-video runs locally, never on fal), Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on FAL_VIDEO_PRICING_VERIFIED_AT; getFalVideoModel(), coerceFalVideoSeconds() (round UP to a covering length), resolveFalVideoResolution(), buildFalVideoRequest() (the exact queue body per model; null for an uncurated id, which keeps the legacy body) (a prompt over the model's promptMaxChars is refused, never cut), estimateFalVideoCostUsd() (null = unknown), describeFalVideoRate(). Dependency-free; the client re-exports it.
grokVideoClip.js Clip lengths grok's image_to_video actually delivers — GROK_VIDEO_DURATIONS ([6, 10, 15]; 6/10 measured in #3022, where a 2s/3s request returned the same 6.04s clip; 15 from xAI's 1–15 s API limit, confirmed per clip by the probe in videoGen/grok.js), GROK_VIDEO_DEFAULT_DURATION, resolveGrokDuration() (validate an already-grok-shaped request, else default), and nearestGrokDuration() (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission targetDurationSeconds). Dependency-free so validation.js / routes/videoGen.js can derive their schemas from the same list the services gate on.
fontMetadata.js fontContainer(buf) (sfnt / woff2 / null) and fontFamilyName(buf) — a font file's family name read from its name table (TrueType, OpenType, and WOFF2's brotli stream) with no font library; null for anything unreadable (#10345).
musicVideoCoverOverlay.js Music Video cover lettering (#10345): COVER_DESIGN_OPTIONS / DEFAULT_COVER_DESIGN, normalizeCoverDesign(design, { fonts }) (accepts every stored design; a font:<id> typeface only when that uploaded font is listed), coverOverlaySvg({ title, tag, design, widths, fonts }) and the coverFontSpec / fontAttrs / titleLinesFor / tagTextFor helpers the width probe reads. Pure; the server render (coverArtCompose.js) and the client's live Lettering preview run this one layout.
musicVideoShotTiming.js Music Video shot modes (#8977): MUSIC_VIDEO_SHOT_MODES (cutaway/performance), isPerformanceScene, MUSIC_VIDEO_PERFORMANCE_STYLES (lipsync/music) + isLipSyncScene, selectedPerformanceInstruction(scene) (the selected take's shot instruction, performance scenes only), clipAudioOffsetSec(instruction) (provider lead padding a landed take's edit points were moved by, #11210), SOURCE_AUDIO_LIPSYNC (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), SOURCE_AUDIO_MUSIC (music-driven lanes — fal.ai audio-to-video models, picked by videoSettings.falMusicModelId, default OmniHuman v1.5 at 1080p), falSceneTake() (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + falTakeRequestFields(take) (that take as /api/video-gen fields), performanceCapability(backend, { scene, videoSettings }) (lip-sync lane, or the music-driven one for a music-driven scene), performanceBlockedReason(backend) (Grok is cutaway-only), planPerformanceWindow() (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), planPerformanceRepair() (complete measured suffix evidence, safe word-gap boundary, source/clip timebases and next spend), clipRelativeCues(), grokCoverage(spanSec) (covering 6/10/15 s request, flags spans needing a split), approximateMotionCues(), shotSplitLimit(scene, backend) (per-take limit: lip-sync window or Grok's longest clip), planShotSplit() (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it.
reactorStartingFrame.js Fits a reactor.inc starting_frame to the fast-h3 session canvas before it is uploaded. readImageSize(path) → {width,height} or null (never a guessed dimension), and prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath) → { aspect, canvas, framePath, fittedPath }: an absent requestedAspect DERIVES the canvas from the frame's own shape (nearestReactorAspect), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. fittedPath is the temp file the caller deletes; null means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does.
reactorVideoClip.js The reactor.inc fast-h3 clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — REACTOR_MAX_PROMPT_LENGTH (800; the API rejects a longer prompt rather than truncating it), REACTOR_MIN_CLIP_SECONDS / REACTOR_MAX_CLIP_SECONDS (5.167–14.375, i.e. 124–345 frames at the REACTOR_CLIP_FPS 24 it delivers), REACTOR_MAX_CLIP_ID_LENGTH, and the picker list REACTOR_CLIP_LENGTHS + REACTOR_DEFAULT_CLIP_LENGTH + reactorClipLengthLabel() (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract set_canvas accepts: REACTOR_CANVASES (16:9 1344×768, 4:3 1024×768, 1:1 768×768, 9:16 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), REACTOR_ASPECTS, REACTOR_DEFAULT_ASPECT, reactorCanvas(aspect) and nearestReactorAspect(width, height) (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to client/src/lib/reactorVideoClip.js, parity pinned by reactorVideoClip.test.js.
runwayVideoModels.js Shared Runway image/text-to-video model capabilities, endpoint-specific request construction, duration/size selectors and verified-price quotes (null for unknown prices). Derived from the bundled OpenAPI snapshot.
runwayImageModels.js Shared Runway image capabilities, exact canvases, reference/seed limits, hosted disclosure, request validation and reference identities.
kimi.js Moonshot AI Kimi Code (kimi) provider helpers — id constants (KIMI_CLI_ID/KIMI_TUI_ID), isKimiCommand/isKimiCliProvider/isKimiTuiProvider predicates, ensureKimiHeadlessArgs (model flag only — non-interactive mode is implicit in --prompt, and kimi has no --print/--afk and refuses approval flags alongside --prompt) / ensureKimiTuiArgs (--yolo) argv builders (model selection uses the KIMI_CONFIGURED_DEFAULT sentinel in providerModels.js so PortOS omits --model like Grok/Antigravity), and prepareKimiPrompt (delivers the prompt as the --prompt <value> argv, not stdin).
runners.js Image-runner family constants (RUNNER_FAMILIES, loraCompatKey), video LoRA families, MiniMax H3 runtime predicates, and the shared AUDIO_TO_VIDEO_RUNTIMES / isAudioToVideoRuntime capability gate (LTX plus H3 Ref2VA). Mirrored to client/src/lib/runnerFamilies.js.
codexAccount.js The ChatGPT-subscription half of the Codex providers (#5589), pure. The fixed codex app-server invocation, the account/* method + notification names, CODEX_ACCOUNT_STATUS (runtime-missing / unknown / signed-out / login-pending / ready / quota-exhausted / reauth-required) and CODEX_ERROR_CODES, isCodexSubscriptionProvider (re-exported from providerModels.js; keyed on the codex COMMAND, so a renamed clone still resolves), the normalizeCodexAccount / normalizeCodexRateLimits / normalizeCodexLoginStart payload normalizers, redactCodexPayload (every log/error/response path runs through it, so "PortOS never writes down a Codex token" is one function rather than a rule per call site), and deriveCodexAccountStatus. Sentinels are load-bearing: runtimeInstalled: null = NOT PROBED, accountFetched: false ≠ signed out, rateLimits: null (failed fetch) ≠ a fetched window with nothing to report. The process half is services/codexAppServer.js.
codexTurn.js The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure. The thread/start / turn/start / turn/interrupt / model/list method names and the turn notifications, CODEX_TEXT_TRANSPORT plus providerDeclaresCodexTextTransport (advertises, reusing codexAccount.isCodexSubscriptionProvider so the two halves cannot drift) vs isCodexTextTransportEnabled (requires both the explicit opt-in and the Providers-UI read-risk acknowledgement), the CODEX_TEXT_THREAD_CONFIG safety envelope a generic text call runs under (empty throwaway cwd, no writes, no network, fail-closed approvals, no MCP servers, no web search — Codex can still read local files by absolute path; see the module docstring), normalizeCodexModels / normalizeCodexTokenUsage / resolveCodexEffort, the createTurnAccumulator → applyCodexTurnEvent → finalizeCodexTurn projection (a non-completed turn yields an error, NEVER the partial text), and classifyCodexTurnError / classifyCodexTransportError, which fold both failure shapes onto the shared ERROR_CATEGORIES the cooldown policy reads. models: null = never fetched, [] = fetched-and-empty. The process half is services/codexAppServer.js.
codexUserConfig.js READ-ONLY probe of the user's own ~/.codex/config.toml (honoring CODEX_HOME), so PortOS can SAY when a third-party bridge has re-pointed Codex model routing away from the account its cards report on. parseCodexRoutingOverride (pure) reports which of the top-level openai_base_url / model_provider / model_catalog_json keys are assigned and the base URL they name — top-level ONLY, since the same key inside a [table] is per-provider configuration and must not trip the badge. readCodexRoutingOverride adds a short TTL cache and the load-bearing sentinel: null = could not read (never paint that as "not overridden"), an ABSENT file = a definite overridden: false. PortOS never writes this file, and baseUrl is machine-local — render it, never log or federate it.
codexAssistantExtract.js Strip Codex CLI banner + echoed metadata from session transcript.
codexCliOutput.js Network/system error patterns for agentErrorAnalysis.js.
contextBudget.js Context-window budgeter for editorial passes. estimateTokens/estimateTokensFromChars (chars/4), usableInputTokens, manuscriptContentBudgetChars (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), planManuscriptPass({ contextWindow, sections }) → { mode: 'whole' | 'chunked', chunks }. Also fitContextToManuscriptFloor/capContextOverhead/trimContextToBudget — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. localOutputReserveTokens(declared, window) shrinks a caller's output reserve for a local model with a known window (floor 2,048, ⅛ of the window, capped at ¼ of the window and at the declared reserve).
localPromptBudget.js What a large prompt costs to PREFILL on a model server running on this machine (#6117). planLocalPromptBudget({ prompt, endpoint, baseDurationMs }) → { promptTokens, prefillMs, expectedDurationMs, longPrefill, … }, or null for a cloud endpoint / no prompt to measure — a sentinel a caller must read as "no estimate", never as a small one. estimateLocalPrefillMs and describeLocalPromptBudget are the token→ms and plan→sentence halves; LOCAL_PREFILL_TOKENS_PER_SECOND is a deliberately pessimistic constant, since over-estimating only widens the window a healthy run gets. Never refuses a dispatch: it raises the run's duration estimate so a ~100K-token public-review envelope reads as a long silent prefill instead of a wedged run. Pure.
ansiStrip.js Streaming ANSI / control-byte stripper.
hfErrors.js Parse huggingface_hub gated-access errors: isGatedRepoError(text) classifies a failure as gated (403/restricted), extractGatedRepo(text) → owner/name (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure.
hfCache.js HuggingFace Hub cache inspection (inspectModelCache(repoId,{revision?}) → {cached,sizeBytes,snapshotPath}, isModelCached, getHfCacheRoot). Drives the inline "Available / Download" badge on the image + video gen forms. Also verifyModelCache(repoId,{deep,revision?}) (structural safetensors-header + optional sha256 integrity check) and repairModelCache(repoId,{deep,revision?}) (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. findCachedRepoSnapshot(repoId,revision) resolves an immutable local snapshot; findCachedRepoFile(repoId,filename,{revision?}) resolves ONE known file without walking it, and findCachedRepoFiles(repoId,filenames,{revision?}) is its all-or-nothing plural form (paths in request order, or null if ANY is missing — a caller needing several pinned files, e.g. the shards of one checkpoint, can do nothing useful with a partial set); isSafeHfRepoRelativePath rejects traversal/absolute dependency filenames; verifyCachedRepoFiles / repairCachedRepoFiles apply that revision-aware exact-file contract to pinned adapter pairs; and repairCachedFile(path,{snapshotPath?}) is the containment-checked matching single-file repair. verifySafetensorsStructure(path,size) is the reusable header/size structural check.
icLoraWeights.js IC-LoRA weight registry for the local LTX-2 remix modes (IC_LORA_MODES, IC_LORA_MODE_VALUES, listIcLoraWeights(), isIcLoraMode(mode), icLoraSpecForMode(mode), icLoraRepos(), icLoraWeightCandidates(spec), findCachedIcLoraWeight(spec), resolveIcLoraWeight(mode) → {path,cached,spec}). Single source of truth mapping each remix mode (ic-control, ic-colorize, ic-ingredients) → its HF repo/filename, reference-count rule, per-weight referenceDownscaleFactor (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video'
sseHeaders.js SSE_HEADERS — the canonical SSE response headers (incl. X-Accel-Buffering:no) in a dependency-free module so any producer (sseDownload.js, sseUtils.js) can share them without pulling in a heavier module's transitive imports.
sseDownload.js `startHfDownloadStream({req,res,repo
installLogger.js createInstallLogger({installer,target}) → {start,onEvent,success,failure,cancel} — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of sseDownload.js). Logs a START line, throttled heartbeats + stage milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. onEvent(ev) auto-detects terminal complete/error SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap.

File & I/O

Module Purpose
borderKey.js Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and alpha meaningfulness/variation checks.
collectionStore.js Per-type, per-record JSON storage with explicit type-level schemaVersion stamping. Use for collections that have outgrown a monolithic JSON file. createCollectionStore({ dir, type, schemaVersion, sanitizeRecord }) returns loadOne / saveOne / saveOneNow / listIds / loadAll / loadAllResult / deleteOne / loadTypeIndex / saveTypeIndex / verifySchemaVersion. loadAll silently drops corrupt records; loadAllResult() → { records, failedIds } keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; saveOneNow is for callers already inside a collection write queue. Boot-time verifyCollectionVersions([store, ...]) logs schema-version mismatches. Type-index config slot holds cross-record state (see the TypeIndexConfig typedef + header convention): { runs?: [], featureFlags?: {}, lockPolicies?: {} } — runs is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. saveTypeIndex({ config }) shallow-merges config one level deep (a patched runs replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside queueTypeIndexWrite(fn).
comparisonModelScope.js catalogSlugForProviderModel(id) / providerCatalogSlugs(inventory) — map provider model ids (Bedrock region prefixes, gateway namespaces, effort/quantization suffixes, dashed versions) onto canonical model identities for scoping shipped reference-price rows to models PortOS can dispatch. Pure.
conflictJournal.js Non-blocking edit-conflict journal for cross-install LWW merges. maybeJournalBeforeOverwrite({kind,id,local,remote,source}) (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (detectConflict via per-record syncBaseHash + contentHashForRecord), then advances the base hash; flushBaseHashes() persists the batched base-hash side store; withBaseHashFlushBatch(fn) defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting pruneTombstoned* loop — collapses N sync_base_hashes.json rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in finally). deleteSyncBaseHash(kind,id) evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; pruneOrphanedBaseHashes(resolves) is the backstop sweep (resolves(kind,id) => bool; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. conflictJournalStore() is the pending/resolved entry store (discard resolves an entry; DELETE hard-removes it — there is no dismissed status). The base-hash file is read STRICT (readJSONFileStrict): a present-but-unreadable sync_base_hashes.json latches _persistBlocked — flushBaseHashes() no-ops so the file is preserved, maybeJournalBeforeOverwrite journals every overwrite fail-closed, detectConflict reports baseUnavailable, and isBaseHashPersistBlocked() exposes the latch to the conflict-journal status payload (#7260). Local-only — never crosses the wire.
schemaVersions.js Cross-instance sync version contract. PORTOS_SCHEMA_VERSIONS (frozen map of { category: layoutVersion }), RECORD_KIND_SCHEMA_CATEGORIES (frozen map of federated record kind → the schema categories it writes), buildPortosMeta() (envelope for every outbound sync payload), compareSchemaVersions(sender, receiver) returning { ahead, behind, compatible }, scopeVersionDiff(diff, categories) (restrict that diff to the categories a specific transfer touches), catalogEnvelopeHasLiveRows() (shared live-row versus tombstone gate for catalog transfers), and formatVersionGap() for UI/log lines. Receivers gate applyIncomingPush / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others.
dataRoot.js Data-root resolution + worktree-checkout detection (#1947). resolveInstallRoot(fallbackRoot) prefers the PORTOS_DATA_ROOT env var (pinned at real launch in ecosystem.config.cjs) over an import.meta.url-derived fallback, so a process booted from inside a CoS agent git worktree still resolves data//data.reference/ to the real install instead of the worktree's empty tree. isWorktreeRoot(rootDir) is the boot-migration backstop — true when rootDir lives under data/cos/worktrees/ (keyed on the path segment only, so a fresh install's empty data/ isn't a false positive). resolveCodeRootForModule(moduleUrl) is the single source of truth for the "two directories above this file" depth assumption — paths.js's CODE_ROOT and services/userActions.js's data-root guard both derive through it so they cannot silently drift apart. DATA_ROOT_ENV is the env-var name constant. The one pin a worktree-executing process honors is a DISPOSABLE root — one carrying DISPOSABLE_ROOT_MARKER (isDisposableRoot(dir)), which the boot smoke creates (#8343); a live install never carries it. Consumed by fileUtils.js (PATHS), server/index.js, and scripts/run-migrations.js.
downloadPreflight.js Free-disk preflight + resumable weight download. assessDownloadPreflight({ destPath, expectedBytes }) → { freeBytes, requiredBytes, headroomBytes, verdict: ok|tight|insufficient }; assertDownloadFits throws typed DISK_INSUFFICIENT (507) when the volume cannot hold the payload. streamResumableDownload Range-resumes a .partial on transport failure, discards it on user cancel, and verifies a published sha256 before rename. sweepOrphanedPartials(dirs, { maxAgeMs }) unlinks leftover .partial (+ .partial.etag) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. probeRemoteSize / siblingDownloadMeta / verifyDownloadHash are the size+digest helpers the four weight-download entry points share. createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel }) is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed <PREFIX>_DOWNLOAD_IN_FLIGHT/_STALLED/_CANCELLED errors, a per-chunk progress throttle, and an isInFlight(path) predicate covering the dest, its .partial, and shards under a claimed directory. Call it at module scope only. isAnyDownloadInFlight answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers.
agentInstructionsFile.js The AGENTS.md + bridge CLAUDE.md pair a repo carries (#4852). writeAgentInstructions(repoPath, content) writes the body to AGENTS.md and the one-line @AGENTS.md import beside it — use it in scaffolders instead of a bare writeFile(join(repoPath, 'CLAUDE.md'), …), since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME, AGENT_INSTRUCTIONS_IMPORT.
scaffoldSnippets.js Shared generated-project source snippets: CORS_SNIPPET provides dependency-free Express CORS middleware for the Express, PortOS, and Vite scaffold generators.
failureLogging.js logFailureWithStack(prefix, error, logger = console.error) — logs ${prefix}: ${message} plus error.stack as a second argument, so a fire-and-forget failure (boot init, a scheduled event handler) keeps its source location instead of collapsing to one message-only line (#6934, #7549).
faultIsolatedEmitter.js makeEmitterFaultIsolating(emitter) overrides an EventEmitter's emit() so each listener for a given event runs in its own try/catch — a throw in one listener no longer aborts dispatch to later listeners for that same call. Preserves emit order, once semantics (invokes rawListeners(), whose self-removing wrapper runs before the real listener), and the true/false had-listeners return value; leaves 'error' events on Node's default semantics. Applied to imageGenEvents/videoGenEvents (#8931), whose multiple independent listeners (socket relay, quota accounting, waiter resolution, asset indexing) must not suppress each other.
fileCore.js Cross-cutting filesystem primitives (atomicWrite, writeFileGuarded, appendFileGuarded, copyFileGuarded, renameGuarded, rmGuarded, unlinkGuarded, createWriteStreamGuarded, directory helpers, parseFilesystemStats(stats) → canonical/byte-alias metrics or null, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers.
familySettingsMap.js The merge rule every per-provider-family map in data/settings.json shares (plan prices, plan tiers) — normalizeFamilyMap(raw, normalizeValue) and mergeFamilyMap(stored, patch, normalizeValue), which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure.
fileUtils.js Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes.
nodeInterpreterPin.js resolvePinnedNodeInterpreter reads the absolute Node binary PortOS's pm2 apps are pinned to (PORTOS_NODE_INTERPRETER, exported value then .env; a missing or non-node path falls back to PATH), isUsableNodeInterpreter, and withNodeBinOnPath for scripts that must run on that runtime. CJS twin in ecosystem.config.cjs.
portosEnv.js Single server-side helper for PortOS's own .env (PORTOS_ENV_PATH anchored to installRoot per #1947, parseEnvContents, readPortosEnvValue, upsertPortosEnvLine + upsertEnvLine), with replacer-function guard for $-patterns and process.env wins precedence; scripts/lib/envFile.js stays as the zero-dependency boundary copy.
portosRootPlaceholder.js Expand leftover __PORTOS_ROOT__ tokens in apps registry fields (repoPath, appIconPath, etc.) so a partial/restored data/ tree cannot leave Apps → Git looking for a non-existent checkout. PORTOS_ROOT_TOKEN, expandPortosRootToken, expandPortosRootInApp, containsPortosRootToken. Used by services/apps.js on load and by scripts/setup-data.js / scripts/lib/rewriteAppsPortosRoot.js when seeding or rewriting data/apps.json.
pm2Jlist.js Sole owner of the strict pm2 jlist stdout parser: parsePm2JlistStdout(stdout) returns the parsed process array (incl. [] for a genuine empty read) or null when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so autofixer/shared.js can use it without the server dependency graph. services/pm2.js re-exports it as parseJlistStdout for compatibility; services/pm2.js#listProcessesStrict and autofixer/shared.js are the only non-test callers permitted to execute raw pm2 jlist.
secretText.js scrubSecretTokens(text) — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with [REDACTED] in free text bound for an LLM provider or a world-readable artifact; scrubSecretTokensDeep(value) walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based redactPayload and commandSecurity.js#redactOutput's JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive.
securityAuditLog.js logSecurityEvent(event, { refused, ...fields }) — one-line 🔐/⛔ Security [event] key=value audit trail for sign-ins, password/session/agent-key changes and refused host-control or browser-relay requests. Flattens control characters and truncates values so a caller-controlled path/Host can't forge a log line; refusals use console.warn.
securityScanEvidence.js Strict scanner evidence/request/grant schemas with committed snapshot provenance; securityScanGrantFromArgs resolves actual Codex launch pins, parseRunnerSecurityScanEvidence preserves ordered runner observations, securityScanPRDisclosure publishes bounded runner evidence independently of assistant summary truncation, and parseSecurityScanEvidence retains legacy agent reports.
homePath.js scrubHomePath(value) — replace the running user's home-directory prefix with ~ anywhere in a string, so /Users/<name>/… never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting / as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: agentRunEvents.js re-exports it for the CoS ledger, and scripts/doctor.js imports it statically because it must load from a bare checkout with no node_modules (scripts/pre-install-entrypoints.test.js enforces that).
jsonIo.js JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and createCachedStore — a TTL-cached mutable JSON document with serialized save/mutate; its load() is strict (#4115) so a corrupt file rejects instead of being overwritten by the next mutate.
settingsStore.js `createSettingsStore(filePath
mimeTypes.js MIME tables and extension allowlists (incl. UPLOAD_AUDIO_EXTENSIONS, the playable-audio subset of /api/uploads), image/video format detection (detectImageFormat, detectVideoFormat), detectMediaManifest (names bytes ffmpeg would open as an HLS/DASH/IMF/concat/SDP manifest that pulls in other files) with id3v2TagLength, and filename sanitization.
paths.js Canonical source/install PATHS, dataPath, and home-directory expansion.
pathContainment.js Dependency-free leaf holding isPathAtOrInsideDir(dir, path) (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to pathSafety.js's strict isPathInsideDir; case-folded on Windows/macOS) and canonicalizePath(path) (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so fileCore.js's #6176 guard can reach them without dragging errorHandler.js/paths.js into the closure of every server suite — see the budget in importScoping.test.js. Keep it free of non-builtin imports.
repoPublishPath.js isSymlinkFreeRepoPath(realRepoRoot, absPath, { leaf: 'dir' | 'file' }) — symlink-aware containment for publishing generated files into a managed app's repo. lstat-walks every existing component below the real root and refuses any symlink (dangling or contained), a wrong-kind leaf, or a realpath outside the root; a missing tail is allowed below a verified ancestor. The lexical isPathInsideDir cannot see a redirecting directory link (#10894, after #9668). Shared by the chiptune and sprite publishers.
pathSafety.js Filename/traversal validation, path containment, and approved image-asset resolvers.
uploads.js Upload staging/import, base64/image persistence, and safe local-file serving. assertFileNotMediaManifest(path) refuses a media upload whose bytes are a playlist or manifest before ffmpeg can probe it (the base64 and multipart import helpers apply the same check).
icloudFile.js Guards against blocking reads of evicted (dataless) cloud files. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a ~/Library/CloudStorage File Provider mount); the path and size remain but no blocks are local, and the first data access BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later fs call in the process queues forever, including the express.static read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. readIfMaterialized(path, {encoding, label}) screens with a stat() (safe — never materializes) and rejects with err.code === ICLOUD_NOT_MATERIALIZED instead of issuing the read, kicking a background brctl download so the next cycle succeeds; concurrent callers for one path+encoding share a single read. isUbiquityPath(path) resolves the containing directory's real path (memoized) rather than substring-matching, so a symlinked route into iCloud — ~/Documents/... under "Desktop & Documents Folders" sync — is still recognized. isDatalessStats(stats) is the raw predicate (size > 0 && blocks === 0) and is not safe alone (a sparse or decmpfs-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via isEvictedStats(path, stats), which is what a caller holding a Stats should use, or isSuspectedDataless(path) which does the stat itself. requestMaterialization(path, {label, retryAfterExit, onFailure}) is the fire-and-forget brctl download every brctl caller shares — read paths kick it (default retryAfterExit: true) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at DOWNLOAD_DEADLINE_MS so a wedged brctl can't hold every slot for the life of the process; the boot/settings pin in mortalLoomStore passes retryAfterExit: false so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an onFailure hook to clear that sticky path on a failed/killed download. claimBrctlMissingWarning() returns true on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited materializeAndWait). materializeAndWait(path, {label, timeoutMs}) is the awaited, bounded counterpart used by WRITE paths (mortalLoomStore before overwriting its store, obsidian.updateNote before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by MATERIALIZE_TIMEOUT_MS (20s — much tighter than the background DOWNLOAD_DEADLINE_MS because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves true only on brctl exit-0, which means the download was accepted, not completed — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: stat/open/rename/unlink never materialize, while read, write (including after O_TRUNC — truncating does NOT skip the download), link, and clonefile all do. unlink being free is a measurement, not the POSIX inference — link is pure metadata too and it does materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: brctl evict <path> works (undocumented, like brctl download), which is what makes the evict/measure/heal loop scriptable. Consumed by services/mortalLoomStore.js and services/obsidian.js.
boundedStateMap.js createBoundedStateMap({ maxSize, ttlMs }) — a Map that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on get/set (no timers); get doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state.
createKeyCachedQueue.js Per-KEY serialized async work queue (sibling to fileWriteQueue.js's single tail). createKeyCachedQueue() returns queue(key, work) that chains each work thunk onto the prior in-flight promise for that key — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; work runs on both fulfil and reject so one failure can't stall the chain; carries .clear() for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record.
createNewestWinsGuard.js Newest-render-wins ordering guard for out-of-order async completions. createNewestWinsGuard() returns { isStale(key, at), mark(key, at), clear() } — tracks the newest applied queuedAt per slot key so an older render completing after a newer one is dropped (isStale true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent at is never stale. Used by createMediaJobImageHook's opt-in guard and the catalog hook's portrait slot.
fileWriteQueue.js Serialize read-modify-write cycles so they don't interleave. createFileWriteQueue() → single-tail queue(fn) for one shared file; createRecordWriteQueue(assertId?) → id-keyed queueRecordWrite(id, fn) where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for collectionStore.queueRecordWrite parity); createKeyedFileWriteQueue() → queueKeyedWrite(key, fn) that collapses the pipeline stage stores' hand-rolled Map + per-key createFileWriteQueue factory (falsy keys → shared '__unknown__' tail; self-pruning via createKeyCachedQueue); trackDetachedWrite(promise) / drainDetachedWrites() → a globalThis-backed registry for bookkeeping a caller schedules off a queued turn and never awaits (the settings ledger row), so a teardown or shutdown can wait for it.
forgeIssueCli.js Pure gh/glab issue-filing argument shapes and output parsing — forgeLabelCreateArgs, forgeIssueCreateArgs, parseCreatedForgeIssue — so the two CLIs' body-flag, label-attachment, and label-create disagreements have one definition.
forgeIssueState.js normalizeIssueState(state) — collapse a forge issue/PR/MR state string to open/closed. GitHub reports OPEN/CLOSED; GitLab reports opened/closed/locked; anything unrecognized is treated as open so an unfamiliar state can never read as "already resolved". Shared by layeredIntelligence/forgeFiler.js and services/blockedIssueReconcile.js.
imageClean.js cleanImageBuffer(buf, { metadata, denoise }) (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · stripPngMetadataChunks / stripPngC2PAChunk (lossless PNG-chunk removers) · compositeIgnoreZone(base, original, mask, { feather }) (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · autoCleanGeneratedImage (in-place clean for post-generation hook). HTTP route in routes/imageClean.js wraps cleanImageBuffer and appends a CPU light diffusion pass (applyLightRegen from services/imageGen/regen.js) for the diffusion=light SynthID-disruption step.
imageCleanDefaults.js resolveCleanersFromConfig(modeCfg, mode) and resolveImageCleaners(body, settings, mode) — dependency-free saved defaults and request overrides; C2PA defaults on for codex/external, denoise stays opt-in.
imageFrameStats.js Degenerate-frame classifier (#4173) — describeFrameStats(bufferOrPath) runs one sharp .stats() decode and returns { ok, reason, perChannel }, rejecting solid-fill (every colour channel stdev under SOLID_FILL_STDEV_EPSILON), fully-transparent (alpha max 0) and near-empty (greyscale entropy under NEAR_EMPTY_ENTROPY_FLOOR), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. ok is three-valued — true/false/null, where null means could-not-measure (undecodable buffer, or under MIN_JUDGEABLE_PIXELS) and must never read as degenerate; gate on isDegenerateFrame(stats) / ok === false, never !ok. Called by the Image Gen provider completion seams, sprite reference normalization, and visionTest.js (so a paid vision call is never spent on a blank frame). A buffer verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a path is never memoized (the file behind it can change), so hand it bytes you already read. stats-unavailable is never memoized either — that branch catches transient probe failures too, and pinning ok: null on valid bytes would disable the gate for them. __resetFrameStatsCache() drops the memo in tests.
imageThumbnail.js Lazy, single-flight WebP previews for flat gallery PNG files, refreshed when the source changes.
imageRgba.js Sharp-backed RGBA boundary: decodeRgbaFrame decodes an image to { data, width, height }, and encodePng turns a raw frame into PNG bytes for the caller's destination/hash policy.
imageWatermark.js removeCornerWatermark (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers resolveWatermarkRegion / inpaintRegion. Distinct from SynthID regen — this targets the visible corner logo.
localImageFilename.js localImageFilename(urlOrPath) resolves a stored image reference to the bare gallery-image filename under data/images/ (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (headshotImageFilename/portraitImageFilename/coverImageFilename/startingImageFilename are thin wrappers). Also exports assetBasename(pathOrName), the shared strip-querystring→basename primitive (reused by moodBoard's imageUrlToAppAsset).
pngMetadata.js extractGenerationMetadataEntries shares the bounded projection between PNG text chunks and video container tags. extractPngGenerationMetadataFile seeks past pixel data for bounded disk-file metadata extraction. Bounded PNG tEXt/zTXt/iTXt extraction for Stable Diffusion-compatible provenance plus normalization of prompt, negative prompt, sampler, steps, CFG, seed, size, model, and model hash fields; GENERATION_METADATA_LIMITS shares the projection bounds with catalog sync validation. Pure.
threejsModel.js Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: evaluateThreejsFlatness(spec) counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an extrude with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. buildThreejsFlatnessFeedback(flatness) turns that into default refinement feedback; listSpecNames(names) is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: evaluateThreejsMaterialPlausibility(spec) keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's type never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. buildThreejsMaterialFeedback(plausibility) turns that into default refinement feedback. The same pass emits a reflective-material-without-environment note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while environment.preset is none — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less attachmentPartIds and the anchored `attachments: [{ partId, anchorPartId
threejsModelAnimation.js summarizeThreejsAnimation(spec) — clip inventory and playback gate over an already-validated Three.js spec: { animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }. The schema proves a declared animation block is well formed (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model declared — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (clip-start-pose-mismatch), a handover between sequences that do not meet (clip-sequence-jump), a loop: true clip that does not return to where it began, a one-shot idle, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. buildThreejsAnimationFeedback(animation) turns those findings into default refinement feedback. A spec with no animation key summarizes as not animated — never as evaluated-and-empty.
threejsModelClipPose.js evaluateThreejsModelClipPose(clip, timeSeconds) — the declarative clip pose evaluator (owner per part+channel, step visible, the four easing curves) shared by the preview (client/src/lib/threejsAnimation.js re-uses it) and the physical audit, so the gate measures the pose the user sees; its test pins it against the emitted THREEJS_PLAYER_SOURCE.
threejsModelCoverage.js evaluateThreejsPartCoverage(spec, { family }) — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a note). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to promise. buildThreejsCoverageFeedback(coverage) turns the error findings (plus any family gap) into default refinement feedback.
threejsModelEnvironment.js The image-based-lighting and render-profile half of the procedural sculpt contract, kept dependency-free so the client suite can import it to assert parity with client/src/lib/threejsEnvironment.js (threejsModel.js pulls in zod, which the client CI job does not install). THREEJS_ENVIRONMENT_PRESETS (none/neutral/studio) is the bounded preset list the spec schema builds its enum from; resolveThreejsEnvironment(spec) normalizes a spec's { preset, intensity } block, reading an absent, partial, or unrecognized one as DEFAULT_THREEJS_ENVIRONMENT per field — a record stored before the block shipped has no key and was rendered with no environment, so none is the honest reading of it. THREEJS_RENDER_PROFILE is the output-colour-space / tone-mapping / exposure contract buildThreejsFactorySource() stamps onto every export.
threejsModelFamilies.js Curated subject-family checklists for Three.js generation. THREEJS_MODEL_FAMILY_OPTIONS / THREEJS_MODEL_FAMILY_IDS drive the picker and route validation; buildThreejsFamilyChecklist(id) returns the prompt block spliced into generation ('' for the default general, so an un-narrowed subject keeps the unchanged general-purpose prompt); findMissingFamilyComponents(spec, id) reports which required components the spec never mentions.
threejsModelPenetration.js evaluateThreejsPenetration(spec) — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same THREE.Euler 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (error) or unrelated parts occupying substantially the same space (warning). Parts in the same subtree and declared attachmentPartIds are exempt — embedding is what those relationships are for — and a shallow or transparent-container overlap is reported as an undecided note, never as a defect. buildThreejsPenetrationFeedback(penetration) turns the errors and warnings (never the undecided notes) into default refinement feedback.
threejsModelPhysicalAudit.js evaluateThreejsPhysicalAudit(spec) — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (floating-part), swallowed geometry (buried-geometry), z-fighting coplanar surfaces (coplanar-surface), unprovenanced appearing geometry (unprovenanced-transition), non-uniform parent scale cascading into descendants (nonuniform-parent-scale), attachments declared with nothing to hang from (unanchored-attachment, warning), and attachments measured further from their declared anchor than maxOffset allows (attachment-far-from-anchor, error — the spec asserted the relationship itself), across the resting pose and the sampled clip poses so a clip that carries an attachment away from its anchor is caught too — interior times (each sequence midpoint, plus a subdivision per 90° of large rotations) as well as boundaries, under a 48-pose budget dealt round-robin across clips; poseCoverage records which clip times were measured and which the budget omitted, and an omission is a clip-poses-unsampled note rather than a clean pass. Named left/right pairs are additionally audited for handedness in the resting pose — measured in the frame of the pair’s nearest common ancestor, since the lateral plane a pair mirrors across is the one their shared parent defines and not world x = 0 — which no bounds check can see — a limb mirrored by a 180° yaw about the vertical axis rather than a lateral reflection (bilateral-chirality), by a negated scale component (bilateral-mirror-scale), or not mirrored at all so both halves sit on one side of the lateral plane (bilateral-pair-same-side), all warnings. An attachment whose anchor geometry could not be measured is listed in unmeasuredAttachments rather than counted as passing. buildThreejsPhysicalAuditFeedback(physicalAudit) turns actionable findings into default refinement feedback.
threejsModelPlayerSource.js THREEJS_PLAYER_SOURCE — the fixed clip-player source buildThreejsFactorySource emits into every exported Three.js module, giving a standalone consumer createSculptAnimationPlayer(root, { onCue }) (plus evaluateSculptClipPose / collectSculptCues) over the node map and validated animation block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes update(deltaSeconds) from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving opacity. Semantics mirror client/src/lib/threejsAnimation.js — change one and change the other.
threejsModelRig.js evaluateThreejsRigReadiness(spec) — honest rig-readiness report over an already-validated Three.js spec: { articulationReady, reasons, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, rootJointId, subjectType }. The schema proves the optional articulation graph is well formed (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is useful (more than a lone root, every child joint carrying a pivot axis, every declared attachment naming what it hangs from) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses.
threejsTransform.js Affine transform primitives shared by every server-side gate that reconstructs where a Three.js scene-spec part sits in the world — rotationMatrix (row-major 3×3 matching THREE.Euler order XYZ, the composition the preview canvas and exported factory both apply), scaleLinear, multiplyLinear, applyLinear, applyTransform, composeTransform(parent, { position, rotationDegrees, scale }), vectorLength, degreesToRadians, IDENTITY_LINEAR / IDENTITY_TRANSFORM. One owner for math threejsModel.js, threejsModelPenetration.js and threejsModelPhysicalAudit.js each used to spell separately. A non-finite rotation component reads as 0 degrees and a non-finite scale component as 1, matching what the renderer does with a malformed stored spec — feeding null/NaN through instead produced NaN bounds that the audits read as "no overlap" and "no defect".
pgFileFacade.js Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). isFileBackend() (dev/test escape-hatch predicate) · resolvePgBackend({ requirement, migrate?, loadDb, makePg }) (health-check → ensureSchema → one-time migration → import db.js → build the PG backend) · createPgFileFacade({ makeFile, makePg }) (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns { getBackend, getBackendName, reset }). Each store keeps its own makeFile/makePg factories + public surface. createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? }) wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → { selectBackend, getBackendName } where the name is 'file'/'postgres'; isFileBackend() is MEMORY_BACKEND=file or isTestRunner(); isTestMode replaces that test signal (Sprites passes isTestRunner()).
multipart.js Streaming multipart/form-data parser.
safetensors.js readSafetensorsHeader(path) reads only the JSON header of a .safetensors file (never the tensor payload). detectFlux2VariantFromHeader(header) / detectFlux2Variant(path) classify a LoRA as FLUX.2 Klein '4b' (hidden dim 3072) vs '9b' (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. classifyLoraKeyLayoutFromHeader(header) / classifyLoraKeyLayout(path) classify the key layout as LORA_KEY_LAYOUTS (bare / comfyui / diffusers / kohya / not_a_lora, null = unreadable), isKnownLoraKeyLayout(layout) validates a layout read back out of persisted state, and videoLoraLayoutIssue(layout) returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or null when it can).
loraEffect.js LoRA adapter-effect report rules — the JS half of the scripts/lora_effect_probe.py diagnostic (#4872). client/src/lib/loraEffect.js re-exports LORA_EFFECT_STATUSES from here; loraEffect.test.js holds LORA_EFFECT_PROBE_VERSION in lockstep with the probes PROBE_VERSION— drift silently disables the cache.LORA_EFFECT_STATUSES (ok/zero/nonfinite/unreadable/unmeasurable) + isKnownLoraEffectStatus; normalizeLoraEffectReport(raw,{sizeBytes,mtimeMs,measuredAt})coerces every non-finite number tonull, drops statistics when nothing was measured so "no data" can never read as "measured 0.0", and downgrades a zerostatus that no measurement backs;readCachedLoraEffectReport(raw,{sizeBytes,mtimeMs})returns a stored report only while its probe version, file size AND mtime all still match, which is what letslistLoras()surface one without ever spawning a probe;loraEffectIssue(report)is the user-facing refusal phrase for a measured entirely-zero adapter andnullfor EVERY other status;formatLoraEffect(report)` is the one-line log/UI summary.
pdfImageEmbed.js PDF image embed helpers for comic / volume PDFs.
zipArchive.js Buffer-backed ZIP reader over the central directory — readZipArchive(buffer, { maxEntries }) lists members with their raw names, isDirectory/isSymlink (Unix mode bits) and a lazy CRC-checked read(); unsafeZipEntryName(name) names why a member path is not a plain relative path (absolute, .., backslash, NUL). For imports that must refuse traversal and symlink members rather than rewrite them.
zipStream.js Streaming ZIP parser (parseZip, unzipper-style); collectZipEntry(entry, maxBytes?) buffers one parseZip entry into a Buffer (size-capped); collectZipEntries(path, { match, onMatch, maxBytes? }) owns the multi-entry import lifecycle (teardown, autodrain, per-entry await) leaving callers only match/parse; isZipUpload(file) predicate for an uploaded ZIP; extractZipEntryToBuffer(path, match) cracks one member out to a Buffer.
zipWriter.js Minimal ZIP writer — createZip(entries) builds a stored (uncompressed) archive Buffer that round-trips through parseZip; crc32(buf) is the dependency-free checksum it uses.
assetHash.js Cross-transport SHA-256 cache for data/images/* — persists hashes in the asset's .metadata.json sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. sidecarGenParamsHash canonically hashes a sidecar's gen-params (excludes the machine-local sha256 cache block) for cross-machine sidecar-convergence comparisons.

Process execution

Module Purpose
agentGuard/ agentGuardEnv(baseEnv?) + AGENT_GUARD_BIN — env patch that prepends a guarded pm2 shim (bin/pm2) to a spawned AI agent's PATH so a confused --dangerously-skip-permissions agent can't pm2 kill / pm2 delete all the shared daemon (which would down every app, incl. PortOS). Blocked-subcommand list mirrors validatePm2Command in commandSecurity.js. POSIX-only (no-op on Windows).
bashResolver.js resolveBashBinary() — resolves the POSIX bash for running bundled *.sh scripts (e.g. scripts/db.sh). On Windows a bare bash often resolves (via PM2's PATH) to WSL, which mounts drives at /mnt/h and can't see a H:/... drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from git on PATH → bare bash). No-op (bash) on non-Windows. toBashPath(p) — the companion path rule: bash reads backslashes as escapes, so a Windows path must reach it with forward slashes.
interactiveShellResolver.js resolveInteractiveShell() — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old COMSPEC default meant cmd.exe, where no command a user would type reaches another drive: cd I: silently PRINTS that drive's cwd and stays put, a bare I:\ is "not recognized as a command", and cd 'I:\path' is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on C:. Resolves PORTOS_SHELL → newest pwsh.exe under %ProgramFiles%\PowerShell\<major> (majors enumerated and sorted numerically, so a future 8 needs no code change) → any pwsh.exe on PATH via findCommandOnPath (scoop/choco/Store shim) → powershell.exe 5.1 (ships with Windows) → cmd.exe last. PowerShell crosses drives with every form. On POSIX: PORTOS_SHELL → existing SHELL → /bin/bash /usr/bin/bash /bin/sh /usr/bin/sh then zsh if present → bare bash/sh via findCommandOnPath → bare sh last — never a hard-coded missing /bin/zsh (PM2/containers often lack SHELL and zsh; node-pty then execvps and the Shell page shows only execvp(3) failed). Memoized; _resetInteractiveShellCache() for tests. resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath}) is the un-memoized injectable form for tests.
fullDiskAccess.js fullDiskAccessDetails() → { fullDiskAccess, remediation } — names the exact binary macOS Full Disk Access must list (walks ps ancestry: a terminal .app when one started the server, else the server's own node binary plus a distinct pm2 daemon node under a LaunchAgent), with FULL_DISK_ACCESS_SETTINGS_URL. Used by the iMessage and Contacts setup checks.
openFolder.js openFolderInSystemExplorer(localPath) — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child error handler prevents spawn failures from crashing the process.
childProcess.js Drop-in child_process replacement that defaults every spawn to windowsHide: true — spawn / spawnSync / fork / exec / execSync / execFile / execFileSync, plus a ChildProcess re-export. Server runtime code must import from here, never from child_process directly (enforced by childProcess.guards.test.js): a console-less PM2 fork spawning a console child without CREATE_NO_WINDOW makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. exec/execFile carry util.promisify.custom so promisify(execFile) still resolves to { stdout, stderr }. An explicit windowsHide: false is respected. Background: docs/WINDOWS_CONSOLE.md.
bufferedSpawn.js bufferedSpawn(cmd, args, opts) (structured non-throwing result) + bufferedSpawnOrThrow (throwing adapter), plus killProcessTree, terminateWithEscalation(child, { graceMs, label, processGroup }) (SIGTERM now, SIGKILL after the grace if the child is still running; returns a cancel for the caller's close handler — the one stop-escalation helper, used by the operator command runner's stop and by bufferedSpawn's own timeout), resolveWindowsExecutable, prepareWindowsSafeSpawn, prepareCliSpawn(command, args, env) (composed resolve+wrap for a spawn()-safe pair), needsShell, IS_WIN32, WIN_CMD_SHIMS, MAX_OUTPUT_BYTES, guardChildStdin(child) (attach the no-op stdin 'error' listener BEFORE any stdin.write/stdin.end — a child that dies before reading stdin makes the pipe emit EPIPE, and an unlistened stream 'error' outside the Express request lifecycle takes the whole server process down; call it at every spawn that writes to a child's stdin) + deliverChildStdin(child, payload, label) (its other half: write-then-end() with a synchronously-throwing write caught, the pipe destroyed so a reading child sees EOF rather than hanging, and the failure logged so an empty-prompt run that exits 0 isn't filed as clean), spawnFailureDetail(result, fallback) (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a --json CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (killGraceMs, default 8s), Windows .cmd/.bat shim resolution, and taskkill /T /F tree-kill. killProcessTree(child, signal, { processGroup }) takes the POSIX group down too when the child was spawned detached (Windows always tree-kills). A killable that is NOT a ChildProcess — a node-pty IPty TUI session — is killed through its own .kill(), with no signal on Windows: node-pty throws Signals not supported on windows. for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by appBuilder.js, appUpdater.js, the CoS agent spawners, and setupScriptRunner.js.
setupScriptRunner.js spawnSetupScript(envVars) / stopSetupScript(child) / SETUP_IMAGE_VIDEO_SCRIPT — the one way to run scripts/setup-image-video.sh (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under resolveBashBinary() with a toBashPath script path, and on Windows presets the PYTHON_BIN the script would otherwise default to python3 for. Cancel via stopSetupScript, which tree-kills so uv / pip / git die with bash.
commandExists.js commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd }) — does running cmd args succeed? A capability probe (spawn-based, with a deadline that settles even when the child ignores termination), not a PATH lookup like processEnv.js's whichFirst; env/cwd let a caller check the exact child process configuration. Consolidates the two previously-private copies in localLlm.js/ollamaManager.js; callers probing a heavier CLI (e.g. codeReview.js's reviewer-binary probe) pass a longer timeoutMs. Sibling commandOutput(cmd, args, opts) runs the same probe but returns the trimmed stdout (or null when it could not run / exited non-zero), so a caller can read a --version banner or a models listing without spawning the same child twice.
runCliBounded.js runCliBounded(cmd, args, { timeoutMs = 15000, ...spawnOptions }) — never-rejecting, never-hanging CLI runner resolving { code, stdout, stderr }; kills a child still running at timeoutMs and resolves code: -1 (stderr preserved, else timed out); pins PWD via withSpawnCwdEnv. Use it for every gh/glab/git call a scheduled job awaits (#11678).
spawnCwd.js resolveSpawnCwd(workspacePath, fallbackRoot, label) — resolves and logs the working directory a run/agent spawns into (expanding ~), and throws when a workspace was requested but is missing / not a directory. Behind services/runner.js#resolveRunCwd, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app repoPath from silently spawning in the PortOS checkout (#3180). usesCreativeDirectorScratchCwd(task) / creativeDirectorScratchCwd(agentId) / removeCreativeDirectorScratchCwd(agentId) / resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId }) — Creative Director no-worktree tasks get a per-agent scratch cwd under os.tmpdir()/portos-cd-cwd/<id> (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). removeCreativeDirectorScratchCwd is the matching finalize cleanup. withSpawnCwdEnv(env, cwd) — returns a copy of env with PWD pinned to cwd (dropping stale case-variant keys), because spawn({ cwd }) doesn't rewrite the inherited PWD and OpenCode resolves its project root as process.env.PWD ?? process.cwd() (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (bufferedSpawn, spawnDetached) already do, so their callers inherit it. spawnCwd.test.js discovers cwd-passing spawns across server/ and fails on any that neither pins nor is listed exempt.
commandSecurity.js Two allowlists, one parser. validateCommand(cmd) gates the OPERATOR-driven runner against ALLOWED_COMMANDS (+ validatePm2Command(args), which rejects daemon-wide pm2 kill/startup/unstartup and <verb> all). validateUnattendedCommand(cmd) gates the UNATTENDED lane (Layered Intelligence cmd sources) against the far narrower UNATTENDED_READONLY_COMMANDS — read-only inspection binaries only, no npx/node/python/pip/curl/wget/brew, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so git reset --hard / git commit, find -delete / -exec, and gh/glab writes (api -X POST, pr merge) are rejected while git log, find -name and gh pr list pass. Both share one parse + DANGEROUS_SHELL_CHARS body. Mirrored by the agentGuard/ PATH shim for agentic paths.
detachedSpawn.js spawnDatabaseMaintenanceWorker(id, token) launches only the fixed, one-use fenced offline-transfer worker and retains its supervisor evidence; it grants no ordinary launch bypass. spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?}) → ChildProcess-like handle for a long media job that SURVIVES pm2 restart portos-server. A pure-sh double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — detached:true alone doesn't, since it only changes the process group); the server tails on-disk log files for stdout/stderr/close. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never detached:true, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (taskkill /T /F there, the process group on POSIX). Used by loraTraining + videoGen. Also exports reattachDetached(controlDir) / isReattachable(controlDir) to RE-ATTACH a survivor after a restart, isDetachedRunning(controlDir, expectedProcess?) with optional executable/argument validation for fixed-command control dirs, and reapDetached to checkpoint-kill one when re-attach isn't possible. snapshotProcesses() (POSIX pid/pgid/start/command table, fails closed on unreadable rows), signalProcessGroup(pgid, signal) and isDetachedSupervisorCommand(command) back database-maintenance descendant reconciliation; completed POSIX launches retire their registry record once two snapshots prove the launcher group empty.
hostShutdown.js Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). markHostShuttingDown() / isHostShuttingDown() are the in-process latch the SIGTERM/SIGINT handler sets first thing; shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused}) keeps every spawn path on the same preserve-vs-finalize policy. writeHostShutdownMarker({agentIds,signal}) / readHostShutdownMarker() / clearHostShutdownMarker() persist that verdict to data/cos/host-shutdown.json so the NEXT boot's orphan sweep can requeue those agents as interrupted — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path.
httpDrain.js createHttpDrain(servers) tracks every ordinary request the HTTP listeners accept; begin(windowMs) is the synchronous shutdown step that stops intake on all of them (server.close() plus a 503 Connection: close gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves { remaining } once accepted requests finish or the window ends (#8323).
upgradeFallback.js installUpgradeFallback(server, options) bounds the lifetime of unclaimed HTTP upgrade requests (ending and destroying them after timeoutMs, default 1000ms) to replace engine.io's destroyUpgrade timer so reverse proxies with slow upstreams (e.g. Eidoverse /ws) can complete handshakes without being cut short (#12069). Exempts claimed upgrades (socket.portosUpgradeClaimed = true via markUpgradeClaimed(socket)) and requests matching Engine.IO's listener on the server.
httpCompression.js httpCompression negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and no-transform.
execGit.js execGit(args, cwd, options) and execGitSafe(args, cwd, options) shared process boundary for Git operations, worktrees, and services/forgeAuth.js credential resolution. The safe variant converts rejections into { exitCode: 1, stdout: '', stderr }; services/git.js re-exports both for compatibility. cwd is REQUIRED — it rejects on a missing/blank one rather than letting spawn fall back to process.cwd() and run git against PortOS's own checkout (#4554).
ffmpeg.js runFfmpegProcess({ bin, args, signal, timeoutMs }) — timeoutMs (opt-in; FFMPEG_FRAME_TIMEOUT_MS for one frame, FFMPEG_SCAN_TIMEOUT_MS for a full-file pass) SIGTERMs then SIGKILLs a stalled child and resolves { ok:false, reason:'timed out after <n>s' }; the signal abort path escalates the same way. Long encodes pass no ceiling. probeMediaTags reads container/stream tags, returning null when inspection fails. Shared ffmpeg helpers (videoGen + videoTimeline). vfrSyncArgs(bin) probes/caches supported VFR output flags per binary (fps_mode on current builds, vsync on older builds); inconclusive probes stay uncached. probeVideoGeometry(videoPath) measures a finished clip's { width, height, fps, numFrames, durationSec } (null when any axis is unreadable) for hosted renders that record no frame count. generateThumbnail(videoPath, jobId, { atSec } = {}) accepts a clamped poster seek while preserving the single-clip default. Includes probeFrameCount(videoPath) (metadata nb_frames, falling back to a real -count_frames pass — expensive, so call it once per file) and trimVideoFromFrame(videoPath, outPath, {startFrame, fps}) — a frame-EXACT head cut via the trim filter (an -ss seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with atrim when the clip has a soundtrack and taking -an when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; outPath may equal the input (temp-file + rename install). Used by the chained-render context window — see videoContinuity.js. buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio}) builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a filter_complex graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass withAudio only when EVERY input has an audio stream — check with hasAudioStream). buildExtendSpliceArgs({sourcePath, generatedPath, outPath, keepFrames, newStartFrame, width, height, fps, audio, sourceAudioPath, masterOutPath}) is the plain-Extend counterpart: source frames [0, keep) + render frames from newStartFrame, one encode, audio crossfaded (~40 ms linear) at the seam; sourceAudioPath swaps the source span's audio for a lossless master and masterOutPath also writes the mix as a 24-bit FLAC master, so the delivered AAC is encoded once from PCM. Its stream-copy sibling is buildExtendNewSpanArgs (encode only the render's new span) + buildExtendConcatList + buildExtendCopyArgs (join it to the untouched source with -c:v copy); probeVideoCodecSignature gates it and videoFrameHashes (per-frame MD5) proves the join before anything is replaced; audioFingerprint / sealAudioMaster / readAudioMasterFingerprint bind a master to the exact decoded soundtrack it was mixed for so a replaced soundtrack invalidates it — driven by services/videoGen/extendSplice.js. H264_ENCODE_ARGS / AAC_ENCODE_ARGS are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: BT709_CONTAINER_ARGS (the colr atom, always emitted) plus bt709TagFilter() → the BT709_TAG_FILTER setparams=… string, or null on an ffmpeg without that filter (supportsSetparamsFilter() probes -filters once per process; null = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. buildTrimConcatArgs takes the filter as its colorTagFilter option rather than probing, to stay pure. installEncodedVideo(tmpPath, targetPath, label) is the shared in-place install: move the original aside to a .bak on Windows (where fs.rename refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning {ok:true,outPath} / {ok:false,reason} so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; pipeline/audioMux.js is the out-of-module caller. edgeFadeFilter(durationSec) is the -af fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. Loudness mastering (#10249): MASTER_LOUDNESS (-14 LUFS / -1.5 dBTP / LRA 11), planLoudnessMaster (measure then build the linear apply filter; throws on a silent source), reportMasteredLoudness (post-encode before/after numbers).
ffmpegFilterGraph.js filterGraphViaFile(bin, args, path) moves a -filter_complex graph over FILTER_GRAPH_ARG_LIMIT into a file (-/filter_complex, or -filter_complex_script before ffmpeg 7), since Linux and Windows cap argument length. Used by the music video render and excerpt encodes.
forgeAccessErrors.js isForgeNoAccessError(err) / isForgeNoAccessMessage(text) / logForgeNoAccessOnce(scope, repoSpec, detail) / forgeNoAccessRemedy(repoSpec) — tells a PERMANENT gh no-access 404 (Could not resolve to a Repository, HTTP 404) apart from a transient blip. execGh stamps ghNoAccess on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (branchReconcile, prWatcher) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. __resetForgeNoAccessLog() is the test seam. The same file classifies a MISSING OAuth scope (parseForgeMissingScopes(text) / forgeMissingScopesOf(err) — GraphQL without `workflow` scope, REST needs the "x" scope, gh's missing required scopes [x]; never Resource not accessible by integration): execGh stamps ghMissingScopes and keeps it out of backoff, forgeScopeRefreshCommand(host, scopes) builds the hand-run gh auth refresh fix, and REFRESHABLE_FORGE_SCOPES is the closed set PortOS will drive itself (services/forgeScopeRefresh.js).
forkHead.js normalizeForkHead(value) / forkRemoteName(ownerLogin) / resolveTaskForkHead(metadata) — the validated {remoteUrl, ownerLogin} address of a cross-repository PR's head branch, which has no origin/<branch> to attach to. Fail-closed: anything that isn't a usable pair (or that starts with -, which git would read as an option) is null, so every caller falls back to origin-only behavior instead of guessing. forkRemoteName is the deterministic fork-<owner> remote name that makes a re-attach reuse the remote it already added. Shared by appPullRequests.js (produces), agentWorktreeCleanup.js/prRemediationFollowUp.js (persist in task metadata), agentWorkspacePrep.js (threads), and worktreeManager.js (consumes — it has no forge client of its own). resolveTaskForkHead is the single reader of the generic forkHead task-metadata key, the fork-side counterpart to taskTargetBranch.js.
frameQuality.js Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. scoreFrame({width,height,data},{recency}) combines three terms over a raw single-channel buffer: log-compressed gradientVariance (focus), distance of meanLuma from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: usable gates on raw gradient variance against MIN_SIGNAL_VARIANCE alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract imageFrameStats.js keeps. Gating on the composite score instead would reject every night scene on the exposure term. TAIL_WINDOW_SECONDS is capped at the reach of the single -sseof -1.0 seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. pickBestFrame(paths) decodes each candidate through sharp and returns the winner (or null when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its index is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. MAX_CANDIDATES is derived from the window, never set independently — the ffmpeg-side -frames:v cap truncates from the NEWEST end, exactly the frames recency prefers. TAIL_WINDOW_SECONDS / CANDIDATE_FPS / MAX_CANDIDATES define the window the caller decodes from. Consumer: services/videoGen/local.js#extractLastFrame.
ffmpegRenderGuard.js attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose}) — shared spawn-state tracking + exactly-once terminal guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior.
gitArgs.js PROTECTED_BRANCHES, validateFilePaths(files), isGitStageableFilePath(file) — pure command-arg builders/validators for git.js (reject injection/traversal in staged paths). isGitStageableFilePath is validateFilePaths' non-throwing twin, for callers that must refuse an unstageable path BEFORE writing the file rather than 500 on the commit.
gitCommitProbe.js commitsSince(workspacePath, sinceMs) / committedDuringRun(workspacePath, sinceMs) count commits by COMMITTER date for completion criteria. runWindowDiff(workspacePath, sinceMs, {maxChars, head}) returns accumulated <base>..HEAD text, advancing the pre-window base to the remote-default merge base when ancestry proves it newer, so absorbed upstream changes are not graded as agent work (#7690). It uses local refs only; already-upstream agent commits are intentionally excluded. Old agent records still need only their timestamp, and an unavailable remote-default ref retains the time-window fallback. A failed comparison or unordered bases returns a reason with a null diff; '' means a valid empty diff. The returned base names the actual comparison commit; an optional pinned head keeps published review references reproducible.
gitForge.js parseGitRemote, parseGitHubOwnerFromRemote, pickGhAccountForOwner, detectForgeCli, parsePullRequestUrl — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by git.js. Pure except that parseGitRemote canonicalizes an ssh Host alias through sshHostAlias.js.
sshHostAlias.js resolveSshHostAlias, parseSshHostAliases — resolves a personal SSH Host alias (git@github-acme:…, backed by HostName github.com in ~/.ssh/config) to the host a remote actually connects to. Every remote-URL host parser (gitForge.parseGitRemote, gitRemote.parseGitRemoteUrl, workTracker.hostFromOriginUrl) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host.
gitOutputParsers.js parseStatus, parseDiffStat, parseBranchVerboseLine, parseSubmoduleStatusLine/SUBMODULE_STATUS_RE, extractAgentSummary — pure parsers turning git command output into structured data for git.js. extractAgentSummary anchors on agentOutputMarkers' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. isBenignConcurrentFetchRefRace(stderr) reads a non-zero git fetch as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, getRemoteBranches, and CoS agent worktrees fetch one .git at once.
githubNotificationAudit.js AUDIT_WINDOW_DAYS, buildAuditSuggestions — the GitHub notifications subscription audit's suggestions from 30 days of stored threads per repo × reason: unwatch, mute handled threads, and links for settings the API cannot change.
githubNotificationParse.js parseGhIncludeOutput, linkHeaderHasNext, pollIntervalSeconds, repoApiPath, advisoryIdFromUrl, GHSA_RE, notificationHtmlUrl, toNotificationRecord — pure parsing for the GitHub notifications inbox: gh api --include output and thread records, with links rebuilt only onto the account's own GitHub host.
githubNotificationPullRequest.js notificationPullRequestTarget, notificationPullRequestView — same-host PR targets and the inbox action eligibility projection; mutations always re-read the forge.
githubNotificationTriage.js TRIAGE_DECISIONS, TRUST_LEVELS, MASS_MENTION_THRESHOLD, computeThreadTrust, spamSignals, parseCiBranch, decideThread, ASSIST_VERDICTS, decisionFromVerdict, learnedDecisionForAction, applyLearnedRule, assistAction, selectNotificationProvider, notificationAgentAccountBinding, agentHandoff, autopilotHandoff, agentRuleScope, agentRunPin, GENERIC_AGENT_LANE, APP_FREE_AGENT_LANES, AGENT_RULE_KINDS, AGENT_RULE_ACTIONS, GENERIC_RULE_KINDS, threadAgentKind, KIND_SQL, normalizeAgentRules, ruleAction, ruleActionScope, PINNED_TRIAGE_RULES — the GitHub inbox's fixed trust, spam and routing rules plus Assist's verdict enum, learned rules, allowed actions and Private-account provider allow-list, plus agent lanes (with the generic notification-resolve lane's trust gate), per-repo automation rules (kind × agent/done/mute/leave, legacy agent booleans read as actions) and run-pin precedence; trust comes only from accounts, repo ownership and forge permissions, never from content.
gitRemote.js getOriginInfo, classifyOriginRemote, parseGitRemoteUrl, readRemoteUrl, isUpstreamOwner, isUpstreamFullName, UPSTREAM_OWNER/UPSTREAM_REPO — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks.
gitRepositoryIdentity.js readGitCommonDirectory(repoPath) — fresh canonical Git common-directory identity for repository-scoped ownership; aliases and linked worktrees share identity, independent clones do not, and unreadable evidence returns null.
gitStaleLock.js gitLockPathFromError, isStaleGitLock, clearStaleGitLock, clearStaleGitLocksIn, STALE_GIT_LOCK_MIN_AGE_MS — recognizes the *.lock a KILLED git process left behind and removes it so the caller can retry. A lock under .git/modules/<submodule>/ is shared by every worktree of the repo, so one dead process wedges submodule checkout install-wide with a bogus "another git process is running". Removal requires a .lock path under a .git directory (so a malformed message cannot aim the unlink at yarn.lock) that is older than 30 minutes — 3x the longest git command PortOS runs (worktreeManager.WORKTREE_ADD_TIMEOUT_MS, pinned by a test), which is what keeps it from deleting a LIVE competitor's lock. The threshold is deliberately not a parameter. clearStaleGitLock(message) is the reactive form, wired into services/gitSubmodules.js#updateSubmodule and worktreeManager.addWorktreeWithRetry; clearStaleGitLocksIn(gitDir) sweeps ahead of update.sh/update.ps1, the most likely producer. scripts/doctor.js reports one as the blocker.
repoLinkFields.js deriveRepoLinkFields(url) / normalizeRepoLinkFields(link) / linkIsRepo(link) / repoLinkLabel(link) — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host isGitHubRepo field names readable across federated peers.
repoUrl.js parseRepoUrl(url) → { host, provider, owner, repo } / isRepoUrl(url) / repoCloneUrl(parsed) / repoBrowseUrl(parsed) / parseGitHubUrl(url) / isGitHubRepoUrl(url) — authoritative "is this a clonable repo URL?" rule, with per-host behavior (subgroup nesting, clone layout) in the REPO_HOSTS table. Re-exported by client/src/lib/repoUrl.js so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone.
glabArgs.js GLAB_JSON_ARGS, withGlabJson(args) — pure glab argv conventions. The JSON output flag is --output json, NOT -F json: on glab issue list (and only there) -F is --output-format (details/ids/urls), so -F json is accepted, ignored, and answers with the human table at exit 0. Shared by all three glab runners so the spelling has one definition; guarded tree-wide by services/gitlab.glabFlags.test.js.
killWithEscalation.js killWithEscalation(proc, {label, stillRunning, delayMs=8000}) — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after delayMs only when stillRunning() holds and the child hasn't exited (exitCode===null && signalCode===null). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths.
npmGlobalBin.js adoptNpmGlobalBinDir() — puts the directory npm install --global actually writes to onto process.env.PATH, from one cached npm prefix -g. npm resolves its prefix through a config cascade (cli flags, npm_config_*, project/user/global npmrc, a builtin npmrc that interpolates env vars), so guessing it from %APPDATA%/$HOME reproduces the bug on the next host — only npm can answer. Exists because a host whose npm prefix is NOT the directory its Node installer put on PATH (a machine-wide Windows prefix vs the per-user %APPDATA%\npm default, NPM_CONFIG_PREFIX, nvm/Volta) installed codex successfully and then reported it unrunnable, advising a restart that inherits the same PATH. Called at boot in BOTH processes that spawn provider CLIs (services/bootstrap.js, cos-runner/index.js) and again from providerRuntimeInstaller.js's probe, because on a first install the prefix directory did not exist when boot looked.
processEnv.js withoutServerSecretsEnv(env, { keep }) / serverSecretEnvKeys(env) — copy of an env minus the vault key, PG*, PortOS tokens and provider credentials, for non-AI-CLI children (managed apps, deploy scripts, third-party installs); keep exempts names a child needs by design. stripDebugMallocEnv(env) / safeChildProcessEnv(extra) — drop macOS Malloc* debug env vars before spawning a child. safeChildProcessOptions(options) adds that sanitized environment plus windowsHide: true, preventing detached PM2 subprocesses from opening transient Windows console UI; buildSafeCliBaseEnv(env, provider) allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also whichFirst(name) — first-hit which/where PATH probe (safe options, 5s timeout, direct PATH fallback on probe failure) returning the absolute binary path or null; whichFirstSync(name) provides the same contract without the await; findCommandOnPath(name, { env, cwd }) resolves an executable from the exact child environment without needing which itself on that PATH. adoptPathDirs(dirs) appends the ones that exist and are not already there to THIS process's process.env.PATH (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from process.env — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by npmGlobalBin.js and services/llamaServerManager.js's winget-shim adoption. windowsPowerShell51Path(env) is the fixed Windows PowerShell 5.1 location under SystemRoot, shared by interactiveShellResolver.js and nativeTrash.js.
branchUpstreamGuard.js enforceSafeBranchUpstream(repo, branch) / readBranchUpstream / isSafeBranchUpstream — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never refs/heads/main. git worktree add -b <b> <path> origin/main does not leave the branch untracked — branch.autoSetupMerge records merge=refs/heads/main — and /do:pr derives its push destination from that config (git push <remote> HEAD:<merge>), so the agent's work lands straight on the default branch with no PR. Prevention is --no-track at the worktreeManager.js creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: readBranchUpstream returns null for could-not-read (distinct from '' = genuinely unset), and an unverifiable upstream is refused rather than waved through — worktreeManager.js undoes the worktree add on refusal so the throw can't strand a tree. Pairs with primaryCheckoutGuard.js, which catches the other way agent work reaches main.
primaryCheckoutGuard.js capturePrimaryCheckoutState(path) / detectPrimaryCheckoutDrift(baseline, {agentBranch}) + PRIMARY_CHECKOUT_MUTATED_REASON/_CATEGORY — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (agentLifecycle.js) and re-reads it in the shared finalize path (agentFinalization.js), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the git reset --hard recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. resolveRemoteDefaultRef(path) resolves local origin/HEAD, origin/main, then origin/master to {ref, sha} or null without fetching; also used by run-window diffs.
ptySpawnDiagnostics.js diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe}) + probePtyRuntime(pty, cwd) and the PTY_UNAVAILABLE_PREFIX / PTY_WORKSPACE_MISSING_PREFIX markers — turns node-pty’s one opaque posix_spawn failed: No such file or directory into a named fault. The executable is already cleared upstream (PATH resolve + --version probe), so a throw is either a cwd that vanished (cheap existsSync) or a PTY layer that cannot fork AT ALL — proven by re-forking a known-good command in a known-good directory; diagnosed: false means neither matched, and the caller re-throws rather than inventing a cause. Retry policy is the caller’s and the two faults differ: agentTuiSpawning.js matches only the PTY-layer prefix, mapping it to the actionable runner-pty-unavailable so the task blocks once with the repair, while a reaped workspace falls through to the retrying spawn-rejected because the next attempt provisions a fresh worktree. The motivating outage: an npm ci inside a CoS worktree emptied the primary checkout’s server/node_modules through a symlink, deleting the spawn-helper binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy.
pythonSetup.js Python venv / runner setup helpers.
vttTranscript.js WebVTT/SRT → readable prose. vttToPlainText(vtt) (paragraph-joined transcript), vttToLines(vtt) (cleaned caption lines), cleanCaptionLine(line). Collapses YouTube auto-captions' rolling repetition and strips inline <c>/timestamp markup. Used by the brain YouTube ingest.
youtubeIngestFormat.js Pure data transformations for the brain's YouTube ingest (#6015): parseVideoMetadata(json) (yt-dlp --dump-single-json → the stored metadata shape, incl. the subtitles-vs-automatic_captions manual-caption signal), buildIngestNote({meta,url,transcript,tags,agentPrompt,capturedAt}) (the Obsidian note, whose YAML frontmatter the user's own vault queries key on — every interpolated scalar goes through yamlString), buildAgentTaskContext(...) (the CoS follow-up prompt, including the untrusted-transcript boundary notice), resolveObsidianPointer({written,vaultId,notePath,prior}) (keeps the prior note pointer when an ATTEMPTED mirror failed, so an evicted note can't be orphaned — #3706), plus sanitizeFilename, formatDuration (seconds → h:mm:ss) and yamlString; and the ingest-history cursor pagination (#8267): compareIngestsDesc(a,b) (newest-first order, ingestedAt desc with videoId desc as a deterministic tie-breaker), decodeIngestCursor(cursor) (opaque base64url sort-key token; returns null rather than throwing on anything malformed), and paginateIngests(sorted, {limit, cursor}) (slices a page starting strictly after the decoded cursor and mints the opaque nextCursor for the last row returned, so records added/removed elsewhere in the index between pages can't repeat or skip a row). No fs/db/childProcess/SSE imports; orchestration and storage stay in services/youtubeIngest.js. Surfaced through the barrel as a NAMESPACE export (youtubeIngestFormat.*) because formatDuration collides with fileCore.js and sanitizeFilename with mimeTypes.js.
youtubeUrl.js Canonical YouTube single-video URL rule (#6014). YOUTUBE_VIDEO_URL_RE (accepts watch/shorts/live/embed plus the www./m./music. hosts, rejects playlists, channels, and /@handle feeds), youtubeVideoIdFromUrl(url) (alias youtubeVideoId), isYoutubeVideoUrl(url), and the shared YOUTUBE_URL_INVALID_MESSAGE. Single source for the brain ingest, the Takeout importer, the history scrape, the Music Video track import, and (by re-export) client/src/lib/youtubeUrl.js. A pure leaf — the throwing form lives in youtubeUrlAssert.js, so importing this can never drag errorHandler.js into the browser bundle.
youtubeUrlAssert.js assertYoutubeVideoUrl(url) — the throwing form of the youtubeUrl.js rule: returns the video id, else throws 400 YOUTUBE_URL_INVALID. Separate because it needs ServerError (and so Node's events), which must stay out of the pure leaf the client re-exports.
ytdlp.js findYtDlp() — cached discovery of the yt-dlp binary on PATH, mirrors findFfmpeg() in ffmpeg.js. Used by the track YouTube-import job. resetYtDlpCache() drops that cache after an in-place update or a fresh install, so neither needs a server restart to take effect.

Networking

Module Purpose
httpClient.js Fetch-based HTTP client factory (axios.create replacement). insecureFetch size-cap rejections carry code: RESPONSE_TOO_LARGE.
abortTimeout.js awaitWithAbort(promise, signal) cancels a caller's wait while owning eventual rejection of shared preparation; withAbortTimeout(timeoutMs, fn) — runs fn(signal) under an AbortController that aborts after timeoutMs and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent peerFetch (so can't use fetchWithTimeout) or one signal across parallel fetches.
fetchWithTimeout.js fetch wrapper with AbortController timeout.
tailnetPeer.js isTailnetPeer(peer) — fail-closed security predicate for "is this peer reachable only over the tailnet". Deliberately separate from instances.js's peerRequiresTailscale() probe-deferral heuristic so a polling-noise tweak can't widen a privacy boundary; required by the unattended-routing gate in ADR 2026-08-20-federated-visual-prompts.
federatedMediaRequest.js Builds and validates the versioned federated-media submission body for a visual kind, so every call site that persists a remote-job marker projects local params onto the wire identically.
federatedMediaWire.js Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). FEDERATED_MEDIA_FEATURES + federatedMediaSupports(status, feature, capability) answer "does the peer BUILD speak this wire feature" from the status-root features list — the one place the "absent reads as the wire-v1 baseline" rule lives; a published list wins outright, with the inputAssets capability block retained as its only legacy overlap tell because it is genuinely per-model. federatedMediaDeclaresFeatures(status) and federatedMediaDeniesFeature(status, feature, capability) separate "positively denied" from "could not establish" for MESSAGE selection only — both gate identically, and which missing signal indicts the peer’s build is recorded per feature rather than at each call site.
connectivity.js isMachineOnline({timeoutMs?, hosts?}) — internet-reachability probe: bare TCP connect to public anycast resolvers on :443 (no DNS, no HTTP), resolves true on the first connect and false only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. Also isPortReachable({host?, port, timeoutMs?}) — the same connect primitive aimed at ONE address, for "is anything listening there yet?"; use it rather than a bind probe whenever another process is expected to own the port, since a bind probe can win the race and kill that process with EADDRINUSE.
safeUrlFetch.js SSRF-guarded public-URL fetch: isPublicHttpUrlSafe/assertPublicHttpUrl (scheme + blocked-host-literal via catalogValidation.isBlockedIngestHost + DNS-resolve), exported strict isPrivateAddress, plus fetchPublicText/fetchPublicBinary/fetchPublicResponse (status-preserving raw Response) (timeout, redirect revalidation, size cap), and resolvePublicUrl (bounded, pinned short-link resolution with an optional hop allow-list) and buildPinnedLookup/buildPinnedDispatcher (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. Also readBodyCapped(response, maxBytes) bounds streamed bodies without choosing a network policy.
pinterestFeed.js Pure Pinterest board RSS helpers: isPinterestHost(host) (explicit domain allow-list) + normalizePinterestFeedUrl(input) (board URL or .rss → { feedUrl, boardUrl }, host/path-gated) + parsePinterestRss(xml) (per-pin pinUrl/imageUrl/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer.
xPostMedia.js Pure x.com/twitter.com post helpers: parseXPostUrl(input) (post URL → { statusId, canonicalUrl }, host-gated) + buildSyndicationUrl/syndicationToken (Twitter's public unauthenticated tweet-syndication endpoint) + extractXPostMedia(json) (→ { images, video }). Feeds the mood-board X post importer.
requestAbort.js abortSignalFromResponse(res) — AbortSignal that fires only when an Express client disconnects before the response finishes (keyed off res close + writableEnded). Plus anyAbortSignal(signals) — combine several signals into one (native AbortSignal.any with a Node-18 fallback).
readResponseJson.js Read a Response body as JSON, tolerating a non-JSON/HTML error page (no Unexpected token < crash). Object callers need no opts; pass { fallback, emptyValue } for arrays or to surface the raw error text.
peerHttpClient.js Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); attaches the peer credential (derivePeerAuthToken pair token, legacy Basic until the receiver confirms it); readPeerBody(response, method, { idleTimeoutMs?, maxBytes? }) bounds native response body stalls (PEER_BODY_IDLE_TIMEOUT) and streamed size (default PEER_BODY_DEFAULT_MAX_BYTES = 256 MiB, rejects with RESPONSE_TOO_LARGE like the HTTPS shim).
peerProbeDiagnostics.js Classify federated peer probe failures (local_refused / tunnel_dial / probe_http / timeout / auth / DNS) so Instances UI and logs can tell a dead local forward from a tunnel dial miss from a PortOS health-details failure; messages stay redacted (no full tc… capabilities).
peerSelfHost.js Tailscale-issued hostname this PortOS sends in federation.
peerUrl.js Build the base URL for a peer.
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; the one definition shared by the park log line, the on-demand toast, and the work-item picker. Re-exported at client/src/lib/perpetualSkipCauses.js.
sharingOrigin.js Origin metadata for records imported from share buckets.
syncIntegrity.js Pure diff of local vs remote manifest lists. INTEGRITY_STATUS constants + computeRecordIntegrity(localList, remoteList) — classifies each record as in-parity, local-only, peer-only, diverged, or assets-missing. No I/O.
syncWire.js Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree).
tailscale.js Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build, and return a normalized backend/MagicDNS/peer snapshot (getTailscaleStatus / isTailscaleUp).
tailcatAddress.js Pure Tailcat capability validation and redaction: isValidTcAddress, redactTcAddress, redactTailcatDiagnostics.
tailcatVersion.js Tailcat CLI version floor for managed install/detect: MIN_TAILCAT_VERSION (0.6.0 — PSK on by default in modern serve), parseTailcatVersion (handles the CLI's v0.6.0 banner that parseHarnessVersion cannot), isTailcatVersionAtLeast, and tailcatVersionTooOldMessage for operator-facing upgrade guidance. Consumed by services/tailcatPeer.js so Dial-them and They-dial-us refuse ≤0.5.x rather than silently timing out on TCP.
httpsState.js Captures whether PortOS booted with HTTPS active.
bareUrl.js parseBareUrl(text) — returns the normalized URL when a captured string is nothing but a URL (bare host gets https://), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's urlNormalize.js isUrl (needs a plausible TLD; http/https/git@ only) because it picks a storage destination rather than a hint.
beatGrid.js Beat grid measurement for library music tracks (#8958): getBeatGrid(absoluteAudioPath) decodes via ffmpeg and returns { bpm, beats, downbeats, hits } | null, cached in memory per (path, mtime) so repeated calls against the same track don't re-decode. The DSP core (decode, onset envelope, tempo incl. windowed fallback, beat/downbeat fitting) comes from audioBeatDsp.js; this module adds onset "hit" peak-picking and the per-file cache, and re-exports decodeAudioToPcm for direct testing. It is unit-tested directly against a synthetic click track via the __analyzeBeatGridPcm test seam (no production caller needs raw-PCM access; every real caller goes through getBeatGrid).
beeperAttachmentPaths.js Layout rules for the Beeper attachment byte mirror (#37): BEEPER_ATTACHMENT_MAX_BYTES (32 MiB, matching FEDERATED_MEDIA_ASSET_MAX_BYTES — a constant, not a setting), attachmentExtension({ mimeType, fileName }), attachmentRelativePath(sha256, ext) (<sha256[0..2]>/<sha256>.<ext>, null for anything that is not a 64-hex digest) and isSafeAttachmentRelativePath(p). Content-addressed, so one forwarded photo is one file and every delete path owes a reference check first; the extension is cosmetic because GET /v1/assets/serve sends no Content-Type and the mirror serves from the stored mimeType instead.
beeperOAuthOrigin.js Which origin the Beeper OAuth redirect_uri is built from: parseBrowserOrigin (a bare http(s)://host[:port], else null), hostnameOf, isLoopbackHostname (the loopback-spelling predicate reused by the settings.beeper.baseUrl gate and the OAuth token-endpoint host pin), and resolveOAuthOrigin({ clientOrigin, requestOrigin, configuredOrigins }) → { origin, source, rejectedClientOrigin }. The browser sends window.location.origin because the request-derived origin is the API's own under the Vite dev proxy (changeOrigin, no x-forwarded-*), which sends the consent redirect to a host the TLS cert does not cover; the value is untrusted, so it is accepted only for a loopback host, the request's own host, or a configured PORTOS_UI_URL/PORTOS_API_URL host — port unpinned, since UI and API are different ports of one install. Rejection falls back to the request origin. Pure.
isSafeHref.js Pure http(s)-only scheme check (isSafeHref) for user-supplied URL fields that get rendered as a clickable <a href> — rejects javascript:/data:/etc. stored-XSS payloads. client/src/lib/isSafeHref.js re-exports it, and client/src/utils/urlNormalize.js re-exports that as isHttpUrl.
networkExposure.js Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI; localApiBaseUrl() resolves the plain-HTTP loopback origin (mirror port under HTTPS, API port otherwise) for local scripts and agent-facing curl snippets.
protobufWire.js Dependency-free protobuf wire codec over a small declarative schema (encodeMessage / decodeMessage): varint (64-bit two's complement), bool, string, bytes, nested/recursive message, double; repeated + packed; unknown fields skipped; truncated input throws code: PROTOBUF_WIRE_ERROR.
itermMessages.js PortOS-authored (clean-room, no vendored api.proto) schemas for the iTerm2 API subset the Shell page's iTerm2 view uses — list sessions, notifications, get buffer, send text, variables — plus encode/decodeItermClientMessage, encode/decodeItermServerMessage and flattenItermLayout (window → tab → pane order).
itermScreenRender.js renderItermFrame({ lines, cursor, firstVisibleLine, cols, rows }) — one iTerm2 screen snapshot → an in-place ANSI repaint (SGR truecolor/palette/attributes, code-point cell runs for wide chars, scrollback cursor offset, control chars neutralized); itermStyleToSgr.

Search & indexing

Module Purpose
bm25.js BM25 ranking + inverted-index helpers.
vectorMath.js Vector math utilities (cosine, etc.).
memoryLinkTypes.js Closed vocabulary for CoS memory links (MEMORY_LINK_TYPES: related symmetric, supersedes / contradicts / derived-from / applies-to directed), DEFAULT_MEMORY_LINK_TYPE, isSymmetricMemoryLinkType.
memoryQuery.js Pure memory-index helpers: meta projection, filter/sort, search/hybrid meta filters, RRF fusion.
memoryStats.js macOS-correct memory accounting (handles "Pages free" quirk).
rrfRanking.js Pure reciprocalRankFusion(textResults, vectorResults, options) — merges two ranked lists via RRF scoring (Cormack 2009). Used by catalogDB.hybridSearchIngredients.

Extraction & parsing

Module Purpose
clientApiPaths.js Static scan of the paths client/src/services/api*.js requests, for the client↔server route-parity guard (apiRouteParity.test.js). `scanClientApiPaths({ repoRoot
htmlToText.js Shared HTML → plain-text converter. htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? }) — strips script/style/head/noscript blocks, converts <br>/block closes to newlines, strips remaining tags, decodes entities via decodeXmlEntities, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: paragraphBreak: '\n\n' + collapseSpaces; SongBook import: defaults — space runs preserved for tab alignment).
jsonExtract.js Pull JSON blocks out of LLM responses. extractNonPlaceholderJson(raw, { field }) skips echoed schema placeholders and distinguishes placeholder-only from parse failures. findBalancedBlocks walks top-level blocks and stops at the first unbalanced one; findAllBalancedBlocks is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first).
streamJsonParser.js Stream-JSON parser for Claude CLI --output-format stream-json. createStreamJsonParser() returns a stateful parser with processChunk/flush/getFinalResult that extracts human-readable lines from streaming NDJSON events (text deltas, tool-use markers, tool input summaries, intermediate assistant results). Also exports summarizeToolInput(toolName, input) for concise tool-call descriptions and safeParse(str) as a plain JSON.parse try/catch. Shared by cos-runner/index.js and services/agentCliSpawning.js.
taskParser.js Parse and generate the Markdown task format (a task's stored form, and the input of db-migration 018), and own the vocabularies it can represent: TASK_STATUS_VALUES / TASK_PRIORITY_VALUES (derived from STATUS_MAP / PRIORITY_VALUES, read by cosValidation.js and peerSyncValidation.js so the HTTP and wire enums cannot drift from the store), plus UNKNOWN_STATUS_BLOCKED_CATEGORY — the marker generateTasksMarkdown stamps when it REPAIRS an unrepresentable task instead of dropping its row (#7239).
taskGenerationOverrides.js applyTaskGenerationOverrides(provider, metadata) — the per-RUN temperature / thinking / effort a task form or schedule entry pins, layered onto a COPY of the provider record (the saved record is shared by every other run; the child-env composer turns the copy into OpenCode’s dynamic agent.build config downstream). Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings — so each override applies only when it validates, and an empty temperature field is absent rather than 0, which would otherwise pin greedy decoding on a task whose author just cleared the box.
cosTaskPrompt.js The CoS task prompt/note split (#4153) — metadata.prompt is the full agent-facing payload, metadata.context the one-line human note. isPromptPayload(value) is the single discriminator (a newline means it's a prompt, not a note), shared by the store's write path and the on-disk migration so they can't classify the same task differently. getTaskPrompt(task) prefers metadata.prompt and falls back to a legacy metadata.context; getTaskContextNote(task) returns the note only on an already-split task; taskContextBlock(task) renders both as one block so prompt templates (including customized ones) never see the split; splitTaskPromptFields(metadata) routes a multi-line context to prompt at CREATE time only. Pure, dependency-free.
cosTaskRows.js Row model for the cos_tasks queues: the stored form of a task (the old Markdown round-trip's normalization), the recent-completed working-set rule, fractional queue position assignment, and planListSave (turn "the whole list changed" into "only these rows changed"). Shared by the Postgres and in-memory repository backends so they cannot drift
cosAgentRows.js Row model for cos_agents, the CoS agent working set: agentRowColumns(agent) (the task/status/start/completion/pid projections the queries read) and planAgentSave({ persisted, next, changedAgentIds }) (turn "the whole agents map" into "only these rows changed" by comparing each record's JSON text with the one last stored, serializing only dirty/added records when hinted). Shared by cosState.saveState and the repository backends
taskPauseHold.js The user-PAUSE hold — pure metadata helpers shared by the writer (pauseAgent), the reader (resumeAgent), and the clearer (updateTask). AGENT_PAUSED_CATEGORY is the blockedCategory a pause stamps; PAUSE_METADATA_KEYS names every key it writes; pauseMetadata({agentId, pausedAt, workspacePath, runId}) arms it and clearedPauseMetadata() releases it (undefined-valued, so updateTask deletes rather than serializing "null"); isAgentPausedTask(task) / isResumablePausedTask(task, agentId) answer whether a pause is still live and whether it is THIS agent's. updateTask clears the whole set whenever the task leaves blocked, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. Also carries the cycle-safe RELEASE adapter (#3730) agentManagement.js registers at load — resolvePausedTaskResume(task) hands updateTask the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and retirePausedAgent(agentId, taskId, branchName) retires the paused record after it.
taskBlockCategories.js The blockedCategory vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. PAUSED_BLOCKED_CATEGORIES (paused until something outside the task changes — keeps the resume pointer), USER_DECISION_BLOCKED_CATEGORIES (user intent / open decision — the reaper's exemption), NON_AUTO_RETRY_BLOCK_CATEGORIES (their union — a completed investigation must never revive these), TIMED_COOLDOWN_BLOCKED_CATEGORIES (a timer clears these — the cooldown sweeper revives them, so block reporters stay quiet), PROVIDER_CONFIG_BLOCKED_CATEGORY (the shared literal the agent-spawn stamp site uses, so the stamp cannot drift from the two sets it belongs to). Pure.
taskRequeue.js The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (in_progress → pending, performed by the orphan sweep and the retry-hold release). REQUEUED_AT_KEY / LAST_SPAWNED_AT_KEY name the two stamps; isPostSpawnRequeue(pendingTask, inProgressTask) answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale pending copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank.
taskRetryHold.js The failed-task RETRY HOLD and delivery-cleanup ownership state (#3373, #13430) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, the orphan sweep, and completed-agent deletion guards. retryHoldMetadata(agentId, now) arms it (task stays in_progress, so no dequeue tier can claim the retry before its resume pointer is resolved); clearedRetryHoldMetadata() releases it in the same write that flips the task to pending; isRetryHeld(metadata) / isRetryHoldOwner(metadata, agentId) gate the spawn and the owner-scoped release; isStaleRetryHold(metadata, now, graceMs) + RETRY_HOLD_GRACE_MS let the orphan sweep finish a transition whose process died; isDeliveryCleanupHeld(metadata) / collectProtectedCleanupOwners(tasks) identify active delivery-cleanup and retry-cleanup owners across in_progress tasks so single deletion and bulk completed-agent clearing retain live recovery evidence.
taskStatusTransition.js The CoS task STATUS TRANSITION vocabulary (#6620) — resolveTaskStatusTransition(previousStatus, nextStatus) classifies one update's status pair ONCE and returns { action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }, so writeTaskUpdate's blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted tasks:changed action all read one answer instead of re-deriving seven. A falsy nextStatus means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. isTerminalTaskStatus(status) is the shared completed/blocked predicate cosTaskStore and cosTaskMerge both read. Pure — metadata predicates (is this block a pause?) stay at the application site.
taskTargetBranch.js Pure task-branch contract: resolveTaskTargetBranch(metadata) reads a retry's legacy existingBranch or a review-loop follow-up's canonical reviewLoopPRBranch; shouldStripTaskTargetBranch(metadata) identifies only retry-owned pointers for terminal cleanup.
claimContinuation.js Claim-flow relaunch pointer. claimContinuationBranch(claimTarget) is the claim/issue-<n> or claim/<key> branch a pinned target checks out. claimContinuationPointer(...) names the claim-* worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). claimContinuationWorkspace(...) turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. reconcileAssignmentForTask, reconcileAssignedTarget, and reconcileMergeTarget preserve scheduler assignments and match their registered/live branch, checkout, and completion policy for reconciliation admission; claimOwnershipBinding(task) is the branch (or "picks its own", for a swarm orchestrator; a pinned run is also "still choosing" until it binds) a claim run registers on its agent record; bindClaimBranch / releaseClaimBranch patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), ownsClaimBranch(agent, branch) is explicit registered/bound ownership only (never a picker's "may pick"), claimCheckoutOwnerReason(...) names a live/possible claim owner for branch-reconcile (claimCheckoutOwner(...) adds the holder run ids a blocked cleanup records), and claimBranchAdmission(...) gates coordinator adoption and detach with the same branch/repository owners; claimContinuationAdmission(...) is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends).
scheduledTaskTypes.js Registered scheduled task names (SELF_IMPROVEMENT_TASK_TYPES), shared by schedule configuration and authoritative skill routing; plus the retired-name map (TASK_TYPE_RENAMES, currentTaskTypeName, taskExecutionKey) for tasks and records written before a task rename.
taskTypeBucket.js CoS task-learning bucket classifier (extractTaskType, classifyUntypedTask, isSandboxedTaskType); browser-safe, shared with the client ETA lookup via client/src/lib/cosTaskType.js.
taskTypeRenames.js Dependency-free retired-task-name map (TASK_TYPE_RENAMES, currentTaskTypeName); re-exported by scheduledTaskTypes.js.
scheduleExecutionFieldsValidation.js scheduleExecutionFieldsSchema validates optional prompt and provider/model selections before schedule writes, preserving null/empty clears.
scheduleRunOrder.js Storage rules for a task's advisory suggestedAfter list — which OTHER scheduled tasks to run first. normalizeSuggestedAfter drops blanks, duplicates and self-references and caps at SUGGESTED_AFTER_MAX; the shipped order it defaults to is auditCatalog.AUDIT_SUGGESTED_AFTER, layered at read time in getScheduleStatus. Advisory only — the ENFORCED dependency field is runAfter. Pure — no I/O.
taskReadinessReasons.js Stable scheduled-task readiness reason codes, membership set, shared by the server and Schedule UI (pure browser-safe leaf).
taskTargetScope.js Target scope for a scheduled task type: INSTALL_WIDE_TASK_TYPES, MANAGED_APP_TARGET_TASK_TYPES, PROGRAMMATIC_SCHEDULED_TASK_TYPES, isProgrammaticScheduledTaskType, requiresManagedAppTarget, requiresInstallWideTarget. Declared here (not in services/taskScheduleRegistry.js, which re-exports it) so quotaBurnValidation.js can reject a burn reference with the wrong target scope without importing upward into services.
taxonomyTally.js Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (services/layeredIntelligenceRejections.js, layeredIntelligenceExecutionFailures.js). createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording}) is the single composed seam — it binds a taxonomy config into {summarize, format}, where summarize(records) yields the three-bucket {entries, unknown, unclassified, diagnosed, total} tally (commonest-first + taxonomy-order tie-break) and format(records, limit) renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: normalizeToken(value) (lowercase + separator-collapse for label/category matching) and formatTaxonomyToken(token, labels) (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph.
appPromptPlaceholders.js applyAppPlaceholders(text, app) — expand {appName} / {repoPath} / {appId} / {appSlug} in a CoS prompt template. The ONE owner of that chain: four renderers (cosTaskGenerator.js's claim-work router and JIRA per-ticket builder, cosTaskPreStepBlocks.js's scheduled builder, referenceRepos.js) each used to spell it themselves and drifted. Function-form replacers throughout, since a name/path/id is free text a $ can appear in. Callers expand their own injected blocks ({trackerInstructions}, {modeInstructions}) FIRST — those blocks carry app placeholders of their own. Pure.
worktreeNodeModules.js Workspace-aware node_modules provisioning for a worktree (#12633). provisionWorkspaceNodeModules(sourceRoot, worktreeRoot) builds a real node_modules directory when the source's holds workspace links (@scope/pkg -> ../../packages/pkg): every entry is symlinked back to the source except those links, which are recreated so they resolve INSIDE the worktree (a plain directory symlink resolves them against the source checkout, so a worktree ahead of the source's branch silently tests stale workspace code). Returns false and creates nothing when there are no workspace links. Every recreated link is checked to resolve inside the worktree, else provisioning fails; removeProvisionedNodeModules undoes the farm and only touches a directory carrying WORKTREE_NODE_MODULES_MARKER, so a real npm install is never mistaken for it. Consumed by services/worktreeManager.js#linkWorktreeDependencies.
worktreeOwnership.js Pure ownership gate for destructive worktree operations. worktreeOwnershipReason() applies root, agent-id, lock, active-agent, liveness and claim policies IN THAT ORDER, so an unconditional hold always outranks a claim and callers never re-derive the precedence from the slug; the claim hold has two opt-outs (allowStaleClaim for reapers, allowLiveClaim for the dispatch side). knownAgentIds() is the one live-agent sentinel: a Set (even empty) is authoritative, anything else is unknown liveness and must never be coerced to an empty Set. worktreeAgentId() is separator-safe; isHumanClaimWorktree() and isAgentWorktreeId() make the protected namespaces explicit; worktreeHoldExpiresAt() names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. appWorktreeSlug(app) is the per-app segment (<name-slug>-<8 id chars>) that claim prompts render INSIDE the claim- prefix — data/cos/worktrees/ is one directory shared by every managed app, so a work-item-only name collides whenever two apps carry the same issue number or PLAN slug.
xmlEntities.js Shared dependency-free XML/HTML entity decoder. decodeXmlEntities(str, extraEntities?) — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. { nbsp: ' ', zwnj: '' }). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text.

Curated static data

Module Purpose
curatedGenomeMarkers.js SNP classification logic (classifyGenotype, formatGenotype, resolveApoeHaplotype) + MARKER_CATEGORIES; loads the ~116-marker dataset from the co-located curatedGenomeMarkers.json at module init.
songCraftParts.js Pure shared rhythm-shape, voice-layer, and harmony-part vocabulary used by AI prompts, browser pickers, and bundled scores.
songCraftRef.js Shared song vocabulary re-exports plus derived dirge and derivable-harmony subsets for AI prompts and bundled scores.

Domain utilities

Module Purpose
appIdentity.js The baseline managed-app id (PORTOS_APP_ID) — importable without pulling in the services/apps.js graph (pm2, scheduler, settings) behind it. Re-exported by apps.js.
appResolver.js Fuzzy-match a spoken/typed phrase to a managed app ({ id, name }). Tiered exact → prefix → substring, used by voice tools that target a specific app.
autonomousJobIntervals.js Autonomous-job cadence vocabulary (pure). INTERVAL_OPTIONS (picker rows, ms: null for a cadence with no recurrence), ON_DEMAND_INTERVAL, JOB_INTERVAL_VALUES (every legal stored cadence, incl. custom), resolveIntervalMs(interval, customMs) → ms or null (the no-interval sentinel — never falls through to DAY), and isOnDemandJob(job) for the three due/next-fire implementations. Lives here so cosValidation.js can validate the cadence without a lib → services import; services/autonomousJobs/constants.js re-exports it. Separate vocabulary from the scheduled-CoS-task INTERVAL_TYPES.
jobFormFields.js A scheduled agent job's own configuration form (pure). JOB_FORM_FIELD_TYPES (text/textarea/number/select/checkbox), the jobFormFieldsSchema / jobFormValuesSchema pair Zod-validates the job payload against, and the prompt projection formatJobFormValues(fields, values) / appendJobFormValues(job, prompt). Definitions and values are stored separately so re-aiming a job (a new value) is not an edit to its design (a new field), and the projection iterates DEFINITIONS — a value whose field was deleted is inert. A field the user left blank is omitted rather than passed as an empty line, but a false checkbox is a real answer and is kept. Consumed by services/autonomousJobs/skillTemplates.js; the values reach the agent as the prompt's ## Run configuration section. describeReaimedValues(fields, saved, run) names the values a manual run changed, as the one-line description suffix that keeps a re-aimed run from colliding with a differently-aimed twin in addTask's first-line dedupe.
capabilityMap.js Pure row builders for Setup & Capabilities, including strict network/provider first-run readiness and optional-integration health rollups; fed by routes/capabilities.js.
claimFlowTaskTypes.js hasClaimFlowContract(task) shares trusted claim identity across registration, completion and resume. CLAIM_FLOW_TASK_TYPES — the ONE list of task kinds whose prompts own their own claim/<item> worktree and push/PR/MR/review lifecycle (#6613). services/cosTaskGenerator.js stamps metadata.claimFlow from it (WRITE side); services/agentPromptBuilder.js reads it back through isClaimFlowTask() to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; claimFlowTaskTypes.test.js fails if a local copy reappears. Imports nothing.
chiptuneRender.js Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); renderScoreToPcm / pcmToWavBuffer / renderScoreToWav.
chiptuneScore.js Chiptune score contract (#2911): chiptuneScoreSchema (Zod) + sanitizeChiptuneScore, buildScoreEvents — the pattern/order → absolute-time flatten mirrored by client/src/lib/chiptunePlayback.js.
musicVideoLayers.js Music Video per-scene visual layers (#8985): MUSIC_VIDEO_VISUAL_LAYERS (footage/still/card/code), MUSIC_VIDEO_STILL_MOVES (hold/push/pan), STILL_PUSH_ZOOM / STILL_PAN_TRAVEL (shared render/animatic motion amounts), MUSIC_VIDEO_FRAME_FITS (fill/still/vhs/black: how an off-shape clip fills the frame), sceneVisualLayer(scene, { layered }) (only a composed render honors a still/card), sceneHasAuthoredSpan, and sceneRenderReady(scene, { layered }). clipSpeedRate(scene) / clipOffsetSec(scene) / clipReversed(scene) read a footage shot's hand-set speedFps, offsetFrames and reverse on the 24 fps grid (CLIP_TIMING_FPS, CLIP_SPEED_FPS_RANGE, CLIP_OFFSET_FRAMES_RANGE). Pure leaf shared by services/musicVideo/render.js and the client board (client/src/lib/musicVideoLayers.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.
musicVideoLyricAnchors.js Music Video lyric anchors: cuesSungWithin(cues, startSec, endSec) and sungLyricTextWithin(cues, startSec, endSec) (shot text, capped at 2,000 characters), the lines a shot's span anchors, each counted from its first sung word to its last when it has word timing, else its line window. Shared by the storyboard anchor check and the retime anchor sync.
musicVideoImageEffects.js Music Video image effects: a code-drawn effect a still shot plays instead of a generated clip (imageEffect: flash-develop, a camera flash then the picture develops like an instant photo over imageEffectSec; or a fade, flash or glitch from the start frame to the end frame). sceneImageEffect(scene, { layered }), imageEffectState (the effect at a time into the shot, painted by the storyboard animatic) and musicVideoImageEffectFilter (the same curves as ffmpeg filters for the final render). Browser-safe and import-free: document videos ship it as is.
musicVideoTransitions.js Music Video cut transitions: VHS glitch styles a shot sets on the cut into (transitionIn) or out of (transitionOut) it, transitionGlitchFrames (the glitched frames of a cut timeline, never moving a cut), transitionFrameAt, sceneTransitionSections, imageEffectGlitchFrames/mergeGlitchFrames (end-frame glitch effects in the same shape), shotGlitchFrames/sceneShotGlitchFrames (glitches a shot sets at moments inside it, scene.glitches), blockBox, edgeGlows (an effect's edge glows as fading ramps) and musicVideoTransitionFilter (per-frame ffmpeg filters for the final render). Styles span VHS, film and camera looks. Browser-safe; the storyboard animatic paints the same frames.
pitchMath.js Dependency-free scientific-pitch math shared by the LLM-authored music formats on both runtimes: pitchToMidi("C4") → 60 (null when unparseable) and midiToFreq(69) → 440.
wavAudioFile.js writeWavAudioFile(wav, dir, basename) — land a synthesized WAV Buffer as <basename>.ogg via the system ffmpeg, falling back to <basename>.wav (and dropping a stale .ogg) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers and the code-engine take upload. wavDurationMs(buffer) reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). measureWavAudio(buffer) decodes PCM 16/24/32-bit or float 32/64 (EXTENSIBLE included) into { channels, sampleRate, frames, durationMs, peak, rms, nonFinite } so native renders are judged by their samples (null when undecodable).
superColliderRuntime.js Managed SuperCollider runtime contract (#9412), pure: image/runtime/policy version constants, buildSuperColliderRunArgs (the one contained docker run for untrusted sclang source: no network/caps, read-only root, limits, ro input, private output), buildSuperColliderBuildArgs, the shipped synthetic probe, evaluateSuperColliderStatus (docker-missing … ready, with stale image/evidence invalidation), and the render contract (#9413): SUPERCOLLIDER_RENDER bounds, the trusted NRT SUPERCOLLIDER_RENDER_WRAPPER_SOURCE, classifySuperColliderRenderLog (syntax/source/pattern/score/synthesis failures) and parseDockerContainerList for orphan sweeps. I/O lives in services/superColliderRuntime.js.
waveSketch.js Drawn-waveform music contract v1 (browser-safe; new paintings are v2 — see paintedCanvas.js): the LLM draws single-cycle shapes (point polylines in [-1, 1]) played by voices as timed strokes with optional glide, shape morph, and drawn envelope, plus a whole-piece contour. normalizeWaveSketch(raw) is the one lenient, idempotent validator (null when nothing playable survives); synthesizeWaveSketch(sketch) → deterministic mono PCM (seeded noise), so the client preview and server render match; pcmPeaks(pcm, columns) for drawing it; WAVE_SKETCH_LIMITS. normalizeWaveSketch dispatches a version: 2 sketch to normalizePaintedCanvas; synthesizeSketchChannels(sketch) renders either version to its channel list; isPaintedCanvas(sketch).
paintedCanvas.js Painted-spectrogram canvas, wave sketch v2 (#8464, browser-safe): stereo time × log-frequency canvas painted with strokes (path keyframes {t, hz, a}, per-keyframe overtones, noise width, pan), plus optional sections and tempo grid. normalizePaintedCanvas(raw, { durationSec, limits }) is the lenient idempotent validator; synthesizePaintedCanvas(canvas) → deterministic [left, right] PCM using only IEEE-exact math (series sine table, log2/exp2), so server WAV and browser preview match on any engine; render work bounded by PAINTED_CANVAS_LIMITS.WORK_MAX_PARTIAL_SEC; paintedCanvasStats(canvas) → stroke/keyframe/noise/work totals.
spectrogramImage.js spectrogramPixels(pcm, { sampleRate, width, height, minHz, maxHz }) → raw RGB pixels of a log-frequency STFT spectrogram (80 dB range) — the picture a model gets of its own painted canvas in the review pass (#8464). Pure; the caller encodes the PNG.
civitai.js Civitai URL parsing + API client.
huggingfaceLora.js HuggingFace LoRA import helpers: parse HF ref → {repo,revision,file}, fetch /api/models metadata, select an exact or family-matching .safetensors, detect the image or video LoRA family (flux2 / ltx-video / …), build the sidecar + resolve download URL. The HF analogue of civitai.js. Pure.
huggingfaceModel.js HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the media-models.json entry (source:'user'), + a searchHuggingfaceModels Hub-search helper. Pure.
localLlmCatalog.js Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure.
localPersistentMindRecommendation.js CPU-only / low-RAM Persistent Mind defaults (Grok-box path): recommended Ollama + Qwen2.5 7B instruct profile, model aliases, and host gates so GPU coding-agent presets are not steered here. Pure.
jev.js Pinned local entailment ("jev") contract: the JEV_MODEL descriptor (repo, revision, qwen3.5-4b-nli subfolder, MIT/ungated), the four-file required allowlist, pinned Python packages, JEV_STAGES / jevStageReadiness() for the operator install checklist, the premise/hypothesis bounds, the jevScoreRequestSchema / jevScoreResponseSchema wire pair, normalizeJevScores (rejects a reply describing a different hypothesis list), and decideFromScores — the margin arithmetic that ABSTAINS rather than picking a near-tie. Pure. Lifecycle is services/jev.js; see docs/JEV_SETUP.md.
jevDecisions.js JEV_DECISIONS — the closed-set decisions PortOS may answer with the local scorer instead of a chat completion, each with its frozen hypothesis wording and its abstention floor. getJevDecision / jevHypotheses / jevValueForHypothesis map between an enum value and the hypothesis that stands for it; jevMinMarginFor composes the per-decision floor, the per-OPTION floor (a destructive delete clears a far wider margin than the archive beside it), and the operator setting, which can only RAISE the bar. isValidJevDecision is the contract every shipped descriptor is tested against. source names the ingress CHANNEL and is null for a decision that has none (scope-adherence asks about the operator's own product documents). Pure. Routing, mode resolution and the counts-only agreement store live in services/jevRouter.js.
jevCorpus.js The weakly-labelled training corpus a project-specific jev head is fit on, in open-jev Route A shape ({context, options, label}) so openjev eval stays usable as an independent cross-check. splitCorpus assigns train/gold by the example's own content hash — deterministic across machines and rebuilds — and assertSplitDisjoint REFUSES a split whose halves share a key or whose gold set is too small to separate three numbers. dedupeCorpus drops the duplicate question a goal re-stated across PRD.md and GOALS.md produces, which is contamination arriving through the front door. Also corpusHash (order-independent), majorityClassAccuracy (one of the two adoption baselines) and summarizeCorpusSources. Pure; the forge reads live in services/jevCorpusBuilder.js.
jevHead.js The artifact contract for a project-specific head trained on the FROZEN jev encoder: jevHeadSchema + parseJevHead (shape, chained layer widths, a bounded parameter count so weights stay inspectable JSON), isHeadCompatible (exact encoder-revision equality — a different checkpoint is a different vector space), and THE ADOPTION GATE, headBeatsBaselines / headAdoptionBlocker: a head must beat BOTH the stock zero-shot classifier and the majority class on the held-out gold set, strictly, or it cannot be adopted through any surface. A head emits the checkpoint's own three labels, so every abstention floor downstream is unchanged. Also JEV_HEAD_SLUG and the train/adopt route schemas. Pure; the store is services/jevHeads.js.
jevHeadReasons.js Operator-facing labels for why a trained project head cannot be adopted (jev-head-below-zero-shot, -below-majority-class, -metrics-invalid) plus jevHeadBlockerLabel. No imports at all, so client/src/lib/jevHeadReasons.js re-exports it rather than mirroring it - same contract as scopeAdherenceReasons.js. Coverage is asserted in jevHead.test.js, so a fourth blocker cannot render as a raw slug.
jevPaths.js Where data/jev/ lives: jevDataDir / jevHeadsDir / jevCorporaDir / jevEmbeddingsDir / jevDecisionEmbeddingsDir. One definition, because the head store writes them, services/jev.js passes the heads directory to the sidecar, and services/backup.js excludes two of the three by path. Kept out of the head store so the sidecar lifecycle does not import the head schema merely to spell a directory. Everything under it is machine-local.
prdClauses.js Chops PRD.md / GOALS.md into addressable clauses — one per paragraph, top-level list item, blockquote or table data row — each carrying its heading path, source file and line. Clause ids are <file>#<heading-slug>:<content-hash> with NO line number and NO document ordinal, so a clause keeps its id when an unrelated paragraph is inserted above it. indexClausesById / formatClauseCitation render a verdict back to a citation a human can go read. Pure; the files are read by services/scopeAdherence.js.
scopeAdherence.js The retrieval and premise half of "does this change advance the stated product goal?" — the QUESTION itself is the scope-adherence entry in jevDecisions.js. selectCandidateClauses fuses two BM25 views of the change (prose, changed files) with fuseRankingsRRF, so scoring is bounded by k rather than the whole corpus; buildClauseIndex is exported so a caller can cache the index beside the corpus. formatChangeEvidence builds the change half ONCE — the same string is screened and scored, so the two cannot drift — and composeAdherencePremise puts the clause first and in full. Also the route-input scopeAdherenceRequestSchema. ADVISORY ONLY: nothing here returns a gateable boolean. Pure; the ladder lives in services/scopeAdherence.js.
scopeAdherenceReasons.js Operator-facing labels for the codes scoreAdherence returns instead of a verdict: SCOPE_ADHERENCE_REASONS, SCOPE_ADHERENCE_REASON_FALLBACK, and scopeAdherenceReasonLabel(code, fallback?) (own-property lookup, so a code naming an Object.prototype key cannot render as a function). Re-exported by client/src/lib/scopeAdherenceReasons.js rather than mirrored — a mirror would need a parity test, and that would need the server→client import scripts/server-imports-no-client.test.js forbids. Keep it import-free so it stays bundleable.
pythonRuntimeDiagnosis.js diagnosePythonRuntimeText(text, { subject, repairLabel, imports, fallback }) — maps raw pip/interpreter output onto the fixed operator-facing diagnosis vocabulary (package-missing, certificate-failed, wheel-unavailable, dependency-conflict, disk-full, network-failed), naming the specific pinned import when one is missing. Evidence is matched and DISCARDED: nothing from the subprocess output (tokens, authenticated index URLs, local paths) is ever returned. Shared by the Prompt Guard and jev installers. Pure.
modelAbuseGuard.js Pinned model-abuse boundary contract: Prompt Guard metadata, deterministic abuse signals (hiddenCodePointSummary for invisible/direction-control/C0-C1 code points, invisibleClusterSummary for a dense cluster of the exempt ones, describeEncodedPayload for compressed/opaque blobs — the last scoped to CODE_CONTENT_SOURCES so a private message carrying base64 is not model abuse — plus hidden HTML comments/collapsed markup that address a model), complete classifier-window coverage validation, chunk/timeout limits, fixed dependency versions (MODEL_ABUSE_GUARD_PYTHON_PACKAGES), and MODEL_ABUSE_GUARD_STAGES / modelAbuseGuardStageReadiness for the operator-facing install checklist. Pure.
diffHiddenContentScan.js Pre-LLM gate over a unified diff — scanDiffForHiddenContent(diff) reports invisible/direction-control Unicode (added lines and filenames), dense clusters of the invisible characters the rules otherwise exempt, compressed or opaque encoded payloads, a new symlink that leaves the repository or a new git submodule, a non-media binary patch, and inline script in SVG/HTML/XML, keyed path:line; formatHiddenContentFindings renders them for a CI log. Detectors for the Unicode/encoded rules are shared with modelAbuseGuard.js (same rules, applied to external PR content). Lockfiles skip the encoded rule but never the Unicode ones, a leading BOM is allowed, and portos-allow-hidden-content on the line itself opts out of the added-line rules. Driven by scripts/scan-diff-hidden-content.js, which CI runs on every pull request before any reviewer reads the diff (core.quotepath=false so a stealth filename is not octal-escaped past the detector). Pure.
localLlmDisk.js Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull.
specDecodePresets.js Curated llama-server launch presets (target + optional drafter GGUF paths, --spec-type, and the Hugging Face repo/quant each file comes from) plus findSpecDecodePreset / specDecodeSource / hfSearchUrl. A preset whose spec type drafts with nothing (none, any ngram-*) carries an empty draftModel and is just a launch line for one checkpoint — which is what makes this the home for a model only llama-server can load, e.g. ternary-bonsai-2-27b, whose ternary packs stock llama.cpp (and therefore Ollama and LM Studio) cannot run. Also owns the --spec-type vocabulary: SPEC_TYPE_SUGGESTIONS (published to the launcher card), parseSpecTypes (the flag is a comma-separated list) and isDraftSpecType (the draft- prefix is what needs a drafter GGUF — every ngram-* type runs without one). Server-owned so the launcher card can offer a Download button per file. Pure.
llamaCppInstall.js Where a llama.cpp install comes from on this host, for services/llamaServerManager.js. llamaCppInstallPlan(platform) → the frozen descriptor for that platform's package manager — Homebrew on macOS/Linux (brew install llama.cpp), winget on Windows (winget install ggml.llamacpp) — carrying manager, managerLabel, packageId, installCommand, the install/upgrade (and, for winget, list/upgrade-check) argv, and the three refusal strings a caller would otherwise hardcode: missingManagerError, notInstalledError, pathRepairHint. The LLMs page renders installCommand out of the llama-server status payload, which is what stopped a Windows install prompt from telling the user to run Homebrew. Also the winget-side readers Homebrew needs no equivalent for: parseWingetPackageFields(stdout, id) (winget has NO machine-readable output mode and LOCALIZED table headers, so fields are read positionally from the tokens after the id token — Version [Available] [Source]; null = not installed), wingetLinkDirs(env) (the portable-shim directories winget adds to the USER PATH, which an already-running server has not inherited) and isWingetManagedPath (counterpart of the manager's isHomebrewLlamaServer: a source build earlier on PATH must not be offered a winget upgrade). Every WinGet path is reasoned about with path.win32 regardless of host, so both branches are coverable from a macOS/Linux checkout. Pure.
ollamaContext.js Ollama runtime context-window reasoning. resolveOllamaContextLength(provider, env) → the window PortOS should hold the daemon at (provider.numCtx, then OLLAMA_CONTEXT_LENGTH, then null = leave Ollama's VRAM-based auto-pick alone); withOllamaContextEnv(env, n) builds the ollama serve child env; parseOllamaContextOverflow(text) recognizes the exceed_context_size_error rejection and pulls { promptTokens, contextLength } out of either the JSON body or the human message; describeOllamaContextOverflow / describeOllamaContextTooSmall render the actionable one-liners; normalizeOllamaBaseUrl(raw) (scheme, no trailing slash, no /v1), isSameOllamaDaemon(providerBase, managedBase) compares host+port so a provider pointed at a remote Ollama never triggers a local-daemon reload, with managedOllamaBaseUrl(env) supplying the managed side (OLLAMA_URL → OLLAMA_HOST → the stock local daemon); managedOllamaContextLength(provider, env) is resolveOllamaContextLength gated on that comparison, and withOllamaRuntimeContextWindow(provider, env) stamps it onto an in-memory provider projection as runtimeContextWindow — how the env rung reaches the vendored toolkit’s clampToRuntimeContextWindow, which may not import out here (#7472); OLLAMA_AGENT_MIN_CONTEXT is the window below which an agent harness is warned. Pure — the daemon side lives in services/ollamaManager.js (ensureContextWindow), the pre-spawn enforcement in services/ollamaAgentContext.js.
localModelHeuristics.js Capability heuristics for untyped local (Ollama/LM Studio) models. isEmbeddingModel/isGenerationModel (so a generation/fallback run never picks an embedding model like nomic-embed-text); isVisionModel(model) (string id or model card — prefers explicit type:'vlm'/capabilities:['vision'] metadata, falls back to id regex; used by the LoRA captioner); recommendEditorialModel(models, { measured }) ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure — client/src/utils/localModelHeuristics.js re-exports isEmbeddingModel/isVisionModel/isToolUseModel from here.
localModelAssessment.js Scoring for MEASURED local-model assessments (recorded by services/localModelAssessments.js): classifyFitVerdict (fits/does-not-fit/incompatible/unknown), summarizePerformance (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), scoreAssessment + scoreForIntent + rankByIntent for the balanced/smartest/fastest/lightweight pickers, explainAssessment, compareEnvironments/describeStaleness (is a stored reading still valid for THIS machine?), buildThroughputReport (every measurement as one tokens/s table, fastest first, per-context readings intact), selectSweepTargets/summarizeSweepScopes/SWEEP_SCOPES (which measurements a "measure everything" run covers, and how many), and measuredFitVerdict/reconcileFit (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. null strictly means NOT MEASURED — never 0, never "failed".
localModelTuning.js Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and applies + the user-facing note are DERIVED from it: config (llama.cpp's -b/-ub/-t/--parallel/--flash-attn/--cache-type-k|v/--spec-draft-n-max, via launchConfig), env (Ollama's OLLAMA_CONTEXT_LENGTH/_FLASH_ATTENTION/_KV_CACHE_TYPE/_NUM_PARALLEL, via launchEnv), cli (a flag on the launch line of a daemon PortOS re-runs — LM Studio's lms load --context-length/--gpu/--parallel, and MTPLX's mtplx serve --context-window/--depth/--generation-mode/--kv-quant/--batching-preset/--profile — via launchArgs), or wire (a request-body field, via requestBody — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an mtplx serve flag — it exits before it binds on one it does not recognize. Also normalizeTuning (coerce + clamp + drop unknown keys), tuningSignature (stable identity — '' for backend defaults, so pre-tuning store keys keep resolving), describeTuning, launchTuning, and compareTunings (which tuning won per model using exact tokens/s when all variants have tokenizer counts and chars/s otherwise, labelled from each record's persisted tuningLabel, with a deltaPercent against the winner), and tuningGridFor (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a sweep value, capped by maxVariants; sweepWith carries a knob's documented prerequisite). Pure.
loraDataset.js Pure helpers for character LoRA training datasets (data/lora-datasets/): sanitizeLoraDataset (collectionStore sanitizer), deriveTriggerWord (name → single-token slug with collision suffix), prefixCaption (idempotent trigger-word prefixing), buildVariationMatrix (deterministic view/pose/expression/outfit tuples for batch generation), computeDatasetReadiness (trainable gate: ≥MIN_TRAINING_IMAGES ready+captioned images, plus an advisory recommended/quality tier via datasetQualityTier nudging toward RECOMMENDED_TRAINING_IMAGES), analyzeCaptionInvariants (flags identity fragments repeated across ≥INVARIANT_SHARE_THRESHOLD of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + stripSharedFragments (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in services/loraDatasetGenerate.js / services/loraDatasets.js.
loraTriggers.js Pure trigger-word weaving for renders that load a LoRA (#4665): weaveLoraTriggers(prompt, triggerWordLists) → { prompt, added } appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. promptHasTriggerWord is the whole-token, case-insensitive presence test (aria_tok does not match inside aria_token); firstTriggerWord picks the canonical token out of a Civitai trainedWords list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by services/imageGen/local.js and services/videoGen/local.js (paired with services/loras.js#readTriggerWordsByFilename for the sidecar reads). The comic pipeline shares it rather than opting out — its own " ()" clause uses the same token, so the weave adds nothing there except for the characters that clause drops.
issueLength.js Per-issue size targets fed into text stages.
musicDuration.js Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors client/src/lib/musicDuration.js.
learningVerdict.js The three-way success-criteria verdict a completed agent run carries on result.validationPassed (#4107). true/false = a declared criterion was met/missed; null = none declared (record the run, fall back to the exit code); SKIP_LEARNING_VERDICT = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on no-app/app-not-found). isSkipLearningVerdict(v) gates the skip; toValidationVerdict(v) narrows anything non-boolean — including the sentinel — back to null for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on typeof v === 'boolean'. Pure.
investigationTasks.js Investigation-task identity, approval, auto-retry, and PR-backed delivery policy — shared by the producers (services/investigationTaskProducer.js), the reaper (cosTaskStore.js, which used to hand-copy the predicate to dodge an import cycle) and the retry (services/investigationRetry.js). isInvestigationTask(task) (durable isInvestigation marker, falling back to the INVESTIGATION_HEADLINE_PREFIX headline for pre-#2615 / peer-synced tasks); INVESTIGATION_TASK_DELIVERY keeps unattended investigations in an isolated worktree and routes them through a PR merged on green, while CLIENT_INVESTIGATION_DELIVERY + clientInvestigationFingerprint({description, app}) give a UI-queued investigation (#6043) the same isolation with a review-then-merge PR and a server-derived ui-investigation dedup key the client cannot hand-craft; buildInvestigationFingerprint(task, analysis) / investigationFingerprint({category, kind, scope}) → the category:kind:scope dedup key; resolveInvestigationApproval({fingerprint, tasks, recentCreations}) → unattended by default (#3714), held only on a repeat-fingerprint or failure-storm loop, with approvalReason + loopProse for the queue UI; couldReleaseBlockedTasks(investigation) is the pure pre-read gate for resolveInvestigationRetryTargets({investigation, tasksById}), which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its RETRY_SKIP_REASONS reason (an auto-expired completion, a non-blocked task, a NON_AUTO_RETRY_BLOCK_CATEGORIES block, or a task past MAX_AUTO_RETRIES_PER_TASK); autoRetryMetadata(task, investigationId, now) stamps the budget that survives the revive's own failureCount reset. Pure.
mediaItemKey.js <kind>:<ref> key vocabulary for media items.
assetProvenance.js Stamp-time model/LoRA license provenance (buildProvenance / provenanceForRender / rollupProvenance). Unknown stays null (displayed as "unknown") — never a permissive default. Mirrored byte-for-byte to client/src/lib/assetProvenance.js.
avatarVariants.js Rigged-record avatar variant spelling (RIGGED_VARIANT_PREFIX, AVATAR_VARIANT_PATTERN, parseRiggedVariant, riggedVariantForId, isAnimatedRecordReady) — the rigged-<modelId> namespace over ?variant=, sharing the route's strict traversal guard.
avatarStyles.js The CoS avatar-style vocabulary (#6253) — AVATAR_STYLES ({id, label, webgl}), AVATAR_STYLE_IDS (the avatarStyle zod enum in cosStatusRoutes.js), AVATAR_STYLE_LABELS, and WEBGL_AVATAR_STYLE_IDS (the three.js-stage set). client/src/lib/avatarStyles.js re-exports it for the picker and the lazy-load map.
migrationMarker.js Shared marker-file helpers for one-time migration/repair/reconcile scripts — markerExists(filename) (boolean gate), readMarker(filename) (parsed payload or null), writeMarker(filename, payload) (atomic write). All anchor filename under PATHS.data and use tryReadFile/atomicWrite so a crash can't leave a truncated marker.
goalFeatureMap.js Deterministic goal category → PortOS feature-area map (deep-links sourced from NAV_COMMANDS). getGoalFeatureAreas(goal) honors the per-goal featureAreas override, else the category default. Mirrored byte-for-byte to client/src/lib/.
goalFidelity.js Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. GOAL_FIDELITY_VERDICTS (ship / fix-first / rethink, only rethink gating a run via goalFidelityHoldsRun), taskObjective(task) (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), resolveGoalFidelityConfig(codeReview, chain) (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its <backend>Model/Effort scalars), normalizeGoalFidelityVerdict(parsed) (null = nothing judged the run, never collapsed into a ship pass or a rethink hold) and formatGoalFidelitySummary(review). mergeOutcomeObjective(task) / mergeOutcomeReview({ number, prState }) / GOAL_FIDELITY_SOURCE_FORGE are the second answer shape: a review-loop follow-up is asked to LAND a change request, which no diff evidences, so its verdict is established from forge state (MERGED ⇒ ship, everything else ⇒ nothing). isDependencyAuditSummaryDiff recognizes only edits to the two existing docs/DEPS.md audit-summary fields; finalization declines diff-only review for that dependency-audit shape only after independently reading empty alert and PR inventories (no invented ship verdict). MAX_OBJECTIVE_CHARS / MAX_FIDELITY_DIFF_CHARS bound what crosses into a fixed-window local model. Pure. retainedProductionUses(objective, diff) supplies exact-token surviving production witnesses for the bounded contradiction check. SUMMARY_DISCLOSURE_REPAIR_CUE frames only the bare premature-summary report, with its description and cap preserved. productionAfterChangeHunks (hunk-local JSX predicate traces) preserves separate file/hunk provenance while excluding deleted lines and tests for focused production review. backfillAccountingFindings adds only source-proven counter/warning contradictions for explicitly requested backfill outcomes; it never establishes delivery. productionAuditEvidence(diff) supplies hunk-local complete-statement syntax facts and handled-rejection scenarios with unavailable enclosing context marked.
goalFidelityCalibration.js Goal-fidelity CALIBRATION contract — what happens when the follow-up investigation overturns a finding, i.e. the objective WAS delivered and the reviewer misjudged it. GOAL_FIDELITY_CONTEXT_GAPS is the closed vocabulary of what the reviewer could not see (truncated-diff, truncated-objective, objective-omits-context, work-outside-diff, execution-step-misread, rubric-gap, other), enforced ONLY by normalizeGoalFidelityContextGap (the report route takes a bounded string, so a near-miss gap name folds to other with its diagnosis intact instead of 400ing the report away). GOAL_FIDELITY_REVIEW_SURFACES addresses the reviewer's three context surfaces once — objective / diff / rubric — and GOAL_FIDELITY_CONTEXT_GAP_FIXES maps each gap onto one of them, so a rename cannot leave seven prose copies lying (goalFidelityCalibration.pointers.test.js walks the table against the real files). goalFidelityCalibrationFingerprint(gap) keys the dedup on the GAP alone, so many false positives from one blind spot fold into one fix instead of minting an agent each. buildGoalFidelityCalibrationTask composes the PortOS-side task body (including the do-not-disarm-the-detector contract) and buildGoalFidelityFalsePositiveReportBlock the curl instructions appended to a follow-up task, taking apiBase as an argument and the call shape from agentApiToken.js. I/O lives in services/goalFidelityCalibration.js.
goalFidelityFollowUp.js Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. resolveGoalFidelityFollowUp(codeReview) (null when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked), normalizeGoalFidelityFollowUpTrigger (shared with the settings projection so the form and the runtime cannot disagree), and goalFidelityFollowUpApplies(review, trigger) over GOAL_FIDELITY_FOLLOW_UP_TRIGGERS (rethink = only the verdict that holds a run, the default; any-finding also fires on the advisory fix-first). goalFidelityFingerprint(task) is the one dedup identity three parties share — the issue body marker (goalFidelityIssueMarker / issueMatchesGoalFidelityMarker), the tracker listing that reads it back, and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. Public issue markers hash that identity while matching legacy markers. buildGoalFidelityIssue requires a complete objective with verified tracker provenance and immutable diff references before publication; buildGoalFidelityFollowUpTask carries the finding issue snapshot and its resolution lifecycle. I/O and public-text scrubbing live in services/goalFidelityFollowUp.js.
navManifest.js Single source of truth for nav (⌘K palette + voice). Add an entry when you add a page. Also getNavPageForPath(pathname) → { label, section, breadcrumb } for the most specific command that owns a route (null for one nothing declares) — how user-facing copy NAMES a page it links to, instead of typing "Models → LLMs" beside the link and stranding it on the next move (#7414). expandPageToken(text, runtime) expands a {page} token in text using getNavPageForPath(runtime?.manageUrl), falling back to generic prose rather than shipping a literal {page} (#7419).
noChangeCompletion.js permitsNoChangeCompletion(task) — the single predicate for "this run may finish successfully with an empty branch": the persisted noChangeSuccess marker AND (autonomousJob OR isInvestigation OR built-in quality audit OR a type in the exported NO_CHANGE_SCHEDULED_TYPES allowlist — dependency-updates, whose ordinary outcome is "already current"; taskSchedule.test.js keeps the list and the schedule defaults' noChangeSuccess markers in parity). Read by both the prompt builder and finalization so the agent is never told a contract finalize will not honour; whether the branch was really empty is the post-run branchProvenEmpty verdict.
noReplaceMove.js moveWithoutReplace(from, to) — publish a staged file into its final name WITHOUT ever clobbering an existing one. fs.rename silently replaces its destination, which is the wrong default for a derived artifact; this uses link(2) + unlink(2), so an existing destination fails atomically with MOVE_DEST_EXISTS and both files survive. Refuses rather than degrading when the filesystem cannot express it (MOVE_CROSS_DEVICE, MOVE_NO_REPLACE_UNSUPPORTED) — a stat-then-rename fallback would be a race. Used by the rigging publication contract (services/rigging/autoSkin.js).
personaTraitBlend.js Digital-twin persona trait-blending (M34 P7). Blends a persona's traitAdjustments against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — client/src/lib/personaTraitBlend.js re-exports it for the Personas UI preview.
textUtils.js Pure dependency-free prose helpers. isStr(v) and isNonBlankStr(v) are the ONLY string predicates under server/ (#6837) — the bare type check, and type check plus a non-empty trim() for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in textUtils.test.js fails the suite when a copy of either, or a trimTo-shaped bounder, is re-declared in any non-test source under server/ or any source under client/src/ (client/src/lib/textUtils.js re-exports both for the browser bundle). countWords(text) is the canonical whitespace-token count (\S+) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (client/src/lib/textUtils.js re-exports it) resolve here, and the "no private countWords" guard in textUtils.test.js fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under server/ or any source under client/src/; the editorial prose-analysis checks deliberately count LETTER words instead, through editorial/proseTics.js#tokenizeWords, which owns that tokenizer the same way; trimTo(value, max) trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; escapeRegExp(value) is the one to import instead of re-inlining the escape (the sibling guard in textUtils.test.js fails the suite when a copy reappears in any non-test source under server/, or in ANY source under client/src/, tests and .jsx included — client/src/lib/textUtils.js re-exports this module for the browser bundle); trimToClause(v, max) is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in storyBible.js, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling crypto / fileUtils); kebabCase(text) is the canonical ASCII slug transform (PLAN.md [slug] ids and planner:<model> labels), and truncateOnBoundary(slug, max) is its bounder — back off to the last - at or before max so a slug a human reads (a PLAN.md id, the app segment of a CoS worktree directory) is never cut mid-word, which trimTo would reintroduce; clampToCharLimit(text, max) is trimTo's reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns { text, truncated } so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). firstLine(text) is the first non-blank line, trimmed — the CoS task headline addTask dedupes on, declared here rather than in the task store so a closure-sensitive caller can reach it (cosTaskStore.js re-exports it).
pipelineIds.js Shared assertValidSeriesId / assertValidIssueId path-segment guards for pipeline snapshots, preserving the safe charset and domain-specific errors.
pipelineIssueOrder.js Volume-based renumbering and compareIssuesInSeries for globally ordered manuscripts and production.
pipelineStages.js Canonical pipeline data-stage groups, visible tab order, UI/voice labels, spoken aliases, and derived voice-intent regex.
postAdaptive.js Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (steps/maxDigits/maxExponent/tolerancePct) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle.
postAppliedNumeracy.js Pure seeded Applied Numeracy pack — everyday percentage, ratio, unit, rate, and estimation scenarios plus server-authoritative numeric/fraction/unit scoring with explicit tolerance handling.
postMultiplicationLadder.js Pure progressive multiplication ladder — mastery-gated difficulty rungs ([1,1] → [1,2] → [1,1,1] → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on postProgression.js.
postPowersLadder.js Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on postProgression.js.
postProgression.js Generic mastery-gated progression ladder (extracted from postMultiplicationLadder.js) — createProgression({ levels, describeLevel, speedTargetForLevel? }) resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (including task switching, Go/No-Go, and Flanker) and their level→generator-config mapping.
spacedRepetition.js The shared SM-2-inspired review scheduler, extracted from services/meatspacePostMemory.js when SongBook practice became its second consumer (#4102). One four-field schedule shape ({ ease, intervalDays, nextReview, lastReviewed }, no repetitions counter — the 0 → 1 → 6 → round(prev * ease) ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). advanceSchedule(schedule, ratio, now) is the core (ease clamped to MIN_EASE..MAX_EASE, interval capped at MAX_INTERVAL_DAYS so new Date(now + interval*DAY) can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). mergeScheduleAdvance(prev, advanced, now) gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; isSameReviewDay is that gate's own predicate, reusable by callers gating their own once-a-day progression. scheduleOrDefault(record, schedule?) is the read-path fallback — a record with no schedule derives one anchored to its updatedAt/createdAt (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. ratioToQuality / qualityToRatio are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. isScheduleDue treats an absent/unparseable nextReview as due — a record we can't schedule is one to surface, never one to hide forever. Pure.
songPractice.js SongBook repertoire practice scheduling (#4102) — the pure core behind POST /api/brain/songbook/:id/practice. applySongPractice(song, quality, now) → { stage, practice }, the exact partial to hand brainStorage.updateWith: it advances the shared spacedRepetition schedule from a 0..5 self-grade and moves the song's stage along SONG_STAGE_ORDER (≥ SONG_PROMOTE_MIN_QUALITY promotes, ≤ SONG_REGRESS_MAX_QUALITY regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at learning — new means "never picked up", which stops being true after one session. songPracticeOrDefault(song) derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp updatedAt on every record and spray federation churn, and would break the data.reference/ seeds' byte-identity). nextSongStage no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. isSongDue(song, now) mirrors the client's isSongDue in client/src/components/songbook/constants.js. Pure.
postTopics.js Pure POST practice-topic registry — POST_TOPICS ({ id, label, module, surface, drillTypes }) is the single source of truth for "what am I studying?", plus resolveTopicForDrillType / isTopicEnabled / isMemoryItemEnabled. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. A pure leaf: the client's post constants.js re-exports it and layers the UI-only TOPIC_UI on top.
postScoring.js Scoring and accuracy helpers for post-training drill types shared between server (services/meatspacePost.js) and client (components/meatspace/post/constants.js) — nBackBalancedAccuracy (balanced signal-detection accuracy for n-back questions), plus DEFAULT_ESTIMATION_TOLERANCE_PCT / resolveEstimationTolerancePct(pct) — the single estimation band that server grading, the client's optimistic check, and the on-screen "within N%" copy all read, so the number shown and the number graded cannot drift.
postRotation.js Pure deterministic day-based rotation for POST practice selection — shuffleForDay supplies a stable pseudorandom daily mix; orderByRecencyRotation sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day so a tier never pins to one drill. Mirrored at client/src/lib/postRotation.js.
postStreak.js Pure DST-safe POST practice-streak math — the single computePostStreaks implementation shared by scored sessions and the training log, plus computeUnifiedStreak (a day is active with EITHER a session or a practice entry), normalizeYmd (day-key prefix for a date that may be a full ISO timestamp), and recordDayKey / withDerivedDayKeys (re-derive a record's day key from its startedAt/completedAt/timestamp instant, so readers ignore a date frozen in a previously-configured timezone).
activeDays.js Cross-domain "days active" set math (#4120) — unionActiveDayKeys(sources, timezone) unions several domains' stored date values into one sorted array of user-local YYYY-MM-DD keys (.length is the honest day count; summing per-domain counts would double-count any day logged in two domains), and toUserDayKey(value, timezone) is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps userLocalToday()) and the health logs (stamp the server-local getDateString()): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than split('T')[0]'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure.
issueClaimEvidence.js Shared forge claim evidence: documented claim refs, PR/MR closing trailers, paginated GitHub commit messages, and complete-page validation.
planIds.js Utilities for PLAN.md [slug] IDs.
markdownText.js stripMarkdownEmphasis(text) — unwrap **bold** / ~~struck~~ / `code` / [text](url) and drop HTML comments, keeping the words. For strings handed to something that can't read markdown (a model's text encoder, a slug builder, TTS); leftover lone *_~ become spaces so an unbalanced marker can't fuse two words. Does not collapse whitespace — callers that need that normalize themselves.
renderSlot.js Render-slot helpers for (proof|final)Image per stage.
renderTargets.js Render-target alphabet (#3231): RENDER_TARGET/RENDER_TARGETS name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into settings.renderDefaults — plus the RENDER_TARGET_BACKEND_AUTO fall-through sentinel. Dependency-free leaf; resolved per surface by services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig.
renderTiming.js renderTimingFields(startedAtMs, nowMs?) → the { renderMs, renderStartedAt, renderCompletedAt } spread every image/video backend stamps on the record it persists, measuring ingestion → finished artifact (not queue wait). Returns {} when no start instant was observed, so absence stays the explicit unknown sentinel for the history cards and services/videoGen/eta.js. omitRenderTiming(record) is the inverse, for a DERIVED record built by spreading its source (an image variant) that must not inherit a duration it never took.
telegramClient.js Telegram bot client.
notificationTypes.js Notification vocabulary, forwarding labels, and the allowlisted NOTIFICATION_ACTION_POLICY used to admit source-owned obligations into the Review Queue.
telegramMessage.js Pure builder for the Telegram notification wire message, shared by both transports (services/telegram.js and services/telegramBridge.js, which drifted apart while each kept a copy — #5688). buildNotificationMessage(notification, { approvalBody }) → { text, options }: emoji + escaped title, the body truncated to TELEGRAM_MAX_RAW_CHARS (2800) BEFORE escaping so the escaped result stays under Telegram's 4096 cap and a slice can't split an entity, the priority line, and the memory approve/reject reply_markup as a plain OBJECT (both transports post JSON, so a pre-serialized string would arrive as a literal string). approvalBody is resolved by the caller because the memory lookup is I/O. Also exports escapeHtml, truncateForTelegram, isMemoryApprovalNotification, the NOTIFICATION_EMOJI/PRIORITY_EMOJI maps (keyed by literal NOTIFICATION_TYPES values to stay a dependency-free leaf; pinned to the real enum by a parity test), and the CALLBACK_APPROVE/CALLBACK_REJECT prefixes the bot's callback_query handler parses back out.
telegramRateLimit.js createTokenBucket({ max = 30, refillMs = 60_000 }) → { consume() } — the coarse full-refill-per-window bucket both Telegram transports use against Telegram's ~30 msg/min throttle. Each transport creates its OWN instance: they are never both active, and one shared bucket would let a transport inherit the other's drained budget. Pure (reads Date.now(), owns no timer).
tempPathGuard.js Throwaway-path guard for destructive test fixtures. isTempPath(target) — true only for an absolute path that is a STRICT descendant of os.tmpdir() after symlinks are resolved (os.tmpdir() itself is refused, or destroyGitSandbox(tmpdir()) would wipe every process's scratch; a .. segment is refused rather than lexically collapsed; macOS /var/folders/... and /private/var/folders/... both pass). assertTempPath(target, operation) throws otherwise and returns target so it can wrap an argument inline. Use it before any fixture git init / git config / rm -rf: spawn silently substitutes process.cwd() for a missing cwd, which is how a test run once set core.bare = true on a real checkout (#4554).
vaultCrypto.js Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM encryptValue/decryptValue (v1:<iv>:<tag>:<ct> format, per-value 12-byte IV), ensureVaultKey() self-heal (generates PRIVACY_VAULT_KEY into the install root's .env on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading .env so decrypt/status survive a server restart, isVaultKeyConfigured(), and the per-type maskValue(type, plaintext) display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers.

Model & config

Module Purpose
backupAssetOwners.js BACKUP_ASSET_OWNERS inventories every durable file-plus-row owner as admitted, reference-only, or outstanding; backupAssetConsistency() derives the consistency a backup snapshot may claim (global only when nothing is outstanding, otherwise admitted-owners with the outstanding ids). Its test keeps admitted entries and withBackupAssetPublication call sites in step.
backupSnapshotBoundary.js withBackupAssetPublication(work) admits a complete durable file-plus-row mutation; acquireBackupSnapshotCut() drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; runOutsideBackupAssetPublication(work) lets a synchronous event fan-out give each listener its own lease; holdsBackupAssetPublication() tells a writer whether it runs inside an active lease; backupSnapshotCutPending() lets optional housekeeping defer instead of waiting out a cut.
backupConfig.js resolveBackupConfig(settings.backup) + DEFAULT_BACKUP_CRON — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted enabled means enabled, a missing/blank cronExpression means midnight (0 0 * * *), and scheduled additionally requires a destPath. Also resolveRetentionCount(settings.backup) + DEFAULT_RETENTION_COUNT/MIN_RETENTION_COUNT/MAX_RETENTION_COUNT (#8334): per-source completed-snapshot retention, where an omitted or null retentionCount means unlimited — a NEW install ships the 30 default on disk via data.reference/settings.json, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by services/backupScheduler.js (registration + handler eligibility, and the retention count services/backup.js#runBackup prunes with) and routes/settings.js (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults.
systemIdle.js summarizeSystemActivity(processingSnapshot) → { idle, activeCount, queuedCount, blockers[] } + describeActivityBlockers — the ONE definition of "is this install doing anything", derived from the /api/system/processing snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed.
browserConfig.js Shared browserExecutablePath resolution for managed and owned render browsers, plus custom path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths.
browserUnsafePorts.js BROWSER_UNSAFE_PORTS / isBrowserUnsafePort(port) — the WHATWG Fetch "bad ports" browsers refuse (ERR_UNSAFE_PORT, incl. X11's 6000). Port allocators (findAvailablePorts, services/ports.js, the PM2 standardizer) must skip these so a managed app's UI is never unreachable.
condaEnv.js Resolves a NAMED conda environment's interpreter: condaEnvPythonCandidates(envName) builds the ordered candidate list (CONDA_PREFIX — walking up two levels when it points at an envs/<name> rather than a root — then CONDA_ROOT, ~/miniconda3, ~/anaconda3, ~/miniforge3, ~/mambaforge, /opt/conda), and resolveCondaEnvPython(envName, { exists }) returns the first that exists or null. Separate from pythonSetup.js (which probes venv layouts and computes candidates from PATHS at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (trellis2, pixal3d) so one lane's pinned deps can't disturb the other's.
cudaCapability.js NVIDIA CUDA host probe — the one place that shells to nvidia-smi. detectCudaGpus() / cached getCudaCapability() return { available, status, gpus, maxVramGb } where status is three-way: 'available', 'absent' (no driver, or driver present with zero GPUs), or 'unknown' (nvidia-smi exists but wouldn't answer — available is null, never false, so callers can say "couldn't detect" instead of lying about the hardware). unknown is not memoized so a transient driver hiccup retries. parseNvidiaSmiGpus(stdout) is the pure CSV parser (a [N/A] VRAM column yields vramGb: null, not a dropped GPU). Gates the image-to-3D local-cuda lane and the Windows FLUX.2 CUDA-torch wheel choice (pythonSetup.js#hasNvidiaGpu). detectCudaComputeCapability() / cached getCudaComputeCapability() are a SEPARATE nvidia-smi query (--query-gpu=name,compute_cap,memory.total, parsed by parseNvidiaSmiComputeCaps) returning primaryComputeCap — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's NATTEN_CUDA_ARCH and SGLang provider filtering; kept separate because an older driver rejects compute_cap and would fail the whole VRAM query with it. detectCudaUtilization() / getCudaUtilization() add live per-GPU utilization on a short TTL.
systemCapabilities.js Machine-local capability snapshot plus the shared three-state hardware requirement evaluator. Captures coarse platform, architecture, Apple Silicon, memory, CPU, and cached CUDA facts; derives requirements for media models, local-LLM catalog entries, and provider runtimes; hides only known-incompatible choices while preserving unknown probe results.
db.js PostgreSQL connection pool and withDatabaseMaintenance(fn) admission/drain gate for atomic restore and reconciliation.
db/ Boot DDL for the PostgreSQL schema, split per domain (#2832). db/schema/index.js re-exports each module's statement array and composes the two ordered lists ensureSchemaImpl() runs on every boot (buildUpgradeDdl() then buildCatalogDdl()). Statement order is load-bearing — append inside the domain module and leave the composer order alone. See db/schema/README.md for the module catalog.
pgTimestamp.js mirrorTimestamp(value, fallback) — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against Date.parse rollover + out-of-range years.
pgTools.js withPgToolEnv(config, run) stages Node trust roots with guaranteed cleanup; isolates libpq connection/TLS settings from inherited PG variables; pg_dump binary resolution shared by the backup snapshot path and the native↔Docker export path: resolvePgDumpBinary(serverMajor) (PORTOS_PGDUMP override → version-aware auto-select → bare pg_dump), plus the lower-level pickPgDump / discoverPgDumpCandidates / resolvePgDump. Picks the closest installed pg_dump whose major is ≥ the running server's.
ecosystemProcessPorts.js Attributes a parsed PM2 ecosystem config's port labels to the app that OWNS them (#7357): processSurface(name) (a process name minus one trailing role suffix, so portos-server/portos-ui share surface portos while portos-autofixer-ui does not), attributeProcessPorts(processes, app) (api/ui/devUi resolved from the app's own surface first, then from a carrier whose name declares no role at all, and left undefined when none — which is what lets the served-by-API uiPort derivation take over), and findCrossProcessPortCollision(processes, edits) (the pre-write guard: a port another process in the same config already holds). Shared by services/appPortConfig.js (write-back) and services/appListEnrichment.js (read/derive) so a displayed port and a rewritten port can never disagree about whose it is.
ports.js Canonical PORTS object (mirroring ecosystem.config.cjs, pinned by ports.test.js), DEFAULT_PEER_PORT, and resolvePostgresPort(pgMode). A pure leaf: client/src/lib/ports.js re-exports it, so nothing here may read process.env at module scope — the env-derived origins live in portosUrls.js.
portosUrls.js PORTOS_UI_URL / PORTOS_API_URL — the origins PortOS interpolates into prompts and links, resolved from PORTOS_* / PORT at module load. PORTOS_API_URL_TOKEN is the {portosApiUrl} placeholder agent prompts embed instead of PORTOS_API_URL; buildAgentPrompt expands it at spawn time to localApiBaseUrl() (the loopback mirror on HTTPS installs). Split out of ports.js so that module stays free of module-scope process.env reads and can be re-exported to the client.
platform.js Platform/OS detection helpers — listening-port probes plus isAppleSilicon() (arm64 darwin; gates MLX model features, detect at the route boundary).
processCwdProbe.js hasProcessCwdInside(dir) — true when any process (via lsof -d cwd) has its working directory inside dir. Fails CLOSED: no lsof, an unsupported platform or an empty/unreadable listing reads as occupied. Backs the ownerless-foreign-worktree release in worktreeManager.js.
openFileHolders.js findOpenFileHolders(files, { canary }) → { known: true, pids } (other processes holding any of files open, via lsof -F pn) or { known: false, reason }. Fails CLOSED: the probe holds canary open itself and rejects any listing that does not report its own PID, so a missing lsof, an unsupported platform or a truncated listing never reads as "nobody holds it". Gates the staged-checkpoint cleanup in services/ollamaSafetensorsImport.js.
signalCrypto.js Pure, dependency-free crypto for Signal Desktop (#2154, #11149): SQLCipher-4 page decryption (decryptSqlcipherDatabase, deriveSqlcipherKeys, sqlcipherPageHmac) and Chromium/Electron safeStorage unwrap (decryptSafeStorageValue, deriveSafeStorageKey). Live sync does not decrypt a raw main-file copy — that misses committed WAL frames — and instead uses services/signalSnapshot.js. isRawHexKey still gates the key. All functions return { ok, ... } reports (never throw).
timezone.js Timezone utilities for scheduling. getLocalParts(utcDate, timezone) / getUtcOffsetMs(utcDate, timezone) are the primitives; nextLocalTime(afterMs, hours, minutes, timezone) finds the next UTC instant matching a local HH:MM. anchorLocalMidnightUtc(dayStr, tz) resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; localDayWindowUtc(timezone, atDate?) exposes an inclusive ISO-string window, while localDayRangeUtc(dateStr, timezone) returns a validated half-open { start, end } Date pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns HHMM_RE/HHMM_STRICT_RE, parseHHMM, dailyCronFromHHMM(time) (the one strict "HH:MM" → "M H * * *" conversion every daily-reminder scheduler registers through, null on malformed input so the caller cancels rather than firing in some other slot), and isWithinTimeWindow (mirrored client-side in client/src/utils/timeWindow.js).
tribeCadence.js Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to client/src/lib/tribeCadence.js): cadenceStatus(entity) → { state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }, daysSinceDate(dateStr), DEFAULT_CADENCE_DAYS (45), SOON_WINDOW_DAYS (7). Consumed by personCadenceStatus / getCareSummary in services/tribe.js (proactive alert + Care widget) and by the client Tribe page/map.
tribeMatch.js Pure, deterministic matcher mapping a calendar attendee / message counterpart ({ email, phone, name }) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): buildPersonMatchIndex(people) → { byIdentifier, byPhone, byName }, matchPerson(identity, index) (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), matchPeople(identities, index) → de-duplicated Set of personIds, normalizeIdentifier(value), normalizePhone(value) (E.164 normalization for iMessage/Signal handles), identityFromHandle(handle) (classify a raw chat.db handle into email-or-phone). Also resolveLinkedPersonId(tribePersonId, tribePersonDeleted) — the shared soft-delete predicate a beeper_participants row's tribe_person_id cache must pass through everywhere it is shaped, so a soft-deleted Tribe person reads as unlinked in both services/beeperConversations.js and services/beeperTribe.js. Consumed by autoLogTouchpoints in services/tribe.js from the calendar, message, and iMessage sync producers.
viteAllowedHosts.js Detect and remediate a managed app's Vite server.allowedHosts. findViteConfig(repoPath) locates the config; parseAllowedHosts(src) / hostIsAllowed(parsed, host) decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); rewriteAllowedHosts(src) deterministically injects allowedHosts: true (or bails ok:false on ambiguous shapes so the caller can fall back to an LLM fix); checkViteHost(repoPath, host) is the one-shot status used by GET /api/apps/:id/vite-host-check.
buildId.js Build-ID derived from the built client bundle.
buildIdentity.js getBuildIdentity() / getCachedBuildIdentity() / formatBuildIdentity() / parsePorcelainV2() — which git commit the RUNNING server process was started from (#4694): { commit, shortCommit, branch, dirty } from ONE git status --porcelain=v2 --branch spawn, cached per process (the promise, so concurrent first callers share it). Answers "is this the code I am testing?" on a machine where one PM2 server serves :5555 while many worktrees hold different code — version cannot, since package.json's version is identical across every development commit. Served on its own GET /api/system/build, NOT on /health/details: peers scrape that payload and persist it verbatim, and this stays machine-local. Complements buildId.js (bundle hash, not commit), which travels separately on the build:id socket frame — the socket path reaches peer relays, so the commit does not use it. Non-throwing, every field independently nullable (no .git → commit: null, never '').

General utilities

Module Purpose
apiAccessPolicy.js Shared always-public path, gated non-/api prefix, and peer-credential federation surface (PEER_API_SURFACE, isPeerApiRequestAllowed) policy consumed by authGate and API discovery.
apiCatalog.js Searchable projection of the Express route inventory (getApiRouteCatalog() from apiRouteGraph.js): domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion.
hostControlRoutes.js The audited HOST_CONTROL_ROUTES list of HTTP routes that execute on the host (app lifecycle, CoS agent queueing, git, scaffold, standardize, feature agents, loops, GSD, local review, provider execution config, autopilot start) plus hostControlRouteFor / isHostControlRoute; authGate.js#hostControlRouteGate applies requireHostControl to every entry. hostControlBodyRouteFor names the per-body gated route a request matches; server/hostControlCoverage.test.js requires every mounted mutating route to be gated or reviewed-open. hostControlBodyKeys names the execution-policy keys of a PUT /api/settings, PATCH /api/settings/slice, or PUT /api/cos/config body (HOST_CONTROL_SETTINGS_SLICES, HOST_CONTROL_OPEN_COS_CONFIG_KEYS), and hostControlSettingsPathsIn / changedHostControlSettingsPaths the nested settings keys that pick an executable, an outbound endpoint or a host data file (HOST_CONTROL_SETTINGS_PATHS, gated only when the value changes). voiceConfigHostControlPathsIn / changedVoiceConfigHostControlPaths do the same for the voice agent's instructions, coding-agent switch and STT endpoint (HOST_CONTROL_VOICE_CONFIG_PATHS on PUT /api/voice/config). All of these are gated by authGate.js#hostControlBodyGate. The socket twin is HOST_CONTROL_SOCKET_EVENTS in services/socket.js.
apiRouteGraph.js Static scan of the mounted HTTP route graph — server/index.js app.use('/api/…', router) mounts → route-module imports → router.use(prefix, child) → router.<method>('<path>'), including aliased mounts, local subrouters, factory returns and composed toolkit.routes.<x> routers. buildApiRouteCatalog({ repoRoot? }) → { derivedFrom, mounts, routes: [{ method, path, mountPath, sources }], stats }; getApiRouteCatalog() derives it on first use and caches it for the process (read by the API Explorer, the internal OpenAPI document and apiRouteParity.test.js); scanRouteGraph() adds declarationKeys / duplicateDeclarationKeys (routeDeclarationKey) for the coverage guard in apiRouteGraph.test.js. Never committed — see "Generated manifests" in server/AGENTS.md.
socketEventCatalog.js Searchable projection of the cached Socket.IO inventory: direction, domain, and runtime-schema coverage.
sourceScan.js Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. blankLiterals(src) blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; matchBracket(src, open) returns the index past the matching )/]/}; parseCallbackAt(blanked, from, limit) parses the function expression at from (async/function/either arrow spelling, skipping the parameter list as a unit so a = {} default is not mistaken for the body) and returns {isAsync, start, text}; unguardedAwaits(body) returns the awaited chains that neither sit inside a try/catch nor END in .catch(…). blankComments(src) is the weaker LINE-based stripper the per-line child_process rule needs. blankLiterals(src, { includeCommentOnly: true }) returns { code, blanked } (the comment-only and fully blanked views) in one lexer traversal for guards needing both. blankCommentBodies(src) is the complement — comments blanked, literal TEXT kept — for a caller that reads a message string and must not see a marker written in a comment beside it. Callers: childProcess.guards.test.js, server/timerCallbackConventions.test.js, server/logLevelConventions.test.js, server/sockets/asyncHandlerGuard.test.js, server/process-safety-net.test.js.
apiOperationContracts.js Detailed operation metadata for intentionally public APIs. It consumes the canonical route Zod contracts and feeds both public and internal OpenAPI documents.
apiRegistry.js Single source of truth for which PortOS services are externally-callable HTTP APIs (voice, sdapi). API_REGISTRY declares each API's publicPrefixes (read/compute-safe surface only) + defaults; isRegistryPublic(settings, path) tells authGate when an exposed && !requireAuth API re-opens its prefix; resolveApiAccess(settings) merges persisted apiAccess flags for the Settings UI + OpenAPI docs.
arrayUtils.js asArray(value) — returns an array unchanged, or a fresh empty array for non-array inputs. shuffle(arr, random?) — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never arr.sort(() => Math.random() - 0.5), which is biased. Shared by meatspacePostCognitive.js (Schulte table / mental rotation) and meatspacePostMemory.js (memory drill generators). dedupeByKey(items, keyOf, pick?) — one survivor per key, first-seen order. Required before any multi-row INSERT … ON CONFLICT (key) DO UPDATE: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). DO NOTHING upserts are exempt. pick(held, candidate) defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — memorySync.applyRemoteChanges keeps the newest updatedAt so a peer's payload ordering can't flip a last-writer-wins outcome. Used by services/mediaAssetIndex/db.js and services/memorySync.js.
assetRoutePrefixes.js Import-free leaf holding the URL prefixes the server owns: ASSET_ROUTE_PREFIXES (every /data/** static mount) and SERVER_OWNED_PREFIXES (what must never reach the SPA fallback, each with the exact spaPaths that ARE client routes). scripts/dev-proxy-drift.test.js checks the dev proxy's ^/data/ wildcard against the mounts, pins the route-registration order in server/index.js (a router added below the terminators is shadowed), and fails if a client route — from NAV_COMMANDS or App.jsx's nested <Route> tree — is ever added under a server-owned prefix without being declared.
asyncMutex.js Promise-based async mutex.
concurrencyGate.js createConcurrencyGate(limit) → run(fn) — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to mapWithConcurrency.js, which caps in-flight work within one array map; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. createMutex (asyncMutex.js) is this with limit fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by huggingFaceMetadata.js (4) and ollamaRegistryCatalog.js (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare fetch failed.
dispatchLabels.js slashdo dispatch-hint contract: the model: capability and effort: reasoning-budget label vocabulary (the tiers themselves live in this module and are deliberately not re-enumerated here — a catalog copy of them is what drifted a tier behind), prescribed forge colors, validation (normalizeDispatchModel / normalizeDispatchEffort), the read-side inverse (dispatchHintFromLabels — recovers {model, effort} from a raw label-name list, used by branch-reconcile's per-branch routing hint), the per-forge label separator (labelSeparator / forgeLabelName — GitLab spells every prefixed label with its native scoped ::, GitHub keeps :, and the read side accepts both; applied once at the forgeIssueLabels / dispatchLabelSpec boundary so the axis builders stay canonical; Jira keeps the hyphen form), optional contributor labels (good first issue / help wanted, never implied by model:light, and released at claim time by formatContributorLabelReleaseCommands — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (volunteerClaimLabels / formatVolunteerClaimCommands — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp in-progress and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (planner:<model>, normalizePlannerId / resolvePlannerId / formatPlannerLabelGuidance — records WHICH model wrote the plan, prefix-matched by dispatchLabelSpec so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (EPIC_LABEL/EPIC_DECOMPOSED_LABEL and IN_PROGRESS_LABEL — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional --label slots a rendered issue create example offers (OPTIONAL_ISSUE_LABEL_FLAG_SLOTS / formatOptionalIssueLabelFlags — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (ISSUE_QUALITY_GUIDANCE, DISPATCH_HINT_GUIDANCE, MANDATORY_DISPATCH_HINT_GUIDANCE, JIRA_DISPATCH_HINT_GUIDANCE, MANDATORY_JIRA_DISPATCH_HINT_GUIDANCE, REFERENCE_WATCH_LABEL_CONTRACT, plus the consumer-side pair DISPATCH_HINT_READING_GUIDANCE / DISPATCH_HINT_FANOUT_GUIDANCE — what the labels mean to an agent that RECEIVES them (the preloaded open-issues task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). All forge filing callers require both dispatch axes and verify labels after creation; help wanted requires specific hardware validation or valuable input from real users; never invent medium; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts.
distrokidForm.js The in-page steps of the DistroKid upload recipe (#10337): fillDistrokidFields (genre, language, store profiles, credits, preview start, the track's normal answers), discloseDistrokidAi (inline AI checkboxes, gate then parts) and untickDistrokidExtras (paid extras). Self-contained so page.evaluate can ship them, and tested against a fixture form in the client's DOM tests.
sunoPage.js The in-page step of the Suno publish recipe: markSunoSongMenu(songId) tags the song page's OWN "More options" button with data-portos-song-menu (false when there is none), skipping the menus of other songs the page shows: the "Cover of" card of the song a cover was made from, the Similar / By-artist lists, the playbar. Runs inside the page via page.evaluate, so it reads only document; fixture tests live in client/src/lib/sunoPage.test.js.
sunoSong.js Suno song links and pages for the track import: SUNO_SONG_URL_RE / isSunoSongUrl (a suno.com/song/<uuid> page or suno.com/s/<code> share link), sunoSongIdFromUrl, isSunoHost, sunoCdnAudioUrl, sunoCdnVideoUrl (the public fallback when Suno withholds the audio file), and parseSunoSongPage(html, songId) → { title, lyrics, style (excluded styles folded in as minus terms), excludedStylesKnown, audioUrl (CDN media only), imageUrl } read from the page's Next.js flight payload (long-text rows resolved) with og: tags as fallback. Pure leaf the client also imports.
sunoSongPicker.js pickSongRow(rows, { songId, durationSec, title }): which Suno Hook picker row is the project song: by id when a row carries it, else the one row with the song's length, else the only row; -1 when rows cannot be told apart.
distrokidGenres.js DistroKid's store genre list (DISTROKID_GENRES) and suggestDistrokidGenres(project), a first primary/secondary genre guess from the song's own style words, and DISTROKID_REMEMBERED_OPTIONS (the release answers kept in settings and refilled on every project). Shared by the DistroKid publish payload and the publish panel's genre pickers.
domainAutonomy.js Per-domain autonomy guardrails (pure). AUTONOMY_DOMAINS/DOMAIN_IDS/DOMAIN_MODES (off/dry-run/execute), getDomainMode(config, id), and normalizeDomainAutonomy(raw) to coerce a hand-edited/partial map. Default per domain is execute (reproduces pre-#711 behavior, so no migration needed). Also CREATIVE_DOMAIN/getCreativeAutonomyMode(config) (#2183) — the Creative Director orchestrator domain, kept out of DOMAIN_IDS and defaulting to mirror the cos mode.
domainBudgets.js Per-domain daily autonomy budgets (pure). BUDGET_LIMIT_FIELDS (maxActionsPerDay/maxMinutesPerDay), getDomainBudget(config, id), normalizeDomainBudgets(raw), hasBudget(budget), and evaluateBudget(budget, usage) → { withinBudget, exceeded }. A null/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in services/domainUsage.js.
federationSafety.js "Does this JSON-shaped payload carry anything that must not leave the install?" — the structured, REFUSAL-side counterpart to the scrubbers (secretText.js, homePath.js) that rewrite text for a log. federationSafetyFindings(value, { limit }) walks every string AND every object key, returning { code, path, detail } for a home/Windows path, IPv4 or IPv6 literal, .ts.net/.local host, MAC, email, phone number, labelled GPS coordinate (the shared table is piiRedactionPatterns.js), credential-shaped value (scrubSecretTokens) or credential-NAMED key (secretKeys.js#isSecretKey — the half no value-shape scan can see). Deliberately over-refuses rather than under-detects: a payload leaving the machine should fail on "looks like an address", and the finding names the exact JSON path to fix. walkJsonText / describeJsonPath are the reusable path-reporting walk. Pure; reads no environment.
piiRedactionPatterns.js PII_PATTERNS — the machine-identity/PII { code, pattern, replacement } table shared by federationSafety.js (detection, via pattern.test()) and services/agentContextMcp.js#redactAgentContextText / services/agentErrorAnalysis.js#redactFailureSnippet (replacement, via redactPii(text)). One list for home/Windows paths, IPv4/IPv6, MAC, .ts.net/.local hosts, email, phone, and labelled GPS coordinates, so a correction reaches every consumer instead of drifting across independent copies (#7474). globalPattern(pattern) derives a global-flagged copy for a .replace() caller without mutating the shared (deliberately non-global) regex object. Dependency-free leaf — credential-shaped/-named checks stay in secretText.js/secretKeys.js. Pure; reads no environment.
secretKeys.js isSecretKey(key) — does a payload KEY name hold a credential (api_key/apiKey/API-KEY all normalize to apikey; a trailing Key/Keys counts; short names like auth/env match only whole). The key-side half of the pair whose value side is secretText.js#scrubSecretTokens. Split out of services/userActions.js so lib/federationSafety.js can reach it; deliberate over-redaction (losing tokenCount beats shipping refreshToken).
eidoverseCreativeToolkit.js The documented creative toolkit for minds building Eidoverse vernacular content (#7459, wired end-to-end in #7627): a closed catalog of EIDOVERSE_CREATIVE_MATERIALS and EIDOVERSE_CREATIVE_MOTIFS (cosmetics — style-layer only) plus EIDOVERSE_CREATIVE_LAYOUTS (named generative placement algorithms — radial-ring/grid-plot/arc-row/grove-cluster). generateDistrictTemplatePlacement is deterministic and seeded (mulberry32, no Math.random, no AI call) so the same {layoutId, anchor, seed} always reproduces the same geometry — services/eidoverseFoundationLedger.js's recordEidoverseFoundation() replays it server-side to derive a district-template's body.placement, never trusting a caller-supplied one. buildDistrictTemplateAugmentOperations turns a placement into ready-to-submit eidoverse.augment spawn operations (the eidoverse.place-layout tool); buildDistrictTemplateFoundationDraft shapes a placement plus a material/motif choice into an eidoverseFoundationInputSchema-ready district-template input, keeping the generative substance in body and the material/motif cosmetics in style (the eidoverse.draft-foundation tool). describeCreativeCatalog() is the prompt-safe catalog projection, including each material's colorHex. Pure: no I/O, no clock, no provider calls.
eidoverseControllers.js Executable Eidoverse world controllers — the install schema and the sandboxed step boundary (#7456). eidoverseControllerInstallSchema / eidoverseControllerRecordSchema describe an install (a registry controllerId, a bounded config, a tickIntervalMs, and a deliverEffects flag that is FALSE by default, so installing arms bookkeeping and never a world verb). eidoverseRiddleActionSchema validates the fixed offer/guess/reveal action with an inspected expectedRevision. runControllerStep is the sandbox: it hands the controller JSON copies of its state and config, REFUSES a step that returns a Promise (an await is the shape every network/disk/AI-provider call takes, so the tick path is provider-free structurally rather than by convention), caps the state it may return, and validates its effects against a closed vocabulary — note (never leaves the ledger), say, and augment, which reuses eidoverseValidation.js's own world-verb operation schema. controllerTickDue / nextControllerTickAt are the scheduling math, measured from now so a machine that slept wakes to ONE tick and not a replayed backlog. summarizeControllerInstall is the prompt-shaped projection that keeps a 16KB state blob out of a mind turn; it surfaces derivedFrom, the edge an install adopted from a peer's foundation carries (#7626). Pure: callers pass now.
eidoverseFoundations.js Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). EIDOVERSE_FOUNDATION_LAYERS (runtime / baseline / vernacular, defaulting to vernacular so nothing is shared by omission) and layerPromoteRefusal; the record / input / candidate-envelope Zod schemas, where a foundation is { body, style } BY CONSTRUCTION — packaging carries body and drops style, so an inheriting peer never receives its author's cosmetics, and styleLeakFindings REFUSES an unambiguously cosmetic key smuggled into body (spatial/asset keys stay allowed — they are a district template's substance). assayEvidenceFromVerdict folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. packageFoundationCandidate and verifyFoundationCandidate are the one gate seen from the sending and receiving sides, over a content-addressed fingerprint hashed from the payload AS SENT; federation safety comes from federationSafety.js. summarizeFoundation is the prompt-shaped projection of a ledger record (layer, identity, assay outcome, whether a candidate exists) that keeps the local style layer and the packaged envelope out of a mind turn, and detailFoundation is its read-ONE counterpart, adding the body and disclosure the list deliberately omits (#7626). eidoverseFoundationTargetSchema + foundationLedgerKey are how a caller NAMES one record — { id, originInstanceId }, where the origin addresses a local copy of a peer's foundation without making the internal peer:<origin>:<id> storage key user-typeable. planFoundationAdoption decides, per kind, what ADOPTING an inherited foundation means: a controller yields a disarmed install of the shipped controller its body names plus a derived-from edge, while schema / affordance / district-template are refused by name rather than silently succeeding. Pure: callers pass now. derivedContributionId({ kind, id, body }) and controllerDefinitionIdFromBody(body) derive the assay binding label from the record itself, so neither an author nor a sending peer can name it (#7625); they live here rather than beside the sandbox that replays the body because the sandbox reaches this module through the creative toolkit.
eidoverseFoundationSandbox.js Derives the agent-free resilience-assay sandbox for a foundation FROM ITS OWN BODY (#7625), closing the hole where the promote gate replayed whatever module the author named in a free-text contributionId. foundationSandbox({ kind, id, body }, { findControllerDefinition }) returns the { id, createSandbox, invariants } contribution runResilienceAssay() consumes, or a reader-facing refusal. One derivation per declared kind: controller replays the shipped definition named by body.controller.definitionId against THIS INSTALL'S body.controller.config (not upstream's exampleConfig); district-template requires body.placement to reproduce from its own layout/anchor/seed through generateDistrictTemplatePlacement and hands the body to the harness as the projection source; schema/affordance are replayed by the declarative interpreter over EIDOVERSE_DECLARED_FIELD_TYPES, which refuses an affordance recorded as prose rather than as { reads, writes } over declared fields. The binding label both the packaging side and a receiving peer re-derive is computed by derivedContributionId in eidoverseFoundations.js, which declares the schema that carries it (and which this module would otherwise import in a cycle, via the creative toolkit). Executes only code PortOS ships; no caller-supplied path is ever resolved. Pure apart from the injected definition lookup.
eidoversePort.js EIDOVERSE_PORT (8940) — the Eidoverse Worlds HTTP port as a dependency-free leaf (#8901), so services/managedVisitorHost.js can default to it without pulling in the heavy services/eidoverse.js graph (os/path/spawn/git/apps). services/eidoverse.js re-exports it rather than declaring its own copy.
eidoverseObservation.js Pure observation-first discovery report for the Eidoverse (#7457) — the read behind eidoverse.observe. buildEidoverseObservation turns already-collected snapshots (world signals, the install's RESOLVED design districts/includes, the foundation ledger, summarized controller installs) plus the previously persisted visit marker into { report, marker }: districts as places a mind can describe, peers keyed to the foundations inherited through each, a peer contribution's origin/arrival instances, controllers filtered to the ones actually failing, and a changes diff against the last visit. Places come from the recipe rather than a constant, so a mind never names a district a later design version renamed; an unreadable source stays null and a recipe-disabled one reports disabled, neither collapsing to 0; a first observation reports firstObservation rather than declaring a settled world new; and places diff on status flips only so routine signal churn never becomes noise. Scalar-vs-list source shape is shared with the projection via EIDOVERSE_SCALAR_SOURCE_KEYS. Pure: the caller passes observedAt and decides whether to commit the returned marker.
eidoverseWorldDesign.js Immutable Eidoverse World Design V1/V2/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons.
eidoverseWorldLabels.js The comp.label component PortOS attaches to every entity it projects into Eidoverse (eidoverse-worlds#5), so a rendered building says what it represents instead of only naming its decorative model. buildEidoverseLabel(component, alias?) reads one already-built comp.portos payload and returns {name, description?, visibility, offset?} — district and world-identity landmarks always visible, live indicators labelled nearby, path markers inspect-only so a walkway cannot bury the district it leads to — and null for anything not managedBy: 'portos', so a caller cannot label somebody else's entity. Names and descriptions are built from PortOS's own vocabulary (district label, kind label, resource category, coarse status, freshness) plus an opaque hashed resource ref for disambiguation, never from record contents, machine identity, addresses, or filesystem paths — the append-only world log is the strictest privacy boundary PortOS writes to. Also owns bounded opaque-key alias normalization and V1 renderer capability parsing; aliases are explicit opt-in names and are never inferred from private records. Owns safeWorldText, the one control-character/length sanitizer shared with services/eidoverseWorldProjection.js so a component field and the label built from it cannot disagree about what is safe. Pure.
eidoverseWorldSignals.js Pure raw-source-to-signal shaping: buildEidoverseWorldSignals, stable opaque host/peer IDs, storage and Jira aggregates; optional local-observation reason metadata and the closed EIDOVERSE_ATTENTION_REASON_CODES vocabulary; no service reads.
errorHandler.js ServerError + asyncHandler middleware, plus sendErrorResponse/buildErrorEnvelope for the standard { error, code, timestamp } body outside a handler's catch.
extensionErrors.js isExtensionError(payload) — true when a client error report came from a browser extension's injected content script (extension URL scheme in source/stack/message, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by services/clientErrors.js to keep un-actionable extension noise out of the Review Hub and out of the 1/sec throttle slot, where it would displace real errors. Re-exported by client/src/lib/extensionErrors.js, so both sides classify identically.
fetchErrorChain.js describeFetchError(err) flattens a fetch rejection's whole cause chain (depth-bounded, cycle-guarded) into one searchable code: message string — undici reports every network failure as the same opaque TypeError: fetch failed with the real reason nested inside, so a classifier reading only err.message misjudges every one of them. isReplayableConnectionError(err) is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via fetchWithTimeout's shouldRetry; it deliberately EXCLUDES timeouts, which broader classifiers like ollamaManager's isTransientPullError include.
isoWeek.js ISO-8601 week identity — the single source of the YYYY-Www week id. getWeekId(date) keys on the ISO week-numbering year (the calendar year of that week's Thursday), not date.getFullYear(), so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also isoWeekParts, getIsoWeekNumber, getIsoWeekYear, parseWeekId (null on garbage), weekStartFromWeekId (local-midnight Monday of that id; null on garbage), and isoWeeksInYear(year) (52, or 53 in a leap-week year). Shared by weekly digest filenames.
snapshotChecksum.js The two snapshot-checksum flavours a sync category can want. snapshotChecksum(data) hashes JSON.stringify — insertion-order SENSITIVE, correct only where the getter already canonicalizes its own ordering (dataSync.js, digital-twin-sync.js). canonicalSnapshotChecksum(data) hashes canonicalStringify, so two converged machines hash identically regardless of the order they learned the data (peerUsage.js, whose payload is a map keyed by wire-supplied instance ids). Picking the wrong one is not a crash — it is two synced peers whose checksums never match, which the sync UI reads as "behind" forever.
lwwTimestamp.js Last-writer-wins timestamp comparison for cross-instance sync merges. parseTsMs(s) (Date.parse → epoch ms or null), compareNewerWins(candidate, incumbent) (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), compareEarlierWins(a, b) (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by mergeMediaCollectionsFromSync / mergeAuthorsFromSync etc.
syncManifest.js Wire contract for the snapshot-sync MANIFEST leg — the fix for a category that is always dirty AND a map of per-instance slots (usage), where one instance advancing dragged every other instance's digest across the wire. isManifestEnvelope(value) validates a { data: { instances }, checksum } response (a legacy peer that 404s the endpoint fails it, and the puller falls back to the whole snapshot); diffManifestSlots(remoteInstances, localInstances) returns the sorted slot ids whose REMOTE LWW stamp is strictly newer than ours — exactly the slots worth fetching. Comparison goes through lwwTimestamp.js, so a tie breaks to what we already hold. Consumed by syncOrchestrator.syncDataCategoryFromPeer; served by dataSync.getManifest.
mapWithConcurrency.js Generic bounded-concurrency async mapper that preserves input order while capping in-flight work.
markedSection.js Marker-delimited section replacement (pure). buildMarkers(id) → { start, end } HTML-comment marker pair; replaceMarkedSection(content, body, markers) splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); extractMarkedSection / hasMarkedSection read it back. Powers the daily-log activity-digest auto-drafts (#2155) via brainJournal.upsertAutoSection().
objects.js Object utilities — deepMerge (recursive merge w/ array replacement), isPlainObject (non-null, non-array object guard for JSON / LLM payloads), POLLUTING_KEYS (shared __proto__/constructor/prototype denylist for sanitizers), bucketFor(map, key, init) (get-or-create a bucket for an externally supplied key; null for POLLUTING_KEYS, hasOwn lookup), canonicalStringify (recursive sorted-key JSON serialization for cross-machine content hashing), isEmptyScalar (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate), boundedByJsonChars (longest prefix of a list whose JSON encoding fits a character budget — the shared prompt-catalog truncation loop).
openapiSpec.js Builds two OpenAPI 3.0.3 documents: the Settings-controlled exposed public surface and the complete internal HTTP inventory. Detailed operations reuse canonical Zod contracts; generated operations are visibly labeled rather than claiming unmodeled schemas.
openapiDowngrade.js OPENAPI_VERSION plus toOpenApi30Schema / toOpenApi30Operation, which rewrite Zod's draft-2020-12 output (null unions, numeric exclusive bounds, const, tuples, propertyNames) into the OpenAPI 3.0.3 dialect. Apply ONLY at the OpenAPI document boundary — the AsyncAPI payloads, CoS provider tool definitions, and tool resource read the same schemas as plain JSON Schema, where these rewrites silently widen bounds and drop null branches.
orchestrationProfile.js Orchestrated CoS execution (#5992) — ORCHESTRATION_MODES / ORCHESTRATION_ROLES (architect, implementer, reviewer), normalizeOrchestrationProfile / normalizeOrchestrationMode, isOrchestratedTask / roleAssignment (both inert on a direct task, so a stored profile stays opt-in), the six-part SPEC_PARTS contract a delegated context-free lane needs, plus parseReasoningDirective / resolveStepEffort (spec rung → role default → run effort; an unsupported rung is an error, never a silent downgrade).
apiToolResource.js Builds the minimized semantic tool resource served at /api/api-docs/tools.min.json — only x-portos-tool-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary.
asyncApiSpec.js Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status.
mergeGateAudit.js Pure verdicts for the post-merge gate audit (#12549): assessMergeGate({repository, headSha, mergedAt, checks, history, heldLease, receipts}) flags a merged claim PR that held no merge-admission lease at mergedAt (leaseCoversMerge) or whose head had a check not completed-green before it (classifyHeadChecks over foldHeadChecks, which dates every run attempt and status post against mergedAt so a later rerun or re-posted context cannot rewrite what the merge saw), and exempts a head the pending-merge coordinator marked merged (receipts; awaitsCoordinatorMark names the unmarked window). null checks = forge unreadable, never a verdict. The forge reads and recovery filing live in ../services/mergeGateAudit.js.
mergeGateContract.js buildManagedGithubMergeScript() emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. MANAGED_WORKTREE_CLEANUP_CONTRACT and its MANAGED_WORKTREE_COMPLETION_HANDOFF share head-pinned, checkout-preserving merge and ownership-gated removal of a merged clean checkout, with no archive copy. mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen}) decides whether a completing run actually owed its own PR merge — only the INLINE (git/gh) prompt renders a Merge Gate section, so a /do:pr run is inert here; resolveMergeGateVerdict({prProbe, summary}) classifies a run that did (merged / merge-handoff-queued / no-pr-action / leave-open-stated / needs-reprompt) from the PR's live state and the agent's own sentinel text; summaryStatesLeaveOpen and buildMergeGateReprompt are its text-matching and corrective-prompt helpers. buildAutoMergeHandoffInstructions(prRef) requires delivery ownership until confirmed merge or an exact-head server receipt accepted for measured CI backlog. hasHealthyAutoMergeRequest(pr, now?) bounds pending handoffs to one hour with readable, non-failed CI; prProbe also verifies the local head matches GitHub before accepting autoMergeEnabled or a pending-merge receipt (mergeHandoffQueued). Pure — the PR lookup lives in ../services/prProbe.js, the re-prompt delivery in agentTuiSpawning.js.
preflightPlan.js The programmatic phase of a user-triggered pipeline run, as renderable data. preflightStepPlan(taskType) is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); createPreflightState opens it, applyPreflightStep advances one step and closes every earlier unfinished one, finalizePreflight closes it handed-off/programmatic/nothing-to-do/failed/interrupted (first close wins), and preflightHeadline names where the run is. Persisted onto a task card by services/preflightTaskCard.js and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure.
prDisposition.js resolveAppPrCompletion(app, metadata) supplies the reviewed automatic merge default for new tasks while preserving explicit managed-app choices and legacy review toggles. PR_MISSING_CATEGORY shares the missing-PR verdict between finalization and cleanup. resolvePrCompletion(metadata) resolves the explicit review-then-merge / merge-on-green / leave-open policy, with legacy reviewLoop fallback; explicitPrCompletion(task) retains only explicit authority (defaults never release a handoff); leavesPrForHuman(task) + PR_STAYS_OPEN_TASK_TYPES keep JIRA hand-offs open; prStaysOpen(task) is the combined policy-or-human verdict. Shared by the agent prompt builder and agentWorktreeCleanup so both halves agree. resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified}) → a PR_CREATION tri-state (never / if-missing / always) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing gh pr create.
recoveryMergeTarget.js repositoryCleanupMergeTarget(task) → the { url, branch } parent PR a repository-cleanup recovery was filed to land, or null (#12251). A claimed target only: merge admission also requires the completed parent's server-written backlink to that exact task, branch and PR.
prHandbackPolicy.js Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. resolvePullRequestWriteAccess(pr) reads isCrossRepository/maintainerCanModify into a PR_WRITE_ACCESS reason, failing closed on an unknown head-repository relationship; resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted}) returns a PR_HANDBACK verdict — remediate (PortOS pushes the fixes and lands it), assign-opener (the PR goes to its author queue), or none. A deferred or unanchorable review never becomes an agent work order. Pure.
prReviewContent.js The one definition of the external pull-request content PortOS screens. screenedPullRequestContent(pr, diff, commits?) builds the contributor-authored surface — title, description, commit log, unified diff — and screenedPullRequestFingerprint(pr, diff, commits?) hashes it to a stable identity for one head commit, returning null when the commit log is missing rather than matching by omission. Both take the PR row, because the pr-reviewer preflight STAMPS that fingerprint and the coordinator RECOMPUTES it from a fresh forge read before it reviews, rebases, or merges: when the two hand-written field projections drifted apart, every approved review was dropped. Never rebuild either shape at a call site. Pure.
prReviewReport.js Owns the structured PR-decision contract end to end: PR_REVIEW_DECISION_CONTRACT is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, normalizeReviewReport bounds what comes back, reviewReportText hands every model-authored string to the abuse scan, and renderReviewBody/renderFinding turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to path:line, test-evidence bullets (TEST_EVIDENCE_STATUSES keeps fail for "the change is broken", with expected-fail and blocked for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by MAX_REVIEW_BODY_CHARS, dropping whole low-priority sections instead of truncating mid-sentence. Pure.
repoStateExpectations.js Post-completion repo-state audit, pure half. resolveRepoStateExpectation({...}) answers whether one finished worktree agent should be audited — naming every not-audited path via REPO_STATE_SKIPS (a failed run is preserved for its retry; a review-loop follow-up or pr-watcher pending merge still owns the branch) — and returns just staysOpen + prExpected, from which classifyRepoStateIssues(expectation, observed) derives every check into REPO_STATE_ISSUES codes. Observations are tri-state: null ("could not ask") never produces an issue. repoStateVerificationEnabled(app) reads the per-app verifyRepoStateOnCompletion switch (unset = on). Probing + remediation live in services/agentRepoStateVerification.js.
shellCd.js buildCdCommand(path, shell) + formatShellCommandLine(command, args, shell) + detectShellFlavor(shell, platform?) + quoteForShell(value, flavor, position?) — build cd and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (cmd.exe → Windows-escaped double quotes, PowerShell → doubled single quotes with & for a quoted command token, everything else → POSIX shellQuote). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare cd does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. formatShellCommandLine joins a command + argv into one quoted line and is shared by agentTuiSpawning.js#buildTuiSpawnConfig and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. Renders the LINE only; the Enter byte that submits it is SUBMIT_KEY in tuiHandshake.js.
shellExit.js buildRunThenExitCommand(commandLine, shell) — "run this CLI, then close the shell with its status", in the dialect the session speaks. An agent TUI shell exists only to host one CLI and must die with it. The POSIX cmd; exit $? was applied everywhere and is actively wrong off-POSIX: in PowerShell $? is a BOOLEAN, so exit $? reports success as 1 and failure as 0 (inverted) — use $LASTEXITCODE, pre-seeded to 1 so a command that never ran still exits non-zero; in cmd.exe ; is an argument separator, so the CLI is handed ;/exit/$? as arguments — use & exit. Verified against node-pty on Windows 11 for pwsh 7, PowerShell 5.1 and cmd.exe.
shellLivenessProbe.js buildLivenessProbeCommand(shellPid, platform?) + parseLivenessProbeOutput(stdout, shellPid) + shellHasLiveChild(shellPid, opts?) — platform-aware process-liveness probe for a launched TUI command in a persistent PTY shell. POSIX (ps -Ao ppid=) / Windows (Get-CimInstance Win32_Process | Select-Object -ExpandProperty ParentProcessId via PowerShell). Resolves true (assume alive) when the probe fails or cannot run.
runnerAgentLiveness.js CoS Runner GET /agents liveness. Presence in the runner's handle map is not proof of life: runnerAgentLivenessFields produces processActive + liveness (pty from TUI onExit bookkeeping, pid from a CLI probe) so Windows ConPTY pid: 0 no longer reports every TUI as dead; runnerEntryShieldsRunningRecord is the corroboration gate both zombie/orphan sweeps use before a listing can keep a durable running record.
shellQuote.js shellQuote(value) — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll.
shellReadinessProbe.js buildReadinessProbe(nonce, shell) — the round-trip "can this shell actually run commands yet?" probe createShellSession's waitForPromptReady sends and watches for, in the dialect the session speaks: POSIX printf '%s\n' 'PORTOSRDY''<nonce>' (unchanged), PowerShell Write-Output ('PORTOSRDY' + '<nonce>'), cmd.exe → null (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe.
sidecarProcess.js runSidecarProcess({bin,args,env,signal,onStage,onProcess}) + parseSidecarResult(stdout) — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → canceled, non-zero exit → stderr-tail reason). Used by pipeline/musicGen.js (all music backends) and audioMidiTranscription.js (MuScriptor).
slashdoCatalog.js The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — SLASHDO_WORKFLOWS ({command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}), getSlashdoWorkflow() (the allowlist gate for POST /api/cos/tasks/slashdo), SLASHDO_COMMAND_NAMES, slashdoWorkflowsForApp(isSwiftApp), SLASHDO_APP_TYPES, and the two run-shape postures WORKFLOW_OWNS_ITS_OWN_GIT (commit-shaped) / WORKFLOW_REPORTS_NO_CODE (report-shaped — carries worktreeChangesExpected: false so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (taskTemplates.js), and the route allowlist, replacing two catalogs that had drifted. client/src/lib/slashdoCatalog.js decorates this list with button styling rather than restating it.
slashdoInvocation.js Resolves how a bundled slashdo workflow is invoked on a given host CLI. resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode}) → {command, args, style, invocation, skillName} for the three shapes slashdo's installer produces (slash-namespaced /do:x for Claude Code, slash-flat /do-x for OpenCode, skill — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus buildSlashdoSection(resolved, body, {bodyPath, reviewWith}) (pure renderer; the caller loads the body via loadSlashdoFile. With a staged bodyPath it emits a filesystem pointer for deferred bundles or bodies over SLASHDO_INLINE_BUDGET_CHARS (24,000)), unreachableReviewerIncludes({reviewers, usernames}) → the reviewer-variant lib includes a run can never reach (the skipIncludes set for loadSlashdoFile; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), SLASHDO_REVIEWER_INCLUDES/SLASHDO_REVIEWER_INCLUDE_NAMES, slashdoSkillName, isValidSlashdoCommand (the one definition of the safe bare-command shape, also gating the Zod schemas), agentOwnsPrWorkflow({providerType, leanMode}) — a strictly WEAKER question than typing a slash command: any local cli/tui harness that is not a lean --bare session drives its own commit → push → PR → review → merge (#3733), with PR_OPENED_BY (agent-slashdo / agent-inline / portos) naming WHO opens a run’s PR per the prompt it was given (stamped as metadata.prOpenedBy by promptOpensOwnPr, services/promptSections/completion.js) and resolvePrOpenedBy({persistedPrOpenedBy, persistedOwnsPrWorkflow, …}) reading it back for a completed agent — mapping both the legacy #3733 ownsPrWorkflow boolean and a pre-#3733 record with no stamp at all; oversizedBodyPointer(bodyPath, body) (the shared "it is on disk, go read it" line); resolvePrOwnership({task, isTruthyMeta, persistedPrOpenedBy, persistedOwnsPrWorkflow, providerId, providerCommand, leanMode}) → {taskOpenPR, prOpenedBy, agentOpensOwnPr, prClaimExpected} — the persisted-first, task-shape-aware ownership verdict plus provider descriptor that both in-process spawners (TUI finish(), direct-CLI close) hand to runSpawnerCompletionCleanup, so the ownership question and the cleanup acting on it cannot disagree; and canTypeSlashCommands() — the single predicate behind agentPromptBuilder.js's completion-workflow gates (can this session TYPE /do:pr / /simplify?), which reads resolveSlashdoStyle's assumeClaudeWhenUnknown posture because the spawners resolve a blank command to claude. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered /do:x string.
slashdoLoader.js Shared slashdo renderer adapter: loadSlashdoBundle(cmd, {stripFrontmatter, skipIncludes, defer}) returns an entrypoint and supporting files using the bundled transformer; loadSlashdoFile returns a self-contained command; loadSlashdoLib expands explicit reads for legacy recipes without traversing see-also links. writeResolvedSlashdoBody(cmd, body, {files}) stages immutable content-addressed bundles under PATHS.slashdoResolved, with relative library paths and the entrypoint written last. Missing required references fail dispatch rather than silently removing workflow gates.
singleFlight.js createSingleFlight() → run(key, fn) — keyed in-flight coalescer: concurrent calls for the same key share one fn() execution and result; the slot auto-clears on settle. createSingleFlight({ exclusive: true }) also keeps different keys from overlapping: a different key waits for the in-flight call, then joins or starts its own (used where the work must never run twice at once, such as starting a local runtime). Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by services/promptRunner.js's fallback mark-and-pick, lib/managedDaemon.js's on-demand wake, and services/ollamaManager.js's starts.
staleWhileRevalidate.js createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? }) → read(key, produce, { wait }) / clear(key?) — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). wait: 'fresh' bypasses and blocks, 'cached' (default) blocks only on a cold cache, 'never' returns the PENDING symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by providerUsage.js (TUI scrapes) and claudeCodeUsage.js.
staticImportGraph.js Static ES-module import scanning for structural test guards. staticImportSpecifiers(file) → every specifier a file statically imports (verbatim, source order); staticImportClosure(entry) → {files, packages} for the whole reachable graph; buildStaticImportGraph(rootDir) → Map<relPath, relPath[]> of one directory's internal static edges (recurses into subdirectories, skips .test.js); listModuleFiles(rootDir) → every non-test .js under a directory, keyed by /-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); findImportCycles(graph) → each cycle rendered as a.js -> b.js -> a.js (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); findImportCycleComponents(graph) → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); specifierMatchesPackage(spec, pkg) matches a package or any subpath; toModuleKey(relPath) is the one graph-key mint — always /-separated, because the keys are built two ways (entry-name concatenation vs path.relative) and Windows spells the second one with \, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — await import() is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by serviceImportCycles.test.js (the tree-wide cycle ratchet), agentImportCycles.test.js and twinImportCycles.test.js (per-cluster acyclicity) and spriteAnimationTracks.test.js (the request-validation graph reaches no sharp/ffmpeg).
progressChannels.js createProgressChannels({ label, describeKey }) — shared GET/POST progress channel lifecycle with late subscriber replay, idle reservation reaping, and one active stream owner per key.
sseUtils.js Per-job SSE stream helpers (imageGen + others) plus createSseRunner — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. dispatchTerminalEvent(jobId, sseSend, emitEvent) — dispatches a job's terminal SSE frame and its lifecycle event independently, each in its own try/catch, so a throw in one (a dead client's res.write, a throwing listener) can't suppress the other. createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? }) — the shared job-failure finalizer (idempotency guard w/ force escape hatch, slot-owner clear, dispatchTerminalEvent-backed SSE error frame + failed event, closeJobAfterDelay, plus a .canceled(job, jobId, slotOwner?) convenience) behind all six media-generation backends (imageGen/{agy,codex,grok}.js, videoGen/{grok,fal,reactor}.js).
streamAttachment.js streamAttachment(res,stream,{filename,contentType,failure,label}) — pipe a readable to a response as a file download. Sets the attachment headers plus X-Content-Type-Options:nosniff, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns failure via sendErrorResponse, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls stream.abort?.() so an upstream child process is torn down. Shared by routes/imageTo3d.js (GLB, full-mesh) and routes/backup.js (snapshot tarball).
streamBackpressure.js awaitWritableDrain(res) — park a streaming-response producer on the socket's next drain (or close) when res.write() returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by routes/ask.js (SSE) and routes/localLlm.js (NDJSON).
streamingSpawn.js runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?}) — run one command to completion and forward its stdout/stderr LINES to a hook, resolving { success, error? }. Never rejects (spawn error, non-zero exit, and timeout all resolve as success: false) because every caller is an install/setup flow running outside the Express request lifecycle, and the onLine hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so brew upgrade ollama exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by services/localLlm.js's package-manager installs and services/localRuntimeSetup.js's one-click daemon setup. splitRe is forwarded to the line readers — pass /[\r\n]+/ for a downloader whose progress bar redraws one line with a bare \r, or the stream goes silent for the whole download. isCancelled is polled once a second and SIGKILLs the child when it turns true (resolving {success:false, error:'cancelled'}) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. bufferedSpawn.js is the sibling for run-and-collect; use this one when live output IS the progress.
repoIntakeActions.js REPO_INTAKE_KEYS + normalizeRepoIntake(input) — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (malwareScan → /do:scan, learn → a repo-study review). Pure half of services/repoIntake.js (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link.
tombstones.js Generic timestamped tombstones ({ <keyField>, deletedAt }) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). normalizeTombstones / recordTombstone / clearTombstone / tombstoneTimestamp maintain the list; mergeTombstones unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; isTombstoned(list, key, createdAt) suppresses a record unless its own creation stamp is strictly NEWER than the deletion; pruneTombstones(list, records) drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); supersedingTimestamp(deletedAt) stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through lwwTimestamp.js, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. DEFAULT_TOMBSTONE_LIMIT (200) caps growth.
untrustedContent.js jevPolicyPatchSchema validates narrow scorer-management updates. Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. selectUntrustedContentProvider is the one provider+model selection rule (automatic selection skips an eligible provider that resolves no model; a pinned provider fails closed).
untrustedContentSources.js The ingress vocabulary alone — UNTRUSTED_CONTENT_SOURCES and PRIVATE_UNTRUSTED_CONTENT_SOURCES. Split out of untrustedContent.js (which reaches zod and node:crypto) so the browser can import it: the Abuse Guard panel offers exactly the sources the server screens, instead of restating them and drifting (#7680).
contributionSecurityPolicy.js Trusted host-control security policy and strict tool-free GitHub contribution assessment contract.
uploadLimits.js Single source of truth for upload size caps — JSON_BODY_LIMIT/JSON_BODY_LIMIT_BYTES (the express.json limit applied in index.js), MAX_BASE64_UPLOAD_BYTES derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), MAX_SCREENSHOT_BYTES. Mirrored client-side as JSON_UPLOAD_MAX_FILE_SIZE.
userActionTypes.js Closed vocabulary for the operator-action ledger (user_action_events, #5594 / #5596): USER_ACTION_TYPES (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), USER_ACTION_ACTORS (user / mind / schedule / system), and the isUserActionType / isUserActionActor predicates. recordUserAction (services/userActions.js) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on.
uuid.js v4() thin wrapper over the global crypto.randomUUID(). Import-free, so a leaf the browser imports may reach it without a Node built-in — importable, not browser-callable: randomUUID needs a secure context there, so client code mints through client/src/lib/uuid.js.
versionUtils.js compareSemver(a, b) — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (updateChecker.js) and the local-LLM Ollama update detector (localLlm.js). Inputs must be v-stripped.
workTracker.js WORK_TRACKERS/CONCRETE_WORK_TRACKERS/DEFAULT_WORK_TRACKER, workTrackerLabel, hostToWorkTracker, isGithubHost (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only isGithub gate), githubRepoSpec(origin) (host-qualified HOST/OWNER/REPO selector for gh --repo, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), forgeCliForTracker, isFileTracker (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), trackerToClaimTaskType, hostFromOriginUrl (subgroup-tolerant, ssh-alias-aware host parse), pure resolveWorkTracker({configured,host}), async resolveAppWorkTracker(app) — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting 'auto' to the git origin host and checking the gh and glab host configs for otherwise-unmatched hosts. Async resolveRepoForgeTarget(repoPath) — the ONE definition of "which forge can we query for this checkout", returning { forge, fullName, repoSpec, apiHost } (enterprise-aware gh --repo selector for GitHub; repoSpec: null for GitLab, which glab resolves from its cwd) or null for a non-forge origin; shared by issueReconcile.js and appIssues.js. Async resolveAppForgeTarget(app, {repoPath}) — the composed resolveAppWorkTracker + resolveRepoForgeTarget for callers holding the managed-app record, returning { tracker, target } with the app's github/gitlab pin threaded in as preferredForge (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the {trackerInstructions} prompt block shared by TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): TRACKER_FILING_PRESETS (per-task-type PLAN.md id prefix / legacy forge-title marker / labels / body requirements — PLAN.md ids remain; old forge markers are read only for de-duplication), TRACKER_FILING_TASK_TYPES (derived from the presets, so a gated type always has wording), extraIssueLabels / formatForgeCategoryLabelFlags (category + metric labels + plan as repeated --label flags), and formatTrackerInstructions(tracker, options) which renders plan/github/gitlab/jira blocks (forge titles use plain human-readable text and issue numbers are IDs; PLAN.md IDs retain their lowercase kebab-case, prefix, maximum-length, and uniqueness rules; GitLab inventories use the paginated API; free-form titles and multiline bodies use file-based transport). Consumed by the claim-work router in cosTaskGenerator.js, referenceRepos.js, and routes/apps.js. Also repoIssueUrlBase(target) — the browsable issue-tracker base URL for a resolved forge target (/-/issues on GitLab, /issues elsewhere), so a caller stamps a finished base onto its record and nothing downstream has to classify a host.
eidoverseProxyRoutes.js Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on :5555 (/eidoverse-host prefix strip and root routes like /ws / /version while the host is active). Shared by services/eidoverseProxy.js so the main server and the optional :5563 bridge stay in sync with eidoverse-worlds server/routes.ts.
workspaceRoots.js Shared allow-list for routes that take a caller-supplied filesystem path. isWithinAllowedRoots(realPath) is the single complete test — on Windows it also allows any lettered non-system drive (D:\code), which appears in no root, so never render ALLOWED_WORKSPACE_ROOTS as "the directories you may use". outsideAllowedRootsMessage(realPath, { field }) formats a redacted server-only diagnostic with the rejected realpath and every checked root. Also ALLOWED_WORKSPACE_ROOTS (defaults + PORTOS_WORKSPACE_ROOTS, split on the platform path delimiter — ; on Windows — and symlink-resolved), isWithinRoot(resolvedPath, root) (separator-safe containment), and WORKSPACE_ROOTS_CONFIGURED (true when the operator set the env var — lets a permissive-by-default route like routes/detect.js opt into confinement). Defaults cover home plus wherever the platform mounts secondary volumes: /tmp + /Users + /Volumes + /mnt + /media + /opt on POSIX; home + the temp dir plus the non-system-drive rule on Windows, where those POSIX literals would resolve to whatever drive the process happens to be on. Used by routes/commands.js, routes/scaffold.js, and routes/git.js (always scoped) and routes/detect.js (scoped only when configured).
zodCompat.js Zod 4 compatibility helpers. partialWithoutDefaults(objectSchema) — like .partial() but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. Also home to the provider-reference zod forms (#7564) — providerRefSchema / providerRefFieldSchema (a preset id OR a composite harness.method@service[+bootstrap], per providerRef.js) and presetProviderIdSchema (preset-only) — because cosValidation.js needs them and must not import validation.js.

Test support

Module Purpose
browserSuiteGate.js probeChromeH264(path) runs the H.264 probe as an owned, deadline-bound child (own process group, SIGTERM→SIGKILL ladder awaiting close) and resolves { ok } or { ok:false, cause } — missing-executable, codec-unavailable, probe-timeout, teardown-failed (answered, then exited nonzero: never trusted, never a missing codec), no-answer; describeH264Probe is its path/PID-free one-liner; chromeWithH264(path) (async) returns the path only when that Chrome decodes H.264, null when the executable or codec is genuinely absent, and { probeFailure } when the probe itself failed (reported by browserSuiteCanRun as a lifecycle failure, not a missing prerequisite); browserSuiteCanRun(label, prerequisites) is the canRun guard for the cross-workspace *.browser.test.js suites (Chrome + ffmpeg + the client bundler). Pass { name: discoveredValue }; a falsy value is missing. Returns false with a visible skip log locally, but throws naming the missing prerequisites when PORTOS_REQUIRE_BROWSER_SUITES is set; browserSuiteBlockReason(prerequisites) is that verdict alone (the same wording, or null) for a caller that only reports, such as scripts/pregate.js — the flag the CI database job sets for the browser suites the planner selected (#10312). resolveTestChrome(env) is the one Chrome candidate list (CHROME_PATH, Playwright's bundled Chromium, then the macOS app and the Linux package paths) shared by the suites, the pregate probe and the test memo's tool keying, and resolveClientBundler(repoRoot) the one client bundler probe (resolved Vite, React plugin and Tailwind PostCSS paths, or undefined when any is missing; non-MODULE_NOT_FOUND errors throw) (#12293).
dbTestGate.js requireDbOrSkip(label, dbReady, reason) keeps a missing local test database as a visible skipped suite, but throws when PORTOS_REQUIRE_DB is set so CI cannot pass after DB-backed suites disappear.
gitTestRepo.js Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then fs.cp into a fresh temp dir. makeGitSandbox({ origin }), attachBareOrigin(scratch, repo), materializeGitRepo(dest), destroyGitSandbox, plus SKIP_HEAVY_INTEGRATION (VITEST_FAST=1). resetGitSandbox({ scratch, repo, initialHead }) / resetGitWorktreeSandbox(repo, initialHead) restore a sandbox in place (branches, worktrees, remote) so a describe can build one sandbox in beforeAll and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs assertTempPath first, so a path outside os.tmpdir() throws instead of git init-ing or rm -rf-ing a real checkout (#4554). Fixture-local maintenance/GC detachment is disabled so awaited Git operations retain their writers through teardown. Primary fixtures pin core.autocrlf=false and core.eol=lf so copied/materialized checkouts preserve exact text bytes under host CRLF defaults. Still real git — just not rebuilt from init+commit+push in every beforeEach.
mirrorParity.js Source-extraction and comparison primitives for declaration-level contract tests: the vendored aiToolkit/ copy of TOOL_USE_RE (localModelHeuristics.mirror.test.js), and the bootstrap sequence's body assertions (bootstrap*.test.js). A pure module the browser needs is imported by the client rather than mirrored, so no client↔server copy test should need these: stripCommentsAndNormalize (so per-side commentary may diverge but logic may not), extractDeclaration(src, name) (balanced {}/()/[] walk over function / async function / const), and compareDeclaration(serverSrc, clientSrc, name). Use these instead of hand-rolling a brace-walker per mirror. Pure — no vitest import — so callers own the assertions.
mockPathsDataRoot.js Best-effort bounded recordTempRootOwner sidecar observations and shared Vitest helpers for PATHS.data → temp dir, no-peer record creation guards, deterministic federation-identity doubles (mockTestIdentity), and ownTestBodies(it) → { it, drain }, which owns each test body so teardown can await drain() before removing a fixture root — a body left running by Vitest's fail-fast cancellation otherwise recreates the removed root (test temp leak:).
settingsTestUtil.js bindSettingsFile(dataRoot) → writeSettingsFile/mergeSettingsFile: direct settings.json disk writes that also drop the getSettings() read cache (dynamic-import reset) so a stale cache can't survive a bypass-save() write.
runtimeEnv.js isTestRunner() — NODE_ENV=test or the VITEST env var, so a run that dropped NODE_ENV is still armed. isVitestRunner() narrows to a real Vitest worker; isSmokeBoot() (SMOKE_BOOT_ENV) marks the server boot smoke, whose boot skips schedulers, agent recovery, and external integrations (#8343). Dependency-free and deliberately apart from db.js, which used to own it: the lowest-level file primitives need the same answer and must not pull in pg, and the many suites spelling vi.mock('../lib/db.js', () => ({ query })) used to strip it out of the graph for every other consumer.
testDataIsolation.js Runtime backstop against a test WRITING into the install's real data/ tree — the filesystem analogue of db.js's row-write guard. isInsideRealDataRoot(path) canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with pathSafety.js#isPathAtOrInsideDir, so a .. climb, a relative path, a data-archive sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through dataRoot.js rather than read from PATHS, so a suite that redirects PATHS.data to a temp root can't also redirect the guard. assertNotRealDataWrite(path, operation) throws under the test runner from atomicWrite, the guarded wrappers in fileCore.js (writeFileGuarded, appendFileGuarded, copyFileGuarded, rmGuarded, unlinkGuarded, createWriteStreamGuarded), and collectionStore's record delete; assertNotNewRealDataDir(dir) is the create-only variant ensureDir uses, since mkdir -p on an existing directory mutates nothing. Inert outside the runner — the isTestRunner() check precedes every syscall. Services mutating files under data/ route through these guarded wrappers. Closes the write half of the bug class testDataIsolation.guards.test.js covers statically and the two-run probe covers for reads (#6176, after #6171, #6203).
testHelper.js Test helpers: request() (supertest-style HTTP) + mockJsonResponse/mockTextResponse (fetch Response mocks with .text(), .json(), and a headers.get content-type), startLoopbackServer(app)/closeLoopbackServer(server)/waitForAbort(signal) for tests that need a real socket (raw disconnects, SSE streaming) that request()'s run-to-completion fetch harness can't model, plus the source-scan pair collectServerSources() / readServerSource(rel) (and SERVER_DIR) used by the whole-tree guard suites — spawnCwd.test.js (#3193) and cliChildEnv.test.js (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: posixPath(v) normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and resolveTestPython() returns an interpreter that actually runs, probing by execution because Windows ships a python Store-alias stub that exists but fails; null when there is none, for describe.skipIf; pinPlatform(value) pins process.platform and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: PY_TEST_TIMEOUT_MS (vitest per-test, passed as it()'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s testTimeout on a contended full-suite worker) and the strictly smaller PY_SUBPROCESS_TIMEOUT_MS (every execFileSync spawn's own timeout, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins).

| fableLoomShots.js | Short-shot grouping, spoken-dialogue timing estimates and 5–10 second render validation. | | eidoverseSceneInspection.js | Typed bounded local scene query, sequence-checked authored geometry view, safe asset references, and conservative world AABBs with explicit completeness and unknown extents. | | eidoverseCityLayout.js | Native halls, rooftop landmark clearance and plinths, curated furniture, visitor chambers, and ordered signal bays for PortOS Commons. | | eidoverseCitySurface.js | Deterministic GLB island scenery, pedestrian paths, gathering terraces, and physical district signs, stored through Eidoverse's content-addressed upload API. | | eidoverseIslandLandscape.js | appendEidoverseIslandLandscape appends deterministic coastline, ocean, and distant mountain-island geometry to the Commons asset. |

| localModelSafety.js | localModelSafety, ESTABLISHED_MODEL_PUBLISHERS, REVIEWED_SECURITY_MODELS — reduced-safeguard warnings and dated publisher/build provenance; never a malware-free certification. |

| privateSecurityPolicy.js | Private assessment task identity, immutable delivery posture, and report schema. |

| privateSecuritySandbox.js | Loopback-only local-provider gate and macOS Seatbelt launch with isolated CLI home and scratch workspace. |

| requestOrigin.js | remoteRequestHandler, markRemoteServer (covers the Socket.IO handshake and upgrade a handler never sees) and isRemoteRequest preserve remote transport identity across a localhost hop without trusting client headers; the host-control gates refuse a marked request as non-local. |

| cosFederationPolicy.js | isMachineLocalCosTask excludes private assessments and explicitly machine-local tasks and agent archives from federation. |

| creativeDirectorVideoReview.js | retainVideoCuts preserves rendered cut references on invalidation. Video checkpoint fingerprints, owner-only review actions, feedback, and targeted revision invalidation. | | creativeDirectorVideoCompiler.js | compileVideoArtifact and validateVideoShot — pure timed-shot/source-reference compilation and pinned-backend compatibility shared by Creative Director project mutations and Video execution preflight. Storage, history and approval remain with their existing owners. |

| providerTypes.js | Pure shared isCliProvider, isTuiProvider, isApiProvider, isProcessProvider, and type-gated isClaudeHarnessProvider predicates. |

| videoTimelineFades.js | Browser-safe fitFades() proportionally fits a fade pair to its visible duration. Shared by timeline normalization/export and the editor preview/trim controls; legacy import paths re-export it. | | videoTimelineSourceSpans.js | Browser-safe source-span resolution for the video timeline: resolveClipSpan (trim clamped to the history clip length, fades refit), resolveStillFades, resolveAudioSpan (bed offset/length/fades fit to the real file length; an unknown length keeps the authored slice), historySourceDuration, MIN_MEDIA_SEC. One implementation for the ffmpeg export (resolveTimeline) and the editor preview, so both play the same timeline. | | voiceEcho.js | Pure voice-echo detection helpers — tokenization, trigram building, thresholds shared by server and client echo gates. | | voiceEngines.js | Shared TTS engine IDs, display metadata, supported-engine set, persisted configuration keys, and retired TTS config migration. | | voiceModelAssets.js | Completion contract for downloaded voice model assets (Whisper .bin, Piper .onnx + .onnx.json). inspectVoiceAsset(kind, path) is the read-only readiness check (verified / unverified / incomplete / missing — stat plus one small JSON read, no hashing or network); verifyVoiceAssetHashes and writeVoiceAssetReceipt are the script-side halves that re-hash and record the .portos-complete.json receipt after promotion. isManagedVoiceAsset separates setup-script-owned files from user-supplied ones. Shared by voice/bootstrap.js, voice/health.js and scripts/voice-asset.js. |

| laneHealth.js | Lane-health metrics (#12088): computeLaneHealth counts, per audit lane (metric label, auditLanes), the issues filed in a window and how they ended — completed, not planned/duplicate, fix reverted (a Revert commit naming the PR or a SHA of it), re-filed (a new issue citing a path/to/file.ext a closed one cited within 30 days); laneHealthFor picks one lane, describeLaneFlag words a flag. Pure; services/appLaneHealth.js supplies the forge and git reads. | | auditQuality.js | Category discovery strategies, slice-scored assessment prompt and v1/v2 report schema, sentinel parsing, and freshness-aware app quality aggregation: per-category rolling window of recent run scores over daily winners across peers. |

| mindToolRecipes.js | Closed recipe schemas, current semantic-contract validation, and safe JSON field binding resolution. | | deckTemplates.js | Decks (playing cards / tarot): kind alphabet, per-kind card roster (deckCardRoster), exact playing-card rank/suit identity cues (deckCardIdentityPrompt), shared layout and face-orientation prompts (deckCardOrientationPrompt), render prompt composition (composeCardRenderPrompt), per-card status and deckCompletion, plus deckCardSize / deckCardAspectStyle (persisted trim → thumbnail box). Pure — re-exported by client/src/lib/decks.js. | | deckValidation.js | Zod schemas + limits for the /api/decks routes (create/update deck, card patch, sample analysis, prompt generation, render). | | kilo.js | Kilo Code command identity (kilo/kilocode), run headless argv, --auto approval posture, and TUI arguments. | | openchamber.js | OpenChamber control-CLI identity, session create headless argv, provider/model gate, and --dir/--prompt spawn-time delivery. | | layaMlx.js | Pinned Laya-MLX experiment model, request validation and probability normalization; entropy confidence stays distinct from entailment. | | layeredIntelligenceSources.js | LAYERED_INTELLIGENCE_SOURCE_KEYS — the ordered list of built-in Layer-1 telemetry sources the self-improvement loop can gather. Used by server schema and client UI to build source lists from one canonical definition. Pure leaf: no Node built-in, nothing outside server/lib. Re-exported by client/src/lib/layeredIntelligenceSources.js. | | layeredIntelligenceSourceKeys.js | Dependency-free LAYERED_INTELLIGENCE_SOURCE_KEYS leaf shared by the server schema, layered-intelligence reader, and client settings form. |

| persistentMindMaintainer.js | Machine-local maintainer intent, inference allowance schema, normalization and additive wake charter; never grants authority. |

| developmentWorkIdentity.js | Canonical development task identity and cross-producer ownership matching. |

| persistentMindProcessAudit.js | Bounded process-audit schemas, deterministic observations, measured recovery ratios, and closed-vocabulary synthetic finding renderer. | | markdownImages.js | markdownImages(content, limit) — bounded, deduplicated safe markdown image previews for Brain cards and import archives. |

| chatgptText.js | stripChatgptCitations(text) removes opaque ChatGPT citation tokens while preserving ordinary Markdown and asset links. |

| modelComparisonComposite.js | buildModelComparisonComposite(observations, inventory) derives a stable sourced index with calibrated and effort estimates, route-specific price references, zero API charges for local-inference inventory and explicit research gaps. |

| messageLogError.js | messageLogError(error) projects mailbox failures to allowlisted codes and HTTP error status, excluding provider text and credentials. |

| launchVideoValidation.js | validateLaunchVideoAssets checks frozen launch composition text, storyboard reading time, duration, and poster position before rendering. |

| messageBrowserIdentity.js | Shared Outlook row extraction, canonical row/member ingestion identity, conservative legacy matching, per-sync exact identity indexing (createBrowserMessageMatcher), detail mapping, and identity-safe browser action scripts; exact unique targets and confirmed row removal. | | messageBrowserCompose.js | Confirmed Outlook/Teams draft delivery through the authenticated browser tab, as pure helpers: planDelivery (deliverability + intended recipients/thread, run BEFORE a draft is claimed), buildComposePhaseScript (probe/open/fill/submit/discard CDP scripts, args as JSON), classifySendOutcome (confirmed only on a closed compose surface plus a fresh provider signal; anything else after the single submit click is unknown), recipientsMatch, checkAccountIdentity, and overridable COMPOSE_SELECTOR_DEFAULTS/resolveComposeConfig. Defaults are unvalidated against a live mailbox. | | messageTransport.js | MESSAGE_ACCOUNT_TRANSPORT — the one table of what each message-account type delivers (sendVia, email-capable): sendViaForAccountType, accountTypeCanSend, and pickEmailSenderAccount (privacy email lanes prefer an API transport, never pick a Teams chat). |

| defaultRequestBody.js | Express middleware that defaults an undefined req.body (Express 5 leaves it unset for body-less requests) to {} so handlers do not crash with a TypeError 500. | | databaseAuthority.js | createDatabaseAuthority(dataDir?) durably records which backend a verified cutover released admission to and which it retired; assertDatabasePoolAuthority(pool) refuses a process whose pool still names the retired source (enforced at boot and on every pooled operation). |

| databaseMaintenanceJournal.js | Shared databaseMaintenanceEndpointSchema plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, worker process-group records, immutable recovery-dump and import receipts, durable forward-only stages through verified, per-pid target proofs from a restarted server, token-persisting same-operation recovery, and releaseAdmission (authority record, then completed archive); source-only cancellation archives an unowned accepted operation. |

| databaseRestoreRecovery.js | createDatabaseRestoreRecovery(dataDir?) durable machine-local journal + admission fence for one in-flight snapshot database restore (#9725): operation id, dump digest, ORIGINAL pre-replay feed positions and stage (replaying → repairing), published before replay and released only after repair or a proven rollback; damaged state fails closed. |

| databaseWriterRegistry.js | createDatabaseWriterRegistry(dataDir?) supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus retire(id, archiveDir?) for proven-quiescent records; reserveDatabaseWriter is the mandatory spawnDetached admission boundary. classifyWriterQuiescence(row, processes) classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |

| musicVideoCreativeContext.js | musicVideoDirectionContext(direction) bounds the authoritative Cast & Sets bible; musicVideoCodeDirectionContext(direction) renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; musicVideoCreativeContext(concept) composes the selected universe style and authored cast/place/object bible for planning and generation; musicVideoSongStyleContext(concept) splits concept.songStyle (a Suno style prompt; minus-prefixed terms are excluded styles) and turns it into design direction for the planning LLMs (never an image prompt). | | musicVideoCharacterStyles.js | Built-in Music Video character styles (a fixed-identity performer a project loads as its base concept and cast): MUSIC_VIDEO_CHARACTER_STYLES / _IDS, getMusicVideoCharacterStyle, summarizeMusicVideoCharacterStyle (picker projection), musicVideoCharacterStyleSnapshot (the concept.characterStyle text), musicVideoCharacterStyleSubject / …SubjectId / …ReferenceId (the protagonist and character-sheet reference a pick adds), musicVideoCharacterSheetPrompt (renders the style's own sheet). Pure; services/musicVideo/characterStyles.js keeps each install's sheet image. | | moodBoardStyleContext.js | collectBoardStyleContext(board) bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. moodBoardImageCandidates(board, resolveItem) lists the poster first, then pinned local images. moodBoardItemCaption(item) returns an item's caption unless it was imported from X/Pinterest/another page (or a frame cut from one). | | musicVideoAutonomous.js | supersededStillsCheckpoint(project, readiness) retires only an old stills checkpoint from presentation once a current final render and approvals supersede it, preserving run history. Fully-autonomous Music Video vocabulary: AUTONOMOUS_STAGES (brief → lyrics → style → song → analyze → produce), optional AUTONOMOUS_CHECKPOINT_IDS, normalizeAutonomousSettings / normalizeAutonomousBrief / normalizeAutopilotParams (the shared run settings, a run's stored brief, and the scheduled task's params), autonomousMedium / autonomousPool (tool picks → footage vs code, production route pool), sunoSongFields + Suno limits/URL helpers, normalizeSunoOptions (the brief's optional suno form options: exclude styles, vocal gender, model version), and pickBrainIdea / ideaToPrompt for the scheduled task. Pure; the client drawer and the run service import it. | | musicVideoAutomation.js | Music Video automation brief: MUSIC_VIDEO_AUTOMATION_TOOLS (image/video backends derived from generationModes.js plus code:render, each flagged metered), MUSIC_VIDEO_AUTOMATION_TOOL_IDS, and normalizeMusicVideoAutomation(patch, current) (per-sub-field merge, catalog-ordered tools, budgetUsd: null = no cap, llm: null clears the direction-LLM pin, llmStages merges per stage with null clearing one, server-written routes survive but are never patch-settable). Also normalizeMusicVideoLlm / normalizeMusicVideoEffort / musicVideoLlmRouteLabel for that pin and the effective route a stage ran on (#9545), and MUSIC_VIDEO_LLM_STAGES / MUSIC_VIDEO_LLM_STAGE_LABELS / normalizeMusicVideoLlmStages for the per-stage pins. Dependency-light; the client create drawer imports it. | | albumLimits.js | Album record length/count caps shared by the albums sanitizer and client editors. | | artistLimits.js | Artist record length caps shared by the artists sanitizer and client editors. | | authorLimits.js | Author record length caps shared by the authors sanitizer and client editors. | | trackLimits.js | Track record length/count caps shared by the tracks sanitizer and client editors. | | shellLimits.js | MAX_TOTAL_SESSIONS shell-session cap shared by the shell service and the Shell UI. | | muscriptorModels.js | MUSCRIPTOR_MODELS (small/medium/large) — MuScriptor size tiers shared by route schemas and audioMidiTranscription.js; pinned to the Python runner's argparse choices. | | loopInterval.js | Loop interval grammar (MIN_INTERVAL_MS, parseInterval, isValidLoopInterval) shared by services/loops.js and createLoopSchema so the route rejects what the service would. |

| musicVideoAspect.js | musicVideoAspect(project) (treatment brief aspect, default 16:9), MUSIC_VIDEO_FRAME_GEN_SIZES and musicVideoFrameGenSize(project): the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. musicVideoAtAspect(project, aspect) re-frames the project for one render (a vertical social cut) without touching the record. musicVideoLocalClipSize(project, model, { endFrame }) sizes a local clip to the aspect, musicVideoRenderCanvas(aspect, lead) the final render's frame, and matchesMusicVideoAspect(w, h, aspect) tests a frame's shape. Shared by productionDispatch.js, documentRender.js and the client board. | | musicVideoMotion.js | MOTION_CONTINUITY_CLAUSE: the clause every Music Video motion (i2v) prompt ends with, pinning the reference frame's lighting, time of day and palette. Shared by handoff.js and the client board. AUDIO_REACTIVE_PERFORMANCE_GUARD: the clause an audio-reactive shot's prompt ends with. silentMotionPrompt(prompt, { styleParts }): the same prompt as plain physical motion (no lyric/beat cues, song times or look words) for a take that hears no audio; applied at video submit only to a request sent before musicVideoShotPrompt.js composed clips. | | musicVideoShotPrompt.js | The model input for a Music Video shot's clip and stills (#11317): musicVideoShotModelInput(project, scene, opts) → { prompt, promptAdditions }, the director's text plus each block PortOS adds (project look, bible, palette/camera rules, shot direction, lighting continuity, camera move, shot actions, Grok phrase timing, audio-reactive guard, song audio reference, repair notes) as a labeled addition; a take that hears no audio is composed without the look, song timing or on-beat camera clause. musicVideoFrameModelInput(project, scene, { slot, fromFrame, refine, repairs, fixes }) does the same for a start or end frame (look, frame direction, plate actions, rework line, keep-the-shot line, refine wrapper). authoredShotPrompt, authoredFramePromptText and visualDirection. Shared by the shot card, the board, the production run and the image and video submits. | | musicVideoConditioning.js | musicVideoStyleImages, musicVideoStylePrompt, musicVideoStyleBasis, and musicVideoStyleReferenceCapacity supply bounded moodboard conditioning and text fallback; musicVideoPanelArtReferences(scene) turns a fitted shot's storyboard panel art into a reference that keeps one slot; musicVideoConditioningReferences(project, scene, castMedia?) selects the approved character sheet, the scene's mapped set plate and the sheets of supporting cast the scene's prompt names (capped at 4), with capped project-wide fallback; a scene's characterVariant leads with that Casting member's guides (musicVideoCastGuideReferences, via catalogMediaLibrary.pickGuideMedia) when castMedia is supplied; shared by board and production. | | musicVideoMediumPlan.js | normalizeMusicVideoProductionPolicy, planMusicVideoMedia, summarizeMusicVideoMediumPlan, and codeFirstProductionAssets: pinned shot media, union-of-intervals video allowance, and selected-asset preflight shared by planning and Board review. musicVideoBriefTools, musicVideoBriefAllowsVideo and musicVideoToolPolicyConflict read the brief's selected tools against the policy (the setup warning and the video-dispatch refusal). |

| imageLimits.js | MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS — browser-safe image generation caps shared with validation. |

| musicVideoActionContract.js | Versioned shot intent shape/timing validation and clip-relative frame/motion prompt compilation, shared by treatment and the board. | | sheetPointers.js | Browser-safe persisted character-sheet layout: LEGACY_SHEET_VARIANT_ID, readSheetPointer, listSheetPointers, identity-preserving applySheetPointerToCharacter, and default-variant browser adapter applySheetPointer. | | musicVideoGrade.js | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. | | filmLook.js | The film look: FILM_LOOK_CONTROLS (sliders, colors, toggles with their photography terms and prompt words), FILM_LOOK_PRESETS, normalizeFilmLook, isFilmLookNeutral, sameFilmLook, scaleFilmLook (a look at a fraction of its strength), describeFilmLook (the look as prompt vocabulary), filmLookFilterMarkup (the one SVG filter the live preview, the document render and gallery bakes apply, frame-seeded), filmLookMotionLayers (the same look as CSS filter functions plus blended overlays a playing video can afford) and filmLookRuntimeSource (the page script that applies and re-seeds it per seek). Browser-safe. | | filmLookGpu.js | filmLookGpuRuntimeSource: the page script defining __portosFilmLookGpu, a WebGL2 renderer that draws filmLookFilterMarkup's filter primitive by primitive the way Chrome's Skia raster backend does (three-box blurs, Skia's feTurbulence, 8-bit premultiplied intermediates), for the footage film-look finishing pass. | | filmLookValidation.js | filmLookSchema / filmLookBakeSchema: the Zod shape of a film look, derived from FILM_LOOK_CONTROLS; filmLookSavedPresetsSchema for the install's saved looks. | | musicVideoStatsOutro.js | The cutting room floor outro: an optional scene after the song tallying the director's choices. normalizeStatsOutro, statsOutroSeconds, musicVideoOutroStats (the counts from the project's takes, selections, marks and media collection), drawStatsOutro (the one canvas painter the animatic and the final render share) and statsOutroPageSource (the render page's script). Browser-safe. | | musicVideoTitleCard.js | The MTV-style opening title card (song, artist, year over the opener): normalizeTitleCard, titleCardVisible, titleCardPrefill (a new card's text and a window ending before the first sung line), and titleCardRuntimeSource (the page script the live preview and the document render install to draw it per seek, with its fade and title-safe layout). Browser-safe. | | musicVideoDependencies.js | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. | | musicVideoEndFrame.js | Style-break end frames (#11173): sceneEndFramePlan(scene, { backend, falModelId }) says whether a clip sends the scene's end frame (only fal models with an end image, never a performance shot) and why not; sceneEndFrameRequestFields turns it into lastImageFile. Shared by the board and production. | | musicVideoLocalModels.js | Which local video models render which Music Video shot: localModelRendersCutaway (image-to-video), localModelRendersPerformance (LTX-2 family a2v or MiniMax H3 Ref2VA, from the still + song slice), localMusicVideoModels(models, performance) and localModelTakesSongAudio (LTX-2 family a2v: a cutaway can take its song slice). Shared by the shot card and project model pickers and submitJob.js / prepareParams.js. | | musicVideoHandoffFrame.js | Continuing shots: sceneClipOutFrameSec(scene, clipDurationSec, fps) is the time in a shot's clip of the last frame the cut shows (performance edit in/out, loop wrap, hold past the clip's end); previousShot(project, sceneId) is the shot before it by start time. | | musicVideoCrossLinks.js | Cross-links between a release's posts: each post's public link, the Label: url lines a new draft adds, which links a posted record carries (links, or what its draft always linked), and crossLinkBackfill(kit) listing the links each editable post (YouTube, Suno, X, Stacker News) still lacks. Shared by the publish payloads and the Publish stage. | | musicVideoCutEffects.js | Music Video cut effects a shot sets on its cut out (scene.cutEffect, kept while switched off): the beat toggle (flips between the two shots' clips on the beats before the cut), a dissolve and a fade through black. sceneCutEffect, beatToggleSwitches, cutEffectCuts (the render's frames), sceneCutEffects (the animatic's song times), and plannedCutEffect / plannedTransitions (a storyboard row's Dissolve or Fade as the default effect). Browser-safe. | | musicVideoExcerptRange.js | excerptRangeFits(startSec, endSec, totalSec, fps): whether a code/document excerpt window fits a frame-quantized render, allowing the end up to one frame past it (scene ends follow the analysed song length; the caller clamps). The start must fall inside the render; an unknown fps allows no slack. |

| musicVideoPlateEvidence.js | Asset-bound authored-shot plate requirements, current evidence and selected-image admission. | | codeAnimationProjects.js | Machine-local Production project, patch and independent budget schemas; package imports grant no execution authority. | | musicVideoNarrativeEvents.js | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. |

| persistentMindContextEvents.js | selectPersistentMindContextEvents, renderPersistentMindContextEvent — retain useful conversation evidence without diagnostic ledger noise. | | persistentMindVisitReceipts.js | Bounded machine-local continuation receipts for a mind's outbound Eidoverse visits: buildVisitReceiptEventData, selectOpenVisitReceipts, renderVisitContinuationPrompt — never the remote ticket or result content. |

| codeAnimationSound.js | Versioned frame/sample timelines, deterministic impact/reveal WAV synthesis and decoded event measurements. |

| musicVideoMediaPolicy.js | Whole-workflow media modes, legacy intent, selection admission and independent document renderer choice. |

| musicVideoFinishedOutside.js | finishedOutside(project), finishedOutsideCovers(project, stageId), finishedOutsideBlocker(project), FINISHED_OUTSIDE_STAGE_IDS and FINISHED_OUTSIDE_RERENDER_NOTE: the director's explicit "finished outside PortOS" marker, which counts Song through Make as done without recording any approval, only while the project holds a final render. Read by the client's stage derivation and musicVideoSummary.js. | | musicVideoSummary.js | summarizeMusicVideoProject(project, readiness) bounded index/picker projection (stage, run status, spend, preview/poster, card badges) and compareMusicVideoProjectsNewestFirst for GET /api/music-video?summary=1 (#10169). |

| sandboxDelegation.js | Bounded tool-free worker context, route configuration, and fidelity evaluation schemas. |

| forgeMaintenanceTasks.js | Current forge-maintenance screening version, queue-compatible identity check, task classification, and legacy refusal reason. |

| peerAdminValidation.js | Strict, separate planning and execution schemas with fixed intents, signed receipts and explicit grant scopes. |

| musicVideoReviewDraft.js | Pure imported Animatic review candidates, newest immutable version first; exact version URLs remain separate from native production approvals. |

| deepAuditCoverage.js | Deterministic bounded source partitions, derived coverage groups and explicit contract-upgrade compatibility. | | deepAudit.js | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |

  • auditWorkflow.js: versioned extended Deep execution and historical certification classification.

| musicDesignerValidation.js | Non-transforming authored input schemas and character limits for Music Designer composition and routes. |

  • mediaFileInfo.js: withMediaFileSize(kind, record) / withMediaFileSizes(items, kind?) add current original-file byte sizes to bounded image/video pages; missing or unreadable files have no size.
  • trashFiles.js: trashFiles(paths) moves existing literal paths to the host OS Trash/Recycle Bin, guards test data, and propagates failures without permanent-delete fallback.
  • nativeTrash.js: moveToNativeTrash(paths, { signal }?) recycles through OS facilities PortOS owns — one hidden, deadline-bound osascript (NSFileManager.trashItemAtURL, exported MACOS_TRASH_SCRIPT) per file on macOS so each gets Finder Put Back; one Windows PowerShell 5.1 -EncodedCommand run (shell32 SHFileOperationW with FOF_ALLOWUNDO, exported WINDOWS_TRASH_SCRIPT, paths in PORTOS_TRASH_PATHS, fixed-drive pre-flight) per batch; trashXdg per file on Linux. Refusals reject with a coded error (TRASH_REFUSED + per-file report, TRASH_DEADLINE, TRASH_ABORTED for canceled macOS/Windows children, TRASH_UNPARSABLE, TRASH_UNSUPPORTED_PLATFORM); no local-directory or permanent-delete fallback.
  • nativeTrashXdg.js: trashXdg(path) moves one file into the freedesktop Trash 1.0 directory serving its volume on node:fs alone (original names, RFC 2396 Path=, O_EXCL info reservation, NAME_MAX-bounded names, mount identity from /proc/self/mountinfo with a st_dev fallback so a bind mount gets its own volume trash instead of an EXDEV, physical-parent mount discovery, an owned trash directory is tightened to 0700 and TRASH_DIR_UNSAFE refuses a symlinked or foreign-owned one or a volume root whose entries other users could rename, a sticky shared .Trash counts only when root or the caller owns it and falls back to .Trash-<uid> when it cannot hold the per-user directory, refuses instead of copying across devices); _topDirTrash(topDir, uid), _parseMountInfo(text) and _mountOf(realDir, mounts) are test hooks.
  • eventLoopLagProbe.js: createEventLoopLagProbe({ clock, intervalMs, toleranceMs, resources, attributeAboveMs }) opens phase-tracking spans that charge overdue time of one shared, span-scoped tick to the current phase, so a slow-operation diagnostic splits each phase into event-loop/host scheduling lag and asynchronous wait (#12329), and a span charged more than attributeAboveMs of lag carries load (process cpuMs, gcMs, invCtx, host load1/cpus) to tell a busy process from a starved one (#12852); beginLoadSample(resources), formatLoadAttribution(load) and systemResources (the same counters for a caller without a span); systemClock (globals resolved at call time), __createManualClock() (deterministic advance = on-time timers vs stall = blocked loop, for tests), roundMs, and phaseGroup(summary, name) (a phase plus its name. sub-phases).
  • pgJson.js: text repair for values bound to PostgreSQL, which refuses a lone UTF-16 surrogate in jsonb and NUL in jsonb/text where every file store accepted both. normalizePgString(s) → toWellFormed() with NUL → U+FFFD (the same lossy repair a UTF-8 file write applied). toPgJson(value) → JSON.stringify that repairs string values and object keys; use it, never bare JSON.stringify, for a parameter bound to a json/jsonb column or ::jsonb cast (pgJsonConventions.test.js enforces this). normalizePgParams(params) is applied by db.js query() and the withTransaction client: repairs string and array-element params (never unescapes \^@) and serializes plain-object params via toPgJson.
  • errorLogFingerprint.js: stderr-log triage primitives for error-log-triage (#12851). groupStderrEntries(text) strips the PM2 date prefix and folds stack/continuation lines under their head line; fingerprintEntry(entry, { extraTerms }) redacts the entry (home paths, hosts, IPs, UUIDs, credentials, quoted record names, plus install literals such as the hostname and OS user) and reduces the head to a template (timestamps, ids, SHAs, filesystem paths and numbers become placeholders; API routes stay distinct) with a stable 16-hex fingerprint; templateSearchExcerpt(template) picks a tracker search phrase, or null when too generic. Pure; the collector and tracker dedupe live in services/errorLogTriage.js.
  • manuscriptLocate.js: locateFind / locateFindSpan — the manuscript find locator (nearest-to-anchorQuote occurrence, then whitespace-tolerant regex fallback). The one implementation behind both the server accept path (services/pipeline/manuscriptFix.js) and the client highlight/impact preview (client/src/lib/manuscriptAnchors.js re-exports it), so the preview selects the span an accept replaces. Pure / browser-safe.

| runwayCatalogSnapshot.js | Shared Runway model catalog capabilities and cached model selection. |

| runwaySpecialVideoModels.js | Aleph 2 video-edit and Act-Two character-performance capabilities, schema compatibility and request validation. |

| codeReviewBatches.js | File-boundary code-review batching with byte-exact diff hashes, candidate revision, reviewed/remaining file identifiers, bounded calls and one shared wall-clock budget. Preserves validated findings when coverage is incomplete and classifies explicit context-capacity refusals without retaining vendor event streams. |

| realityStarterV1.js | Frozen version 1 of the text-only photographic Reality starter; migration-safe. | | universeStarters.js | Latest shipped universe starter text patches for explicit restoration. |

Reality starter updates: add a new frozen realityStarterV<N>.js text config and point universeStarters.js at it. Do not change a version imported by an applied migration. Universe Builder's Restore latest starter action uses that current pointer; it replaces only starter idea, logline, premise, style notes and the positive/negative influence lists. It preserves canon, media and local settings. Automatic migration 440 fills only a blank, unlocked Reality; customized or deleted records remain untouched. Future automatic upgrades need their own migration with explicit recognition of the outgoing shipped defaults.