Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
promote the runners and prompt builders out of lib, closing the layering backlog
[._.]/ Adam Eivy57b92d159151
diff --git a/client/public/flows.json b/client/public/flows.jsonindex c2c4adb373..8292eb9726 100644--- a/client/public/flows.json+++ b/client/public/flows.json@@ -70,7 +70,7 @@{ "id": "svc.taskSchedule", "label": "taskSchedule", "group": "server-services", "file": "server/services/taskSchedule.js", "desc": "Unified v2 schedule store (interval/cron) with prompt versioning." },{ "id": "svc.cosJobScheduler", "label": "cosJobScheduler", "group": "server-services", "file": "server/services/cosJobScheduler.js", "desc": "Fires due scheduled jobs: inline script/shell or task:ready for AI agents." },- { "id": "lib.promptRunner", "label": "promptRunner", "group": "server-lib", "file": "server/lib/promptRunner.js", "desc": "Assembles prompts from templates + context and runs them through a provider." },+ { "id": "lib.promptRunner", "label": "promptRunner", "group": "server-lib", "file": "server/services/promptRunner.js", "desc": "Assembles prompts from templates + context and runs them through a provider." },{ "id": "lib.aiProvider", "label": "aiProvider + aiToolkit", "group": "server-lib", "file": "server/services/aiProvider.js", "desc": "Provider registry/resolution: CLI providers, local backends, model selection." },{ "id": "lib.peerHttpClient", "label": "peerHttpClient", "group": "server-lib", "file": "server/lib/peerHttpClient.js", "desc": "peerFetch: authenticated HTTP to federated peer instances." },{ "id": "lib.navManifest", "label": "navManifest", "group": "server-lib", "file": "server/lib/navManifest.js", "desc": "NAV_COMMANDS + resolveNavCommand — shared by ⌘K palette and voice nav." },diff --git a/scripts/dev-proxy-drift.test.js b/scripts/dev-proxy-drift.test.jsindex 980195660f..2344c8c65b 100644--- a/scripts/dev-proxy-drift.test.js+++ b/scripts/dev-proxy-drift.test.js@@ -30,7 +30,7 @@ import { fileURLToPath } from 'url';import { NAV_COMMANDS } from '../server/lib/navManifest.js';import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../server/lib/assetRoutePrefixes.js';-import { ASSET_MOUNTS } from '../server/lib/assetMounts.js';+import { ASSET_MOUNTS } from '../server/services/assetMounts.js';const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');const read = (rel) => readFileSync(join(REPO_ROOT, rel), 'utf8');diff --git a/server/index.js b/server/index.jsindex 5d662ad366..b0411fdfd8 100644--- a/server/index.js+++ b/server/index.js@@ -3,7 +3,7 @@ import { Server } from 'socket.io';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { PATHS } from './lib/fileUtils.js';-import { mountAssetRoutes } from './lib/assetMounts.js';+import { mountAssetRoutes } from './services/assetMounts.js';import { existsSync } from 'fs';import { createTailscaleServers } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';diff --git a/server/integrations/moltbook/challengeSolver.js b/server/integrations/moltbook/challengeSolver.jsindex 2a4d7ec7b4..3a40c7a45e 100644--- a/server/integrations/moltbook/challengeSolver.js+++ b/server/integrations/moltbook/challengeSolver.js@@ -12,7 +12,7 @@* Uses AI for interpretation — supports both API and CLI providers.*/-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../../services/promptRunner.js';import { getActiveProvider, getProviderById } from '../../services/providers.js';/**diff --git a/server/integrations/moltbook/challengeSolver.test.js b/server/integrations/moltbook/challengeSolver.test.jsindex 31dacdb5b2..77cd14c4b4 100644--- a/server/integrations/moltbook/challengeSolver.test.js+++ b/server/integrations/moltbook/challengeSolver.test.js@@ -1,12 +1,12 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../../lib/promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));+vi.mock('../../services/promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));vi.mock('../../services/providers.js', () => ({getActiveProvider: vi.fn(),getProviderById: vi.fn(),}));-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../../services/promptRunner.js';import { getActiveProvider, getProviderById } from '../../services/providers.js';import { solveChallenge } from './challengeSolver.js';diff --git a/server/lib/README.md b/server/lib/README.mdindex f3b2b5e0a5..1d663d5ed7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -15,7 +15,7 @@ grep -i "what you want to do" server/lib/README.mdThe barrel `server/lib/index.js` is a machine-checkable enumeration of every public surface;`server/lib/index.test.js` verifies that every non-test `.js` file is re-exported AND appears in this README, AND that no two flat-exported modules share an identifier name.-**Namespace exports.** The validation modules (`brainValidation`, `digitalTwinValidation`, etc.), `runners`, `stageRunner`, and `storyBible` are surfaced through the barrel as namespace exports — `barrel.brainValidation.settingsUpdateInputSchema`, not bare `settingsUpdateInputSchema` — because their generic names collide with peers. Direct deep imports (`import { settingsUpdateInputSchema } from './brainValidation.js'`) are unaffected.+**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.---@@ -91,7 +91,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). || `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |-| `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. || `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. |@@ -99,7 +98,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. || `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. |-| `bibleExtractor.js` | LLM bible-extraction stage + sanitization. || `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. || `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`). Mirrored on the client at `client/src/lib/catalogTypes.js`. |@@ -107,7 +105,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `comicScriptParser.js` | Marvel/DC-format comic script parser. || `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. || `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |-| `creativeDirectorPrompts.js` | Creative Director agent prompt builders. || `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. || `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context. |@@ -122,15 +119,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |-| `promptRunner.js` | Shared LLM runner wrapper. |-| `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 `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |+| `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. || `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. |-| `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). || `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). |-| `stageRunner.js` | Shared staged-LLM runner. |-| `stagePinPolicy.js` | Run-scoped "ignore per-stage LLM pins" switch (AsyncLocalStorage) — `withStagePinsIgnored(ignore, fn)` marks an async subtree, `stagePinsIgnored()` reads it, and `stageRunner#effectiveStage` enumerates which stage-config fields it strips. Backs Series Autopilot's "use one provider/model for every stage" option. |+| `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. || `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. |@@ -336,7 +330,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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`, pitch math (`pitchToMidi`/`midiToFreq`), and `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. || `civitai.js` | Civitai URL parsing + API client. |-| `createSettingsGatedSyncScheduler.js` | `createSyncScheduler({ id, label, icon, source, getConfig, runSync })` → the `start*Scheduler()` function the settings-gated ingestion domains share (iMessage, Signal, Spotify, YouTube). Registers one `eventScheduler` interval job, no-ops when the domain is disabled in settings, and re-reads `enabled` on every tick so toggling it off stops runs without a restart (the interval itself stays locked at registration). || `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. |@@ -403,7 +396,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `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` | `shuffle(arr)` — 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). |-| `assetMounts.js` | `ASSET_MOUNTS` — every `/data/**` static mount as `{ route, dir, gate? }` (`dir` a thunk so a test that re-roots `PATHS.data` still steers it) — plus `mountAssetRoutes(app)`, which mounts them and then TERMINATES each `SERVER_OWNED_PREFIXES` namespace with a 404. The terminator matters: the SPA fallback only skips paths carrying a file extension, so an extensionless `/data/…` or a mistyped `/api/…` used to be answered with index.html and a 200 — a binary loader parsed HTML, an API client got HTML with a success status (#4688). || `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 `huggingFaceCatalog.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`. |@@ -429,7 +421,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. || `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`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `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 `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); 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` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. |-| `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. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |+| `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. 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. || `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; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. 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 `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). || `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 3098ddf897..ffbbc9b6cb 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -63,7 +63,6 @@ export * from './threejsModelPlayerSource.js';export * from './threejsModelRig.js';// === Story & narrative ===-export * from './bibleExtractor.js';export * as catalogBulkParsers from './catalogBulkParsers.js';export * from './catalogChunking.js';export * from './catalogTypes.js';@@ -72,7 +71,6 @@ export * from './canonPrompt.js';export * from './comicScriptParser.js';export * from './composeStyledPrompt.js';export * from './creativeDirectorPresets.js';-export * from './creativeDirectorPrompts.js';export * from './creativeLatitude.js';// Namespaced: the editorial-check registry (#1284) lives in the editorial/// subdir with its own barrel — surface it under `editorial.*` so the root@@ -81,7 +79,6 @@ export * as editorial from './editorial/index.js';export * from './fableLoomGraph.js';export * from './fableLoomLimits.js';export * from './fableLoomFormats.js';-export * from './sceneExtractor.js';export * from './scenePrompt.js';export * from './proseExportSettings.js';export * from './shotGrammar.js';@@ -140,7 +137,6 @@ export * from './videoModeProfiles.js';export * from './videoReferenceModes.js';export * from './videoTextEncoders.js';export * from './promptPartials.js';-export * from './promptRunner.js';export * from './promptSystemStages.js';export * from './promptTemplate.js';export * from './providerCooldown.js';@@ -173,11 +169,8 @@ export * from './openAiChatStream.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in// mediaModels.js — namespace it so the barrel surface is unambiguous.export * as runners from './runners.js';-// `stageRunner.js` defines its own `extractJson` distinct from `jsonExtract.js`.-export * as stageRunner from './stageRunner.js';export * from './stagePinPolicy.js';export * from './tuiHandshake.js';-export * from './tuiPromptRunner.js';export * from './tuiShellLaunch.js';export * from './tuiUsageScrape.js';@@ -306,7 +299,6 @@ export * from './capabilityMap.js';export * from './chiptuneRender.js';export * from './chiptuneScore.js';export * from './civitai.js';-export * from './createSettingsGatedSyncScheduler.js';export * from './huggingfaceLora.js';export * from './huggingfaceModel.js';export * from './localLlmCatalog.js';@@ -380,7 +372,6 @@ export * from './viteAllowedHosts.js';// === General utilities ===export * from './apiRegistry.js';export * from './arrayUtils.js';-export * from './assetMounts.js';export * from './assetRoutePrefixes.js';export * from './asyncMutex.js';export * from './concurrencyGate.js';diff --git a/server/lib/layering.test.js b/server/lib/layering.test.jsindex eacf6ee615..0d38072f25 100644--- a/server/lib/layering.test.js+++ b/server/lib/layering.test.js@@ -8,9 +8,9 @@* meatspacePostDrillCache.js` for a four-string array — dragging in the LLM* drill generator behind it.*- * Burn-down, like the a11y control-name guard: the allowlist only shrinks.- * Fixing a module means deleting its row, and the stale-entry test below fails- * if you name one without deleting it. Tracked in #4901.+ * The burn-down is COMPLETE: the allowlist is empty, so this is now a plain+ * rule rather than a backlog. The stale-entry test below stays because the+ * allowlist must keep shrinking if anyone ever re-opens it.*/import { describe, it, expect } from 'vitest';@@ -23,14 +23,16 @@ const LIB_ROOT = dirname(fileURLToPath(import.meta.url));// Modules that still import upward into services. Each row is a real layering// inversion awaiting its slice of #4901 — NOT a permanent exemption. Fix the// module, delete the row. Never add a row for new code.-const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set([- 'assetMounts.js',- 'createSettingsGatedSyncScheduler.js',- 'creativeDirectorPrompts.js',- 'promptRunner.js',- 'stageRunner.js',- 'tuiPromptRunner.js',-]);+// EMPTY — the burn-down is complete (#4901). Every server/lib module that+// imported upward into services has been resolved, each on its own merits:+// pure vocabularies were pushed DOWN into lib, and genuine orchestration+// (runners, the HF download stack, aiProvider) was promoted UP into services.+//+// Do NOT add a row here. An empty list means the rule is now simply enforced:+// if you need a service from lib, either the dependency belongs below (move the+// constant/helper down) or the module belongs above (promote it). Adding a row+// re-opens a backlog that took six PRs to close.+const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set([]);// Permanently exempt — NOT burn-down rows. Both reach into services through a// DYNAMIC import for a documented structural reason, and turning either into adiff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.jsonindex 7873c59e5a..3ccda7a975 100644--- a/server/lib/promptStageCallSites.generated.json+++ b/server/lib/promptStageCallSites.generated.json@@ -16,13 +16,13 @@"server/services/catalogExtraction.js"],"cd-evaluate": [- "server/lib/creativeDirectorPrompts.js"+ "server/services/creativeDirectorPrompts.js"],"cd-plan": [- "server/lib/creativeDirectorPrompts.js"+ "server/services/creativeDirectorPrompts.js"],"cd-treatment": [- "server/lib/creativeDirectorPrompts.js"+ "server/services/creativeDirectorPrompts.js"],"cos-agent-briefing": ["server/services/agentPromptBuilder.js"@@ -259,7 +259,7 @@"server/lib/editorial/checkInfra/structureStages.js"],"pipeline-extract-scenes": [- "server/lib/sceneExtractor.js"+ "server/services/sceneExtractor.js"],"pipeline-foundation-repair": ["server/services/pipeline/foundationJudge.js"@@ -407,7 +407,7 @@"server/services/writersRoom/liveDirector.js"],"writers-room-characters": [- "server/lib/bibleExtractor.js",+ "server/services/bibleExtractor.js","server/services/writersRoom/evaluator.js"],"writers-room-continue": [@@ -424,18 +424,18 @@"server/services/writersRoom/evaluator.js"],"writers-room-objects": [- "server/lib/bibleExtractor.js",+ "server/services/bibleExtractor.js","server/services/writersRoom/evaluator.js"],"writers-room-places": [- "server/lib/bibleExtractor.js",+ "server/services/bibleExtractor.js","server/services/writersRoom/evaluator.js"],"writers-room-revise": ["server/services/writersRoom/evaluator.js"],"writers-room-script": [- "server/lib/sceneExtractor.js",+ "server/services/sceneExtractor.js","server/services/writersRoom/evaluator.js"]}diff --git a/server/lib/testDataIsolation.guards.test.js b/server/lib/testDataIsolation.guards.test.jsindex 4cff265d49..0cd4da37b8 100644--- a/server/lib/testDataIsolation.guards.test.js+++ b/server/lib/testDataIsolation.guards.test.js@@ -72,7 +72,7 @@ const SELF = relative(REPO_ROOT, fileURLToPath(import.meta.url)).split(sep).join// feed a real vision model, and skips itself when the directory is absent.// A future false positive belongs here too — with a sentence saying why it's safe.const ALLOWED = new Set([- 'server/lib/creativeDirectorPrompts.test.js',+ 'server/services/creativeDirectorPrompts.test.js','server/services/visionTest.integration.test.js',]);diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 6c21afa89b..1487ee2fe0 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -1038,7 +1038,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes runs the extractor and persists scenes (visualPrompt → description)', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({extracted: {title: 'The Pilot', logline: 'A heist gone wrong.',@@ -1094,7 +1094,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes does NOT pair a new providerOverride with the stale series model', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({extracted: { title: 'T', logline: 'L', scenes: [] },runId: 'r', providerId: 'mock', model: 'mock-model',@@ -1118,7 +1118,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes with from=prose routes to the prose stage output', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'a paragraph beat' }] },runId: 'run-scenes-2', providerId: 'mock', model: 'mock-model',@@ -1145,7 +1145,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes with force=true overwrites existing scenes', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'fresh scene' }] },runId: 'run-scenes-3', providerId: 'mock', model: 'mock-model',@@ -1171,7 +1171,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes overlays the canonical numbering on LLM scenes (hybrid: alignment + dialogue preserved)', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');// The LLM extraction supplies rich fields (dialogue/visualPrompt); the// canonical list overlays its numbering/sluglines. The LLM may number /// slug the scenes differently — the overlay must win on identity.@@ -1230,7 +1230,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes uses the canonical list alone when there is no source text (deterministic, no LLM)', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes');const app = makeApp();@@ -1266,7 +1266,7 @@ describe('pipeline routes', () => {});it('POST /issues/:id/stages/storyboards/extract-scenes falls back to the LLM when the beat sheet has no scene list', async () => {- const extractor = await import('../lib/sceneExtractor.js');+ const extractor = await import('../services/sceneExtractor.js');const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'llm scene' }] },runId: 'run-fallback', providerId: 'mock', model: 'mock-model',diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex 757b80d4aa..99fff0a838 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -41,7 +41,7 @@ import { startEpisodeVideoForIssue } from '../../services/pipeline/episodeVideo.import { COMIC_PAGE_VARIANTS } from '../../services/pipeline/owners.js';import { ASPECT_RATIOS, QUALITIES } from '../../lib/creativeDirectorPresets.js';import { QUEUEABLE_IMAGE_MODES } from '../../services/imageGen/modes.js';-import { extractScenes, scenesFromBeatSheet, SOURCE_KIND } from '../../lib/sceneExtractor.js';+import { extractScenes, scenesFromBeatSheet, SOURCE_KIND } from '../../services/sceneExtractor.js';import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';import { parseComicScript } from '../../lib/comicScriptParser.js';import {diff --git a/server/services/activityDigest.js b/server/services/activityDigest.jsindex 36a4e07949..e9d9401da0 100644--- a/server/services/activityDigest.js+++ b/server/services/activityDigest.js@@ -27,7 +27,7 @@ import { getDaySummary } from './humanActivity.js';import * as journal from './brainJournal.js';import { getPerson } from './tribe.js';import { getProviderById } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';const SETTINGS_FILE = join(PATHS.brain, 'activity-digest-settings.json');diff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.jsindex a15ccf18da..5065539559 100644--- a/server/services/agentContentGenerator.js+++ b/server/services/agentContentGenerator.js@@ -7,7 +7,7 @@import * as agentActivity from './agentActivity.js';import { safeJSONParse } from '../lib/fileUtils.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';/*** Parse JSON from AI response text (handles markdown blocks, extra text)diff --git a/server/services/agentPersonalityGenerator.js b/server/services/agentPersonalityGenerator.jsindex 94b011900b..f223c00773 100644--- a/server/services/agentPersonalityGenerator.js+++ b/server/services/agentPersonalityGenerator.js@@ -5,7 +5,7 @@* Generates style, tone, topics, quirks, and prompt prefix for social platform agents.*/-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';const GENERATION_PROMPT = `You are creating a unique AI agent personality for a social media platform where AI agents interact with each other and humans.diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex fb37de53b9..2695b12055 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -53,7 +53,7 @@ vi.mock('./promptService.js', () => ({vi.mock('./providers.js', () => ({getActiveProvider: vi.fn().mockResolvedValue(null),}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');diff --git a/server/services/aiDetect.js b/server/services/aiDetect.jsindex 20e684fa2d..8322c7a026 100644--- a/server/services/aiDetect.js+++ b/server/services/aiDetect.js@@ -4,7 +4,7 @@ import { join, basename } from 'path';import { getActiveProvider, getProviderById } from './providers.js';import { tryReadFile } from '../lib/fileUtils.js';import { extractJson } from '../lib/jsonExtract.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';const DEFAULT_AI_DETECT_TIMEOUT_MS = 60000;diff --git a/server/services/aiDetect.test.js b/server/services/aiDetect.test.jsindex b5dd3c43f8..ea06d4c748 100644--- a/server/services/aiDetect.test.js+++ b/server/services/aiDetect.test.js@@ -11,12 +11,12 @@ vi.mock('./providers.js', () => ({getProviderById: vi.fn()}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({runPromptThroughProvider: vi.fn()}));import { getActiveProvider, getProviderById } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import { detectAppWithAi } from './aiDetect.js';const VALID_DETECTION_JSON = JSON.stringify({diff --git a/server/lib/assetMounts.js b/server/services/assetMounts.jssimilarity index 96%rename from server/lib/assetMounts.jsrename to server/services/assetMounts.jsindex c1838e747c..06c512edba 100644--- a/server/lib/assetMounts.js+++ b/server/services/assetMounts.js@@ -15,10 +15,10 @@* resolve after the mock, not at import.*/import express from 'express';-import { PATHS } from './fileUtils.js';-import { ServerError, sendErrorResponse } from './errorHandler.js';-import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from './assetRoutePrefixes.js';-import { wrWorksDir } from '../services/writersRoom/_shared.js';+import { PATHS } from '../lib/fileUtils.js';+import { ServerError, sendErrorResponse } from '../lib/errorHandler.js';+import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePrefixes.js';+import { wrWorksDir } from './writersRoom/_shared.js';// `acceptRanges: true` is the serve-static default already, but we set it// explicitly because the federated peer-sync receiverdiff --git a/server/lib/assetMounts.test.js b/server/services/assetMounts.test.jssimilarity index 97%rename from server/lib/assetMounts.test.jsrename to server/services/assetMounts.test.jsindex 96d3e842e4..7f87f25d2c 100644--- a/server/lib/assetMounts.test.js+++ b/server/services/assetMounts.test.js@@ -16,15 +16,15 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';import express from 'express';import { mkdirSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';-import { request } from './testHelper.js';-import { createTempDataRoot, makePathsProxy } from './mockPathsDataRoot.js';+import { request } from '../lib/testHelper.js';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';// Re-roots every `PATHS` member under a temp tree, so the mounts resolve there// instead of at the running install's `data/` — including `wrWorksDir()`, which// derives from `PATHS.data`. This is why every `dir` in the table is a thunk:// it has to read `PATHS` after this mock applies, not at import.const tempRoot = createTempDataRoot('portos-asset-mounts-');-vi.mock('./fileUtils.js', async (importOriginal) => (+vi.mock('../lib/fileUtils.js', async (importOriginal) => (makePathsProxy(await importOriginal(), { dataRoot: tempRoot })));afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));diff --git a/server/lib/bibleExtractor.js b/server/services/bibleExtractor.jssimilarity index 98%rename from server/lib/bibleExtractor.jsrename to server/services/bibleExtractor.jsindex feae06a7d8..711a6af8f9 100644--- a/server/lib/bibleExtractor.js+++ b/server/services/bibleExtractor.js@@ -2,7 +2,7 @@// canonical bible shape. Caller owns persistence.import { runStagedLLM } from './stageRunner.js';-import { sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, pickPromptFields } from './storyBible.js';+import { sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, pickPromptFields } from '../lib/storyBible.js';const KIND_STAGE = Object.freeze({[BIBLE_KIND.CHARACTER]: 'writers-room-characters',diff --git a/server/lib/bibleExtractor.test.js b/server/services/bibleExtractor.test.jssimilarity index 100%rename from server/lib/bibleExtractor.test.jsrename to server/services/bibleExtractor.test.jsdiff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 7475f8b2b8..56f25f82ad 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -57,7 +57,7 @@ import { setAIToolkit as setProvidersToolkit } from './providers.js';import { setAIToolkit as setProviderStatusToolkit } from './providerStatus.js';import { setAIToolkit as setRunnerToolkit, executeCliRun as executeCliRunFixed } from './runner.js';import { setAIToolkit as setPromptsToolkit } from './promptService.js';-import { executeTuiRun as executeTuiRunFixed } from '../lib/tuiPromptRunner.js';+import { executeTuiRun as executeTuiRunFixed } from './tuiPromptRunner.js';import { initAutoFixer } from './autoFixer.js';import { initTaskLearning } from './taskLearning.js';import { initSpawner } from './subAgentSpawner.js';diff --git a/server/services/brain.js b/server/services/brain.jsindex b0304a87b6..daf8c583b0 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -15,7 +15,7 @@ import { getActiveProvider, getProviderById } from './providers.js';import { buildPrompt } from './promptService.js';import { validate } from '../lib/validation.js';import { safeJSONParse } from '../lib/fileUtils.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import { getDomainAutonomyMode } from './cosState.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { deleteMemoryAssets } from './chatgptImport.js';diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 627e85f442..f4676d50dc 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -118,7 +118,7 @@ vi.mock('./instances.js', () => ({// return canned responses; the runner-internal mechanics (spawn args, --model// flag injection, stdio shape, gemini-cli --output-format) are covered by// runner.test.js, not here.-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');@@ -128,7 +128,7 @@ assertProvider: (provider, { message, code, status = 503 } = {}) => {runPromptThroughProvider: vi.fn()}));-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import * as githubCloner from './githubCloner.js';import * as storage from './brainStorage.js';import { deleteMemoryAssets } from './chatgptImport.js';diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.jsindex 39229d38c7..0fe6d73723 100644--- a/server/services/catalogExtraction.js+++ b/server/services/catalogExtraction.js@@ -18,8 +18,8 @@*/import { randomUUID } from 'crypto';-import { extractBible } from '../lib/bibleExtractor.js';-import { runStagedLLM } from '../lib/stageRunner.js';+import { extractBible } from './bibleExtractor.js';+import { runStagedLLM } from './stageRunner.js';import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';import { CATALOG_TYPES } from '../lib/catalogTypes.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.jsindex cf17f45439..78a01197dc 100644--- a/server/services/catalogExtraction.test.js+++ b/server/services/catalogExtraction.test.js@@ -13,10 +13,10 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../lib/bibleExtractor.js', () => ({+vi.mock('./bibleExtractor.js', () => ({extractBible: vi.fn(),}));-vi.mock('../lib/stageRunner.js', () => ({+vi.mock('./stageRunner.js', () => ({runStagedLLM: vi.fn(),}));// catalogDB pulls in the Postgres pool — mock just the one function the@@ -27,8 +27,8 @@ vi.mock('./catalogDB.js', () => ({listChildScraps: vi.fn(),}));-const bibleExtractor = await import('../lib/bibleExtractor.js');-const stageRunner = await import('../lib/stageRunner.js');+const bibleExtractor = await import('./bibleExtractor.js');+const stageRunner = await import('./stageRunner.js');const catalogDB = await import('./catalogDB.js');const { catalogEvents } = await import('./catalogEvents.js');const {diff --git a/server/services/chiptune.js b/server/services/chiptune.jsindex 19bda60e2d..532a689fee 100644--- a/server/services/chiptune.js+++ b/server/services/chiptune.js@@ -22,7 +22,7 @@ import { PATHS, atomicWrite, isPathInsideDir } from '../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../lib/ffmpeg.js';import { chiptuneScoreSchema, CHIPTUNE_LIMITS, CHIPTUNE_NOISE_PRESETS, scoreDurationSec } from '../lib/chiptuneScore.js';import { renderScoreToWav } from '../lib/chiptuneRender.js';-import { resolveProviderAndModel, assertProvider, runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveProviderAndModel, assertProvider, runPromptThroughProvider } from './promptRunner.js';import * as tracks from './tracks/index.js';import { getAppById, PORTOS_APP_ID } from './apps.js';diff --git a/server/services/chiptune.test.js b/server/services/chiptune.test.jsindex 14e1218382..0381913b10 100644--- a/server/services/chiptune.test.js+++ b/server/services/chiptune.test.js@@ -20,7 +20,7 @@ vi.mock('./tracks/index.js', () => ({}),}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({resolveProviderAndModel: vi.fn(),assertProvider: vi.fn(),runPromptThroughProvider: vi.fn(),@@ -43,7 +43,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {});const tracks = await import('./tracks/index.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const apps = await import('./apps.js');const { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack, buildChiptunePrompt } = await import('./chiptune.js');diff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.jsindex 9fb74d253b..69e585a746 100644--- a/server/services/cosLocalEndpointSlots.js+++ b/server/services/cosLocalEndpointSlots.js@@ -22,7 +22,7 @@* A shared counter across process boundaries isn't worth the coupling.*/-import { LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';+import { LOCAL_LLM_MAX_CONCURRENCY } from './promptRunner.js';import { SWARM_COUNT_MAX, SWARM_COUNT_MIN } from '../lib/validation.js';import { localRuntimeForProvider, localEndpointPort, normalizeOpenAiBaseUrl } from '../lib/localProviderRuntime.js';import { listProviders, getActiveProvider } from './providers.js';diff --git a/server/lib/createSettingsGatedSyncScheduler.js b/server/services/createSettingsGatedSyncScheduler.jssimilarity index 97%rename from server/lib/createSettingsGatedSyncScheduler.jsrename to server/services/createSettingsGatedSyncScheduler.jsindex 97c1ced8c6..4f4f2ad2f2 100644--- a/server/lib/createSettingsGatedSyncScheduler.js+++ b/server/services/createSettingsGatedSyncScheduler.js@@ -16,7 +16,7 @@* user disabling the sync mid-session doesn't keep polling until restart.*/-import { schedule } from '../services/eventScheduler.js';+import { schedule } from './eventScheduler.js';/*** Build a `start*Scheduler()` function for one settings-gated sync domain.diff --git a/server/lib/createSettingsGatedSyncScheduler.test.js b/server/services/createSettingsGatedSyncScheduler.test.jssimilarity index 96%rename from server/lib/createSettingsGatedSyncScheduler.test.jsrename to server/services/createSettingsGatedSyncScheduler.test.jsindex 50359e86eb..3ad5e585d3 100644--- a/server/lib/createSettingsGatedSyncScheduler.test.js+++ b/server/services/createSettingsGatedSyncScheduler.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';const scheduleMock = vi.fn();-vi.mock('../services/eventScheduler.js', () => ({ schedule: (...args) => scheduleMock(...args) }));+vi.mock('./eventScheduler.js', () => ({ schedule: (...args) => scheduleMock(...args) }));const { createSyncScheduler } = await import('./createSettingsGatedSyncScheduler.js');diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex 8ad66c9862..ab6d54fc01 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -16,7 +16,7 @@import { randomUUID } from 'crypto';import { addTask, reviveBlockedTask, cosEvents } from '../cos.js';-import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../../lib/creativeDirectorPrompts.js';+import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../creativeDirectorPrompts.js';import { getToolSpecs } from '../creative/toolRegistry.js';import { getSettings } from '../settings.js';import { resolveStagePin } from './projectsLogic.js';diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.jsindex 7b66117efe..a2ed804bd2 100644--- a/server/services/creativeDirector/agentBridge.test.js+++ b/server/services/creativeDirector/agentBridge.test.js@@ -18,7 +18,7 @@ vi.mock('../cos.js', () => ({reviveBlockedTask: mocks.reviveBlockedTask,cosEvents: { emit: mocks.emit },}));-vi.mock('../../lib/creativeDirectorPrompts.js', () => ({+vi.mock('../creativeDirectorPrompts.js', () => ({buildTreatmentPrompt: mocks.buildTreatmentPrompt,buildEvaluatePrompt: mocks.buildEvaluatePrompt,buildPlanPrompt: mocks.buildPlanPrompt,diff --git a/server/services/creativeDirector/bridgeFromIssue.js b/server/services/creativeDirector/bridgeFromIssue.jsindex 6743a9591c..f6db471d18 100644--- a/server/services/creativeDirector/bridgeFromIssue.js+++ b/server/services/creativeDirector/bridgeFromIssue.js@@ -25,7 +25,7 @@* is itself reachable from seriesAutopilot's teaser step.*/-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import {CD_BRIDGE_STAGE,shapeProposal,diff --git a/server/services/creativeDirector/bridgeFromIssue.test.js b/server/services/creativeDirector/bridgeFromIssue.test.jsindex cde3d4a79a..ee8b8e4884 100644--- a/server/services/creativeDirector/bridgeFromIssue.test.js+++ b/server/services/creativeDirector/bridgeFromIssue.test.js@@ -22,7 +22,7 @@ const mockStartProject = vi.fn();// stageRunner is shared by bridgeFromIssue AND liveDirector (which provides the// real shapeProposal/CD_BRIDGE_STAGE we deliberately keep unmocked).-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => mockRunStagedLLM(...a) }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: (...a) => mockRunStagedLLM(...a) }));vi.mock('../pipeline/issues.js', () => ({ getIssue: (...a) => mockGetIssue(...a) }));vi.mock('../pipeline/series.js', () => ({ getSeries: (...a) => mockGetSeries(...a) }));vi.mock('../videoGen/local.js', () => ({ defaultVideoModelId: () => 'ltx-model' }));diff --git a/server/services/creativeDirector/sceneEvaluator.js b/server/services/creativeDirector/sceneEvaluator.jsindex e9c3c39674..eb3016e121 100644--- a/server/services/creativeDirector/sceneEvaluator.js+++ b/server/services/creativeDirector/sceneEvaluator.js@@ -29,8 +29,8 @@ import { z } from 'zod';import { PATHS } from '../../lib/fileUtils.js';import { safeUnder } from '../../lib/ffmpeg.js';import { extractJson } from '../../lib/jsonExtract.js';-import { runPromptThroughProvider, assertVisionRunUsedImages } from '../../lib/promptRunner.js';-import { buildEvaluateVisionPrompt, CD_MAX_SCENE_RETRIES } from '../../lib/creativeDirectorPrompts.js';+import { runPromptThroughProvider, assertVisionRunUsedImages } from '../promptRunner.js';+import { buildEvaluateVisionPrompt, CD_MAX_SCENE_RETRIES } from '../creativeDirectorPrompts.js';import { getSettings } from '../settings.js';import { getProviderById } from '../providers.js';import { listVisionModels } from '../localLlm.js';diff --git a/server/services/creativeDirector/sceneEvaluator.test.js b/server/services/creativeDirector/sceneEvaluator.test.jsindex f0a3c22766..f9503cac61 100644--- a/server/services/creativeDirector/sceneEvaluator.test.js+++ b/server/services/creativeDirector/sceneEvaluator.test.js@@ -26,9 +26,16 @@ const mocks = vi.hoisted(() => ({}));vi.mock('fs', () => ({ existsSync: mocks.existsSync }));-vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { videoThumbnails: '/data/video-thumbnails' } }));+// Spread the real module rather than replacing it: this mock used to supply+// ONLY videoThumbnails, which left PATHS.data undefined for anything else the+// graph reached. Override the two fields this suite cares about and point the+// data root at a mock path so nothing touches the real checkout.+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: '/mock/data', videoThumbnails: '/data/video-thumbnails' } };+});vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '') }));-vi.mock('../../lib/promptRunner.js', () => ({+vi.mock('../promptRunner.js', () => ({runPromptThroughProvider: mocks.runPromptThroughProvider,assertVisionRunUsedImages: mocks.assertVisionRunUsedImages,}));diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 9728e765dc..a01de638f7 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -32,7 +32,7 @@ import { join } from 'path';import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';import { verifyVideoPlayable } from '../../lib/ffmpeg.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';-import { CD_MAX_SCENE_RETRIES } from '../../lib/creativeDirectorPrompts.js';+import { CD_MAX_SCENE_RETRIES } from '../creativeDirectorPrompts.js';import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';import { VIDEO_GEN_MODE } from '../videoGen/modes.js';import { grokVideoJobParams, resolveVideoBackendPin } from '../videoGen/backendPin.js';diff --git a/server/lib/creativeDirectorPrompts.js b/server/services/creativeDirectorPrompts.jssimilarity index 98%rename from server/lib/creativeDirectorPrompts.jsrename to server/services/creativeDirectorPrompts.jsindex 9655cd9e5f..6c8c73bac8 100644--- a/server/lib/creativeDirectorPrompts.js+++ b/server/services/creativeDirectorPrompts.js@@ -23,9 +23,9 @@ import {resolveAspectDimensions,QUALITY_PRESETS,presetToRenderParams,-} from './creativeDirectorPresets.js';+} from '../lib/creativeDirectorPresets.js';import { PORTOS_API_URL } from './ports.js';-import { buildPrompt } from '../services/promptService.js';+import { buildPrompt } from './promptService.js';// Shared project-block view used by both prompt stages. Defaults out// nullable fields to `''` so the templates' `{{#x}}`/`{{^x}}` Mustache-spec@@ -153,7 +153,7 @@ export async function buildPlanPrompt(project, { toolSpecs } = {}) {// focused consumers intentionally mock only the PATHS keys they use; loading// the on-disk model catalog is specific to planning and should happen only// when a plan prompt is actually requested.- const { getVideoModels } = await import('./mediaModels.js');+ const { getVideoModels } = await import('../lib/mediaModels.js');const view = buildPlanView(project, toolSpecs, getVideoModels());return buildPrompt('cd-plan', view);}diff --git a/server/lib/creativeDirectorPrompts.test.js b/server/services/creativeDirectorPrompts.test.jssimilarity index 99%rename from server/lib/creativeDirectorPrompts.test.jsrename to server/services/creativeDirectorPrompts.test.jsindex facdb632db..517b9bdc3d 100644--- a/server/lib/creativeDirectorPrompts.test.js+++ b/server/services/creativeDirectorPrompts.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { readFile } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { applyTemplate } from './promptTemplate.js';+import { applyTemplate } from '../lib/promptTemplate.js';// Resolve the templates from disk so the tests exercise the real Prompts// Manager templates — if a future edit breaks an unwrapped {{var}} or a@@ -25,7 +25,7 @@ const loadStage = async (stageName) => {// Mock the prompt-service buildPrompt to render the on-disk template through// the same engine production uses, without needing a live aiToolkit instance.-vi.mock('../services/promptService.js', () => ({+vi.mock('./promptService.js', () => ({buildPrompt: vi.fn(async (stageName, view) => {const template = await loadStage(stageName);return applyTemplate(template, view);diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.jsindex ffcd965ed5..45c59c195a 100644--- a/server/services/digital-twin-helpers.js+++ b/server/services/digital-twin-helpers.js@@ -1,7 +1,7 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { existsSync } from 'fs';import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import { clearTombstone, tombstoneTimestamp, supersedingTimestamp } from '../lib/tombstones.js';export const DIGITAL_TWIN_DIR = PATHS.digitalTwin;diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex 0f80deda0e..f80d56b04a 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -74,7 +74,7 @@ vi.mock('./socialAccounts.js', () => ({getAllAccounts: vi.fn(() => [])}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({runPromptThroughProvider: vi.fn()}));@@ -87,7 +87,7 @@ import { existsSync } from 'fs';import { getProviderById, getActiveProvider } from './providers.js';import { buildPrompt } from './promptService.js';import { safeJSONParse, atomicWrite } from '../lib/fileUtils.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import {digitalTwinEvents,diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex c9f7116643..a8d0dad5c8 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -14,7 +14,7 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { resolveLlmRoutePin } from '../../lib/llmRoutePin.js';import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 87304ab4fd..f69020bdff 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -14,7 +14,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const runStagedLLM = vi.hoisted(() => vi.fn());-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM }));const getUniverseMock = vi.hoisted(() => vi.fn(async () => null));vi.mock('../universeBuilder.js', () => ({ getUniverse: getUniverseMock }));diff --git a/server/services/games/feedback.js b/server/services/games/feedback.jsindex 12c98d296b..82d040dcf3 100644--- a/server/services/games/feedback.js+++ b/server/services/games/feedback.js@@ -7,7 +7,7 @@ import { ServerError } from '../../lib/errorHandler.js';import {resolveEffectiveModel,runPromptThroughProvider,-} from '../../lib/promptRunner.js';+} from '../promptRunner.js';import { getAppById } from '../apps.js';import { getProviderById } from '../providers.js';import { getRecord as getSpriteRecord } from '../sprites/records.js';diff --git a/server/services/games/feedback.test.js b/server/services/games/feedback.test.jsindex 491e61120b..796031f71c 100644--- a/server/services/games/feedback.test.js+++ b/server/services/games/feedback.test.js@@ -25,7 +25,7 @@ vi.mock('../providers.js', () => ({})),}));-vi.mock('../../lib/promptRunner.js', () => ({+vi.mock('../promptRunner.js', () => ({resolveEffectiveModel: vi.fn((_provider, model) => model),runPromptThroughProvider: vi.fn(async () => ({text: 'Add a victory cue.',@@ -46,7 +46,7 @@ vi.mock('../tracks/index.js', () => ({getTrack: vi.fn(async (id) => ({ id, title: 'Example Theme', audioFilename: 'theme.ogg' })),}));-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../promptRunner.js';import { getProviderById } from '../providers.js';import { requestGameFeedback } from './feedback.js';diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsindex cd45ae8023..75f2285b6b 100644--- a/server/services/goalScorecard.js+++ b/server/services/goalScorecard.js@@ -33,7 +33,7 @@ import { localDayRangeUtc, localDayKey, listEvents } from './humanActivity.js';import * as journal from './brainJournal.js';import { buildMarkers } from '../lib/markedSection.js';import { getProviderById, getActiveProvider } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');const INSIGHTS_DIR = join(PATHS.data, 'insights');diff --git a/server/services/hfToken.test.js b/server/services/hfToken.test.jsindex 52fbe9d17a..ab71c50390 100644--- a/server/services/hfToken.test.js+++ b/server/services/hfToken.test.js@@ -6,7 +6,7 @@ const { mockGetSettings, mockTryReadFile } = vi.hoisted(() => ({}));vi.mock('../services/settings.js', () => ({ getSettings: mockGetSettings }));-vi.mock('./fileUtils.js', () => ({ tryReadFile: mockTryReadFile }));+vi.mock('../lib/fileUtils.js', () => ({ tryReadFile: mockTryReadFile }));import { hfChildEnv } from './hfToken.js';diff --git a/server/services/imessageScheduler.js b/server/services/imessageScheduler.jsindex 68f4b8d4b6..de65751075 100644--- a/server/services/imessageScheduler.js+++ b/server/services/imessageScheduler.js@@ -17,7 +17,7 @@* Disk Access + user intent.*/-import { createSyncScheduler } from '../lib/createSettingsGatedSyncScheduler.js';+import { createSyncScheduler } from './createSettingsGatedSyncScheduler.js';import { getImessageConfig, runSync } from './imessageSync.js';/**diff --git a/server/services/importer.js b/server/services/importer.jsindex fe9876a672..c0344d26ec 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -11,7 +11,7 @@*/import { randomUUID } from 'crypto';-import { runStagedLLM } from '../lib/stageRunner.js';+import { runStagedLLM } from './stageRunner.js';import { importerEvents, emitImporterProgress } from './importerEvents.js';// Re-export so consumers reach the analyze-phase progress bus through the// importer's public surface (the socket bridge imports it from the sourcediff --git a/server/services/importer.test.js b/server/services/importer.test.jsindex b891699bf3..543eb5ec7f 100644--- a/server/services/importer.test.js+++ b/server/services/importer.test.js@@ -57,7 +57,7 @@ vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());// Mock runStagedLLM so tests never hit a real provider — every importer// LLM call resolves to a canned JSON shape we control per-test.const mockRunStagedLLM = vi.fn();-vi.mock('../lib/stageRunner.js', () => ({+vi.mock('./stageRunner.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),runStagedLLM: (...args) => mockRunStagedLLM(...args),}));diff --git a/server/services/localModelAgentBenchmark.js b/server/services/localModelAgentBenchmark.jsindex 7281a88f83..2a30fc4f33 100644--- a/server/services/localModelAgentBenchmark.js+++ b/server/services/localModelAgentBenchmark.js@@ -25,7 +25,7 @@ import { isClaudeCommand, isOpencodeCommand } from '../lib/providerModels.js';// different tool-call counts for the same run.import { summarizeOpenCodeEvents } from '../lib/opencodeStream.js';import { getProviderById } from './providers.js';-import { executeTuiRun } from '../lib/tuiPromptRunner.js';+import { executeTuiRun } from './tuiPromptRunner.js';import { getRunsPath } from './runner.js';export const LOCAL_TUI_AGENT_BENCHMARK_TARGETS = Object.freeze({diff --git a/server/services/localModelAgentBenchmark.test.js b/server/services/localModelAgentBenchmark.test.jsindex 41b93cccd0..2f677758b4 100644--- a/server/services/localModelAgentBenchmark.test.js+++ b/server/services/localModelAgentBenchmark.test.js@@ -1,7 +1,7 @@import { describe, expect, it, vi, beforeEach } from 'vitest';import { join } from 'path';vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));-vi.mock('../lib/tuiPromptRunner.js', () => ({ executeTuiRun: vi.fn() }));+vi.mock('./tuiPromptRunner.js', () => ({ executeTuiRun: vi.fn() }));vi.mock('./runner.js', () => ({ getRunsPath: vi.fn(() => '/tmp/portos-benchmark-runs') }));vi.mock('../lib/providerModels.js', () => ({isOpencodeCommand: vi.fn(() => true),@@ -9,7 +9,7 @@ vi.mock('../lib/providerModels.js', () => ({}));import { getProviderById } from './providers.js';-import { executeTuiRun } from '../lib/tuiPromptRunner.js';+import { executeTuiRun } from './tuiPromptRunner.js';import {buildOpenCodeAgentBenchmarkPrompt,runOpenCodeAgentBenchmark,diff --git a/server/services/loops.js b/server/services/loops.jsindex 8cf1ae2052..bf93d8db69 100644--- a/server/services/loops.js+++ b/server/services/loops.js@@ -12,7 +12,7 @@ import { join } from 'path';import { PATHS, ensureDir, atomicWrite, tryReadFile } from '../lib/fileUtils.js';import { randomUUID } from 'crypto';import { createRun } from './runner.js';-import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';import { getAllProviders, getActiveProvider } from './providers.js';export const loopEvents = new EventEmitter();diff --git a/server/services/loops.test.js b/server/services/loops.test.jsindex ab114bda84..47d737ba9a 100644--- a/server/services/loops.test.js+++ b/server/services/loops.test.js@@ -24,7 +24,7 @@ vi.mock('./runner.js', () => ({createRun: vi.fn()}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');@@ -42,7 +42,7 @@ vi.mock('./providers.js', () => ({import { tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { createRun } from './runner.js';-import { runPromptThroughProvider, resolveProviderAndModel } from '../lib/promptRunner.js';+import { runPromptThroughProvider, resolveProviderAndModel } from './promptRunner.js';import {createLoop,stopLoop,diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.jsindex 9bda7bb490..2527b7277b 100644--- a/server/services/meatspacePostLlm.js+++ b/server/services/meatspacePostLlm.js@@ -10,7 +10,7 @@*/import { getActiveProvider, getProviderById } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import {LEGACY_POST_LLM_PROVENANCE,POST_LLM_MAX_SEMANTIC_CANDIDATES,diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.jsindex d3b2342e11..d359fc2a9c 100644--- a/server/services/meatspacePostLlm.test.js+++ b/server/services/meatspacePostLlm.test.js@@ -9,7 +9,7 @@ vi.mock('./providers.js', () => ({// Mock the central LLM handler — meatspacePostLlm used to spawn child_process// + fetch directly, but now delegates to runPromptThroughProvider. Runner// internals (spawn args, --model flag injection) are covered by runner.test.js.-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');@@ -20,7 +20,7 @@ assertProvider: (provider, { message, code, status = 503 } = {}) => {}));import { getActiveProvider, getProviderById } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import {LLM_DRILL_TYPES,generateLlmDrill,diff --git a/server/services/mediaPromptFromMedia.js b/server/services/mediaPromptFromMedia.jsindex f74751f66f..ad9783687d 100644--- a/server/services/mediaPromptFromMedia.js+++ b/server/services/mediaPromptFromMedia.js@@ -26,7 +26,7 @@ import {assertVisionRunUsedImages,resolveEffectiveModel,runPromptThroughProvider,-} from '../lib/promptRunner.js';+} from './promptRunner.js';import { getProviderById } from './providers.js';import { loadHistory } from './videoGen/history.js';import { describeImagesFromPaths } from './visionCli.js';diff --git a/server/services/mediaPromptFromMedia.test.js b/server/services/mediaPromptFromMedia.test.jsindex 4844c0a067..e3ee98fa89 100644--- a/server/services/mediaPromptFromMedia.test.js+++ b/server/services/mediaPromptFromMedia.test.js@@ -5,7 +5,7 @@ vi.mock('./providers.js', () => ({getProviderById: vi.fn(),}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({resolveEffectiveModel: vi.fn((_provider, model) => model || 'default-model'),runPromptThroughProvider: vi.fn(),assertVisionRunUsedImages: vi.fn((_result, provider) => provider),@@ -52,7 +52,7 @@ vi.mock('fs', async (importOriginal) => {});const providers = await import('./providers.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const visionCli = await import('./visionCli.js');const fileUtils = await import('../lib/fileUtils.js');const ffmpeg = await import('../lib/ffmpeg.js');diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.jsindex 8bfe1eb129..f5483c489d 100644--- a/server/services/mediaPromptRefiner.js+++ b/server/services/mediaPromptRefiner.js@@ -1,6 +1,6 @@import { ServerError } from '../lib/errorHandler.js';import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';-import { resolveEffectiveModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';import { getProviderById } from './providers.js';const MAX_PROMPT_LEN = 8000;diff --git a/server/services/memorySummarizer.js b/server/services/memorySummarizer.jsindex 05aba4db76..33e9c574cd 100644--- a/server/services/memorySummarizer.js+++ b/server/services/memorySummarizer.js@@ -20,7 +20,7 @@import { getProviderById } from './providers.js';import { loadMeta } from './brainStorage.js';import { readArchivedConversation } from './chatgptImport.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';// Preferred summarizer model when the Brain default doesn't resolve. gpt-oss:20b// is the typical Brain default and has ample context for a full transcript.diff --git a/server/services/memorySummarizer.test.js b/server/services/memorySummarizer.test.jsindex 6f7b6fcd66..55b76bfbeb 100644--- a/server/services/memorySummarizer.test.js+++ b/server/services/memorySummarizer.test.js@@ -8,7 +8,7 @@ const runPromptThroughProvider = vi.fn();vi.mock('./providers.js', () => ({ getProviderById }));vi.mock('./brainStorage.js', () => ({ loadMeta }));vi.mock('./chatgptImport.js', () => ({ readArchivedConversation }));-vi.mock('../lib/promptRunner.js', () => ({ runPromptThroughProvider }));+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider }));let summarizer;diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.jsindex 58d1e93e4e..1a706a3d04 100644--- a/server/services/messageEvaluator.js+++ b/server/services/messageEvaluator.js@@ -4,7 +4,7 @@ import { getSettings } from './settings.js';import { getProviderById, getAllProviders } from './providers.js';import { buildRulesPromptSection } from './messageTriageRules.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import { extractJson } from '../lib/jsonExtract.js';const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.diff --git a/server/services/modelPersonality.js b/server/services/modelPersonality.jsindex 2312829901..a555681af1 100644--- a/server/services/modelPersonality.js+++ b/server/services/modelPersonality.js@@ -20,7 +20,7 @@ import { randomUUID } from 'crypto';import { join } from 'path';import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';-import { resolveProviderAndModel, runPromptThroughProvider, assertProvider } from '../lib/promptRunner.js';+import { resolveProviderAndModel, runPromptThroughProvider, assertProvider } from './promptRunner.js';import {PERSONALITY_TAXONOMY_VERSION,PERSONALITY_TRAIT_KEYS,diff --git a/server/services/modelPersonality.test.js b/server/services/modelPersonality.test.jsindex 393aed67c2..b2b717e2cf 100644--- a/server/services/modelPersonality.test.js+++ b/server/services/modelPersonality.test.js@@ -15,7 +15,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) =>makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));// Full stub — promptRunner drags in the runner/provider stack transitively.-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({resolveProviderAndModel: vi.fn(),runPromptThroughProvider: vi.fn(),assertProvider: (provider, { message } = {}) => {@@ -29,7 +29,7 @@ vi.mock('./digital-twin-meta.js', () => ({loadMeta: vi.fn(async () => ({}))}));-const { resolveProviderAndModel, runPromptThroughProvider } = await import('../lib/promptRunner.js');+const { resolveProviderAndModel, runPromptThroughProvider } = await import('./promptRunner.js');const { buildPrompt } = await import('./promptService.js');const { loadMeta } = await import('./digital-twin-meta.js');const svc = await import('./modelPersonality.js');diff --git a/server/services/moodBoardStyleSynthesis.js b/server/services/moodBoardStyleSynthesis.jsindex d24f51bab8..f9d558a3c7 100644--- a/server/services/moodBoardStyleSynthesis.js+++ b/server/services/moodBoardStyleSynthesis.js@@ -12,7 +12,7 @@import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';import { ServerError } from '../lib/errorHandler.js';-import { assertProvider, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, runPromptThroughProvider } from './promptRunner.js';import { trimTo } from '../lib/storyBible.js';import {sanitizeInfluences,diff --git a/server/services/moodBoardStyleSynthesis.test.js b/server/services/moodBoardStyleSynthesis.test.jsindex 6d30698ffd..c0def3ee23 100644--- a/server/services/moodBoardStyleSynthesis.test.js+++ b/server/services/moodBoardStyleSynthesis.test.js@@ -4,13 +4,13 @@ vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});-vi.mock('../lib/promptRunner.js', async (importActual) => {+vi.mock('./promptRunner.js', async (importActual) => {const actual = await importActual();return { ...actual, runPromptThroughProvider: vi.fn() };});const aiProvider = await import('./aiProvider.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const {collectBoardStyleContext,buildBoardStyleSynthesisPrompt,diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.jsindex 956f64ce9c..1caeaea667 100644--- a/server/services/musicDesigner.js+++ b/server/services/musicDesigner.js@@ -23,7 +23,7 @@*/import { ServerError } from '../lib/errorHandler.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';// Caps mirror the Generate form's own field limits so a designer round-trip// can't produce text the generate route would then reject.diff --git a/server/services/musicDesigner.test.js b/server/services/musicDesigner.test.jsindex b1966d3397..e12605dc74 100644--- a/server/services/musicDesigner.test.js+++ b/server/services/musicDesigner.test.js@@ -8,13 +8,13 @@ const ai = vi.hoisted(() => ({selectedModel: 'fake-model',runPromptThroughProvider: vi.fn(),}));-vi.mock('../lib/promptRunner.js', async () => ({- ...(await vi.importActual('../lib/promptRunner.js')),+vi.mock('./promptRunner.js', async () => ({+ ...(await vi.importActual('./promptRunner.js')),resolveProviderAndModel: vi.fn(async () => ({ provider: ai.provider, selectedModel: ai.selectedModel })),runPromptThroughProvider: ai.runPromptThroughProvider,}));-import { resolveProviderAndModel } from '../lib/promptRunner.js';+import { resolveProviderAndModel } from './promptRunner.js';import {DEFAULT_DESCRIBE_TEMPLATE, DEFAULT_LYRICS_TEMPLATE,buildDescribePrompt, buildLyricsPrompt, describeMusic, writeLyrics,diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex 44f50d478b..1ce40b22c6 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -30,7 +30,7 @@import { ServerError } from '../../lib/errorHandler.js';import { extractJson } from '../../lib/jsonExtract.js';-import { resolveProviderAndModel, runPromptThroughProvider } from '../../lib/promptRunner.js';+import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';import { snapSectionsToGrid } from './audioAnalysis.js';import { getProject, addProjectScenes } from './projects.js';diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.jsindex 18b4f7d3c9..1df87421e2 100644--- a/server/services/musicVideo/planner.test.js+++ b/server/services/musicVideo/planner.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../../lib/promptRunner.js', () => ({+vi.mock('../promptRunner.js', () => ({resolveProviderAndModel: vi.fn(),runPromptThroughProvider: vi.fn(),}));@@ -10,7 +10,7 @@ vi.mock('./projects.js', () => ({addProjectScenes: vi.fn(),}));-import { resolveProviderAndModel, runPromptThroughProvider } from '../../lib/promptRunner.js';+import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';import { getProject, addProjectScenes } from './projects.js';import {validSections,diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 211717a7a8..54e2b1b03e 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -25,7 +25,7 @@ vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());// Stub the staged-LLM runner so the test owns the LLM response shape.// Each test sets `stageRunnerSpy = vi.fn(...)` to control what comes back.-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),extractJson: (raw) => JSON.parse(raw),// Large window by default so completeness runs as a single call (mode:diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 78df1f19e0..c87ba28daa 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -7,7 +7,7 @@* Built on the leaf helpers in ./context.js.*/-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { ServerError } from '../../../lib/errorHandler.js';import { stripAnsi } from '../../../lib/ansiStrip.js';import { ARC_LOCKABLE_FIELDS, getSeries, updateSeries } from '../series.js';diff --git a/server/services/pipeline/arcPlanner/beatContinuity.js b/server/services/pipeline/arcPlanner/beatContinuity.jsindex 6a10774402..0e31b5d40a 100644--- a/server/services/pipeline/arcPlanner/beatContinuity.js+++ b/server/services/pipeline/arcPlanner/beatContinuity.js@@ -24,7 +24,7 @@* trio — same LLM-call + shape + apply structure, one altitude down.*/-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { ServerError } from '../../../lib/errorHandler.js';import { getSeries } from '../series.js';import { listIssues, updateStageWithLatest, TEXT_STAGE_IDS } from '../issues.js';diff --git a/server/services/pipeline/arcPlanner/completenessPass.js b/server/services/pipeline/arcPlanner/completenessPass.jsindex 6fcaf72cf5..0e3230ba5c 100644--- a/server/services/pipeline/arcPlanner/completenessPass.js+++ b/server/services/pipeline/arcPlanner/completenessPass.js@@ -4,7 +4,7 @@*/import { createHash } from 'crypto';-import { resolveStageContext, runStagedLLM } from '../../../lib/stageRunner.js';+import { resolveStageContext, runStagedLLM } from '../../stageRunner.js';import {estimateTokens, planManuscriptPass, fitContextToManuscriptFloor,trimContextToBudget, MANUSCRIPT_FLOOR_TOKENS, CHARS_PER_TOKEN,diff --git a/server/services/pipeline/arcPlanner/coverConcepts.js b/server/services/pipeline/arcPlanner/coverConcepts.jsindex 7b3f1fd647..9ff9cd14dd 100644--- a/server/services/pipeline/arcPlanner/coverConcepts.js+++ b/server/services/pipeline/arcPlanner/coverConcepts.js@@ -3,7 +3,7 @@* Built on ./context.js.*/-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { getSeries, updateSeasonOnSeries } from '../series.js';import { assertStageUnlocked, getIssue, updateStageWithLatest } from '../issues.js';import { ERR_VALIDATION, makeErr } from './context.js';diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.jsindex 30421d1cdd..adff5ebb53 100644--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js@@ -3,7 +3,7 @@* and the per-episode canon extraction. Built on ./context.js.*/-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { getSeries } from '../series.js';import { createIssue, listIssues, updateIssue, TEXT_STAGE_IDS } from '../issues.js';import { renderArcShapeGuidance, renderArcShapePositionSummary } from '../../../lib/storyArc.js';diff --git a/server/services/pipeline/arcPlanner/manuscriptDerive.js b/server/services/pipeline/arcPlanner/manuscriptDerive.jsindex 92c05b6db2..c618f43d05 100644--- a/server/services/pipeline/arcPlanner/manuscriptDerive.js+++ b/server/services/pipeline/arcPlanner/manuscriptDerive.js@@ -3,7 +3,7 @@* source text and commit the derived plan. Built on ./context.js + ./arcCore.js.*/-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { getSeries, updateSeries } from '../series.js';import { getIssue, listIssues, recomputeIssueNumbersForSeries, updateIssue, updateStage } from '../issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';diff --git a/server/services/pipeline/audioCues.js b/server/services/pipeline/audioCues.jsindex 46861c7c1a..64a1389fab 100644--- a/server/services/pipeline/audioCues.js+++ b/server/services/pipeline/audioCues.js@@ -27,7 +27,7 @@* re-extract).*/-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';import { trimTo } from '../../lib/storyBible.js';import {diff --git a/server/services/pipeline/audioCues.test.js b/server/services/pipeline/audioCues.test.jsindex 3f784a52b8..33624967d4 100644--- a/server/services/pipeline/audioCues.test.js+++ b/server/services/pipeline/audioCues.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// Stub the LLM driver so deriveAudioCues never hits a provider.const runStagedLLMMock = vi.fn();-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: (...a) => runStagedLLMMock(...a),}));diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.jsindex 8b0b08df50..26c679f992 100644--- a/server/services/pipeline/continuityBible.js+++ b/server/services/pipeline/continuityBible.js@@ -28,7 +28,7 @@ import { createHash } from 'crypto';import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';import { createSseRunner } from '../../lib/sseUtils.js';-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { seriesStore, getSeries } from './series.js';import { getSeriesCanon } from './seriesCanon.js';diff --git a/server/services/pipeline/continuityBible.test.js b/server/services/pipeline/continuityBible.test.jsindex e78ce44215..603d37b2e5 100644--- a/server/services/pipeline/continuityBible.test.js+++ b/server/services/pipeline/continuityBible.test.js@@ -11,7 +11,7 @@ vi.mock('../../lib/fileUtils.js', () => ({// runStagedLLM returns the next queued canned ledger.const llmQueue = [];const llmCalls = [];-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(async (stage, vars) => {llmCalls.push({ stage, vars });const content = llmQueue.shift();diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 80c2e88a4c..6eb2c54b2c 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -17,7 +17,7 @@import { randomUUID } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';-import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';+import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../stageRunner.js';import { planManuscriptPass, fitContextToManuscriptFloor, estimateTokens, MANUSCRIPT_FLOOR_TOKENS } from '../../../lib/contextBudget.js';import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, orderChecksByDependencies, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex 038006573c..b962406dfa 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -46,7 +46,7 @@ vi.mock('../arcPlanner.js', async () => {completenessSourceHash: completeness.completenessSourceHash,};});-vi.mock('../../../lib/stageRunner.js', () => ({+vi.mock('../../stageRunner.js', () => ({runStagedLLM: vi.fn(async () => ({runId: 'llm-run',content: {@@ -97,7 +97,7 @@ let editorialState = { characters: [] };vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () => editorialState) }));const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors, previewCustomCheck, buildScopedPriorFindings, effectiveCheckSources, __testing: checkRunnerTesting } = await import('./checkRunner.js');-const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');+const { runStagedLLM, resolveStageContext } = await import('../../stageRunner.js');const { buildCompletenessContext, collectManuscriptSections, completenessSourceHash, sectionsCorpus } = await import('../arcPlanner.js');const { getSeriesCanon } = await import('../seriesCanon.js');const { getSeries } = await import('../series.js');@@ -527,7 +527,7 @@ describe('previewCustomCheck (#1607)', () => {});it('normalizes an out-of-enum LLM severity to the draft default', async () => {- const { runInlineLLM } = await import('../../../lib/stageRunner.js');+ const { runInlineLLM } = await import('../../stageRunner.js');runInlineLLM.mockResolvedValueOnce({runId: 'inline-run',content: { findings: [{ severity: 'catastrophic', issueNumber: 1, location: 'p1', problem: 'x', suggestion: 'y', anchorQuote: 'z' }] },@@ -551,7 +551,7 @@ describe('previewCustomCheck (#1607)', () => {});it('honors a maxFindings cap', async () => {- const { runInlineLLM } = await import('../../../lib/stageRunner.js');+ const { runInlineLLM } = await import('../../stageRunner.js');runInlineLLM.mockResolvedValueOnce({runId: 'inline-run',content: { findings: [diff --git a/server/services/pipeline/editorial/comparativeRank.js b/server/services/pipeline/editorial/comparativeRank.jsindex 65ff636bd9..cd212ddcad 100644Binary files a/server/services/pipeline/editorial/comparativeRank.js and b/server/services/pipeline/editorial/comparativeRank.js differdiff --git a/server/services/pipeline/editorial/comparativeRank.test.js b/server/services/pipeline/editorial/comparativeRank.test.jsindex 0d252d1802..c349d031e4 100644--- a/server/services/pipeline/editorial/comparativeRank.test.js+++ b/server/services/pipeline/editorial/comparativeRank.test.js@@ -10,7 +10,7 @@ vi.mock('../../../lib/fileUtils.js', async (importActual) => ({ensureDir: vi.fn(async () => {}),}));-vi.mock('../../../lib/stageRunner.js', () => ({+vi.mock('../../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveStageContext: vi.fn(async () => ({ contextWindow: 200_000 })),}));@@ -34,7 +34,7 @@ vi.mock('../readerPanelDigest.js', () => ({}));const fileUtils = await import('../../../lib/fileUtils.js');-const stageRunner = await import('../../../lib/stageRunner.js');+const stageRunner = await import('../../stageRunner.js');const issuesSvc = await import('../issues.js');const digest = await import('../readerPanelDigest.js');const {diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.jsindex 462705056d..6457ad04ae 100644--- a/server/services/pipeline/editorialAnalysis.js+++ b/server/services/pipeline/editorialAnalysis.js@@ -18,7 +18,7 @@import { join } from 'path';import { createHash } from 'crypto';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { getIssue, listIssues } from './issues.js';import { getSeries } from './series.js';diff --git a/server/services/pipeline/editorialAnalysis.test.js b/server/services/pipeline/editorialAnalysis.test.jsindex ef21f137c5..d0b6d2ad37 100644--- a/server/services/pipeline/editorialAnalysis.test.js+++ b/server/services/pipeline/editorialAnalysis.test.js@@ -14,7 +14,7 @@ vi.mock('../../lib/fileUtils.js', () => ({// runStagedLLM returns the next queued canned analysis.const llmQueue = [];const llmCalls = [];-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(async (stage, ctx) => {llmCalls.push({ stage, ctx });const content = llmQueue.shift();diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex ff5d3fb3d2..1b10f439f4 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -37,7 +37,7 @@import { join } from 'path';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';-import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { getStage } from '../promptService.js';import { composeStyleNotes, sanitizeStyleGuide, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';diff --git a/server/services/pipeline/foundationJudge.rollback.test.js b/server/services/pipeline/foundationJudge.rollback.test.jsindex fb232eef03..26f90e034d 100644--- a/server/services/pipeline/foundationJudge.rollback.test.js+++ b/server/services/pipeline/foundationJudge.rollback.test.js@@ -36,7 +36,7 @@ vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());// Everything the foundation judge needs but this round-trip doesn't exercise.-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveStageContext: vi.fn(async () => ({ contextWindow: 200_000 })),resolveJudgeForStage: vi.fn(async () => ({ provider: { id: 'judge-x' }, model: 'jm-heavy' })),diff --git a/server/services/pipeline/foundationJudge.structureRollback.test.js b/server/services/pipeline/foundationJudge.structureRollback.test.jsindex d7de9ddf8b..8151fed80e 100644--- a/server/services/pipeline/foundationJudge.structureRollback.test.js+++ b/server/services/pipeline/foundationJudge.structureRollback.test.js@@ -41,7 +41,7 @@ vi.mock('crypto', async () => {vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),extractJson: (raw) => JSON.parse(raw),resolveStageContext: vi.fn(async () => ({ provider: { id: 'p' }, model: 'm', contextWindow: 1_000_000 })),diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex ac73d768fe..0c110ae086 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -9,7 +9,7 @@ vi.mock('../../lib/fileUtils.js', async (importActual) => ({ensureDir: vi.fn(async () => {}),}));-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveStageContext: vi.fn(async () => ({ contextWindow: 200_000 })),resolveJudgeForStage: vi.fn(async () => ({ provider: { id: 'judge-x' }, model: 'jm-heavy' })),@@ -57,7 +57,7 @@ vi.mock('./arcPlanner.js', async (importActual) => ({}));const fileUtils = await import('../../lib/fileUtils.js');-const stageRunner = await import('../../lib/stageRunner.js');+const stageRunner = await import('../stageRunner.js');const seriesSvc = await import('./series.js');const universeBuilder = await import('../universeBuilder.js');const universeBuilderExpand = await import('../universeBuilderExpand.js');diff --git a/server/services/pipeline/manuscriptEditor.test.js b/server/services/pipeline/manuscriptEditor.test.jsindex 9574d9f8d5..ab9910a867 100644--- a/server/services/pipeline/manuscriptEditor.test.js+++ b/server/services/pipeline/manuscriptEditor.test.js@@ -21,7 +21,7 @@ vi.mock('crypto', async () => {vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),extractJson: (raw) => JSON.parse(raw),// Large window so manuscript-fix runs as a single call (mode: 'whole').diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsindex df940446aa..a30b717748 100644--- a/server/services/pipeline/manuscriptFix.js+++ b/server/services/pipeline/manuscriptFix.js@@ -13,7 +13,7 @@*/import { randomUUID, createHash } from 'crypto';-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';import { getSeries, MANUSCRIPT_TYPES } from './series.js';import { getIssue, updateStageWithLatest, updateStagesWithLatest } from './issues.js';diff --git a/server/services/pipeline/manuscriptReformat.test.js b/server/services/pipeline/manuscriptReformat.test.jsindex b0ea411124..3bc1ff5b96 100644--- a/server/services/pipeline/manuscriptReformat.test.js+++ b/server/services/pipeline/manuscriptReformat.test.js@@ -3,13 +3,13 @@ import {} from 'vitest';// Mock the staged-LLM runner so the reformat core is tested without a real call.-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveStageContext: vi.fn(async () => ({ contextWindow: 100000 })),}));import { reformatManuscriptText, reformatManuscriptStageText } from './manuscriptFix.js';-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';describe('reformatManuscriptText — integrity guard', () => {beforeEach(() => runStagedLLM.mockReset());diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.jsindex a3e8b538c4..682502ba1a 100644--- a/server/services/pipeline/perspectiveRewrite.js+++ b/server/services/pipeline/perspectiveRewrite.js@@ -22,7 +22,7 @@ import { join } from 'path';import { createHash, randomUUID } from 'crypto';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { richCanonDescriptorFragments, flattenCanonDescriptorFragments } from '../../lib/canonPrompt.js';import { filterCanonListForIssue } from '../../lib/storyBible.js';diff --git a/server/services/pipeline/perspectiveRewrite.test.js b/server/services/pipeline/perspectiveRewrite.test.jsindex b638cbfc23..0f331afc13 100644--- a/server/services/pipeline/perspectiveRewrite.test.js+++ b/server/services/pipeline/perspectiveRewrite.test.js@@ -15,7 +15,7 @@ vi.mock('../../lib/fileUtils.js', () => ({// returns the next queued JSON object.const analysisQueue = [];const llmCalls = [];-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(async (stage, ctx) => {llmCalls.push({ stage, ctx });if (stage === 'pipeline-pov-rewrite') {diff --git a/server/services/pipeline/pipelineJudge.js b/server/services/pipeline/pipelineJudge.jsindex 6742f999c0..9458972d48 100644--- a/server/services/pipeline/pipelineJudge.js+++ b/server/services/pipeline/pipelineJudge.js@@ -30,7 +30,7 @@import { join } from 'path';import { createHash } from 'crypto';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';-import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { computeSlopPenalty } from '../../lib/editorial/slopScore.js';import { getStage } from '../promptService.js';diff --git a/server/services/pipeline/pipelineJudge.test.js b/server/services/pipeline/pipelineJudge.test.jsindex 43046b26c7..f891350a61 100644--- a/server/services/pipeline/pipelineJudge.test.js+++ b/server/services/pipeline/pipelineJudge.test.js@@ -9,7 +9,7 @@ vi.mock('../../lib/fileUtils.js', async (importActual) => ({ensureDir: vi.fn(async () => {}),}));-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveStageContext: vi.fn(async () => ({ contextWindow: 200_000 })),resolveJudgeForStage: vi.fn(async () => ({ provider: { id: 'judge-x' }, model: 'jm-heavy' })),@@ -32,7 +32,7 @@ vi.mock('./seriesCanon.js', async (importActual) => ({}));const fileUtils = await import('../../lib/fileUtils.js');-const stageRunner = await import('../../lib/stageRunner.js');+const stageRunner = await import('../stageRunner.js');const issuesSvc = await import('./issues.js');const { computeSlopPenalty } = await import('../../lib/editorial/slopScore.js');const {diff --git a/server/services/pipeline/readerPanel.js b/server/services/pipeline/readerPanel.jsindex 91dce7ef2c..b1ba6ec2d4 100644--- a/server/services/pipeline/readerPanel.js+++ b/server/services/pipeline/readerPanel.js@@ -21,7 +21,7 @@import { join } from 'path';import { rm } from 'fs/promises';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import {PANEL_PERSONA_IDS,minePanelDisagreements,diff --git a/server/services/pipeline/readerPanel.test.js b/server/services/pipeline/readerPanel.test.jsindex 7f8815094e..0575d81177 100644--- a/server/services/pipeline/readerPanel.test.js+++ b/server/services/pipeline/readerPanel.test.js@@ -19,7 +19,7 @@ vi.mock('../../lib/fileUtils.js', () => ({tryReadFile: (...a) => tryReadFile(...a),safeJSONParse: (s) => (s == null ? null : JSON.parse(s)),}));-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: vi.fn() }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: vi.fn() }));vi.mock('./readerPanelDigest.js', () => ({computeSourceContentHash: (...a) => computeSourceContentHash(...a),renderDigestText: (d) => JSON.stringify(d),diff --git a/server/services/pipeline/refineHelpers.js b/server/services/pipeline/refineHelpers.jsindex f47a0cb142..65d7c0bd84 100644--- a/server/services/pipeline/refineHelpers.js+++ b/server/services/pipeline/refineHelpers.js@@ -1,4 +1,4 @@-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';// Pass `logTag: null` to suppress the default runId log so a caller thatdiff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.jsindex 74e7a5617a..47c025bd61 100644--- a/server/services/pipeline/reverseOutline.js+++ b/server/services/pipeline/reverseOutline.js@@ -25,7 +25,7 @@ import { createHash } from 'crypto';import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';import { createSseRunner } from '../../lib/sseUtils.js';-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { seriesStore, getSeries } from './series.js';import { getSeriesCanon } from './seriesCanon.js';diff --git a/server/services/pipeline/reverseOutline.test.js b/server/services/pipeline/reverseOutline.test.jsindex 66fa74fc3f..9c7156be3f 100644--- a/server/services/pipeline/reverseOutline.test.js+++ b/server/services/pipeline/reverseOutline.test.js@@ -11,7 +11,7 @@ vi.mock('../../lib/fileUtils.js', () => ({// runStagedLLM returns the next queued canned outline.const llmQueue = [];const llmCalls = [];-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(async (stage, vars, opts = {}) => {llmCalls.push({ stage, vars, opts });const content = llmQueue.shift();diff --git a/server/services/pipeline/scriptVerify.js b/server/services/pipeline/scriptVerify.jsindex ec2e909b48..34a62f0f58 100644--- a/server/services/pipeline/scriptVerify.js+++ b/server/services/pipeline/scriptVerify.js@@ -14,7 +14,7 @@* necessary.*/-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { getIssue } from './issues.js';import { getSeries } from './series.js';diff --git a/server/services/pipeline/seriesAutopilot/observer.js b/server/services/pipeline/seriesAutopilot/observer.jsindex 0064343a44..82569f4c3c 100644--- a/server/services/pipeline/seriesAutopilot/observer.js+++ b/server/services/pipeline/seriesAutopilot/observer.js@@ -42,7 +42,7 @@import * as cosTaskStore from '../../cosTaskStore.js';import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { trimToClause } from '../../../lib/storyBible.js';import { getSettings } from '../../settings.js';import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';diff --git a/server/services/pipeline/seriesAutopilot/observer.test.js b/server/services/pipeline/seriesAutopilot/observer.test.jsindex d7d19f1465..0b0f862b89 100644--- a/server/services/pipeline/seriesAutopilot/observer.test.js+++ b/server/services/pipeline/seriesAutopilot/observer.test.js@@ -18,7 +18,7 @@ vi.mock('../../domainUsage.js', () => ({let llmContent = null;const runStagedLLM = vi.fn(async () => ({ content: llmContent }));-vi.mock('../../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));+vi.mock('../../stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));vi.mock('../../settings.js', async (importOriginal) => ({...(await importOriginal()),diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.js b/server/services/pipeline/seriesAutopilot/selfImprove.jsindex 98d9d661bf..2a85815e45 100644--- a/server/services/pipeline/seriesAutopilot/selfImprove.js+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js@@ -50,7 +50,7 @@import * as cosTaskStore from '../../cosTaskStore.js';import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';-import { runStagedLLM } from '../../../lib/stageRunner.js';+import { runStagedLLM } from '../../stageRunner.js';import { trimToClause } from '../../../lib/storyBible.js';import { getSettings } from '../../settings.js';import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.test.js b/server/services/pipeline/seriesAutopilot/selfImprove.test.jsindex 3933ebaf13..bec007a59f 100644--- a/server/services/pipeline/seriesAutopilot/selfImprove.test.js+++ b/server/services/pipeline/seriesAutopilot/selfImprove.test.js@@ -19,7 +19,7 @@ vi.mock('../../domainUsage.js', () => ({let llmContent = null;const runStagedLLM = vi.fn(async () => ({ content: llmContent }));-vi.mock('../../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));+vi.mock('../../stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));vi.mock('../../settings.js', async (importOriginal) => ({...(await importOriginal()),diff --git a/server/services/pipeline/seriesGenerate.js b/server/services/pipeline/seriesGenerate.jsindex 7a8498e883..02b4e5d827 100644--- a/server/services/pipeline/seriesGenerate.js+++ b/server/services/pipeline/seriesGenerate.js@@ -43,7 +43,7 @@ import { getUniverse, joinInfluenceList, ERR_NOT_FOUND as UNIVERSE_ERR_NOT_FOUNDimport { listSeries, NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';import { ARC_SHAPES, ARC_SHAPE_IDS } from '../../lib/storyArc.js';import { runPromptRefineRaw } from './refineHelpers.js';-import { runStagedLLM, resolveJudgeForStage } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveJudgeForStage } from '../stageRunner.js';import { getStage } from '../promptService.js';import { ServerError } from '../../lib/errorHandler.js';diff --git a/server/services/pipeline/seriesGenerate.test.js b/server/services/pipeline/seriesGenerate.test.jsindex c6f74141bc..f4779b2fbb 100644--- a/server/services/pipeline/seriesGenerate.test.js+++ b/server/services/pipeline/seriesGenerate.test.js@@ -15,7 +15,7 @@ vi.mock('./series.js', async (importOriginal) => {return { ...actual, listSeries: vi.fn(async () => []) };});vi.mock('./refineHelpers.js', () => ({ runPromptRefineRaw: vi.fn() }));-vi.mock('../../lib/stageRunner.js', () => ({+vi.mock('../stageRunner.js', () => ({runStagedLLM: vi.fn(),resolveJudgeForStage: vi.fn(),}));@@ -36,7 +36,7 @@ import {import { getUniverse } from '../universeBuilder.js';import { listSeries, NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';import { runPromptRefineRaw } from './refineHelpers.js';-import { runStagedLLM, resolveJudgeForStage } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveJudgeForStage } from '../stageRunner.js';const baseUniverse = {id: 'uni-1',diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.jsindex 866f4bde71..ac3ea9c11e 100644--- a/server/services/pipeline/seriesReview.js+++ b/server/services/pipeline/seriesReview.js@@ -43,7 +43,7 @@ import { unlink } from 'fs/promises';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse, sha256Text } from '../../lib/fileUtils.js';import { canonicalStringify } from '../../lib/objects.js';import { createSseRunner } from '../../lib/sseUtils.js';-import { runStageScopedInlineLLM } from '../../lib/stageRunner.js';+import { runStageScopedInlineLLM } from '../stageRunner.js';import { getDomainMode } from '../../lib/domainAutonomy.js';import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/index.js';import { loadState } from '../cosState.js';diff --git a/server/services/pipeline/seriesReview.run.test.js b/server/services/pipeline/seriesReview.run.test.jsindex 83572d32c9..f3f000a489 100644--- a/server/services/pipeline/seriesReview.run.test.js+++ b/server/services/pipeline/seriesReview.run.test.js@@ -36,7 +36,7 @@ function partial(overrides) {vi.mock('./series.js', partial({ getSeries: vi.fn(async () => ({ id: 'ser-test', severityWeights: null })) }));vi.mock('./issues.js', partial({ listIssues: vi.fn(async () => []) }));vi.mock('../settings.js', partial({ getSettings: vi.fn(async () => ({})) }));-vi.mock('../../lib/stageRunner.js', partial({ runStageScopedInlineLLM: vi.fn(async () => ({ content: {} })) }));+vi.mock('../stageRunner.js', partial({ runStageScopedInlineLLM: vi.fn(async () => ({ content: {} })) }));// The four passes whose interleaving this suite is about. Each appends to the// shared `order` log so the test can read the real execution sequence.diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex 737a621167..d0c1da5690 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -19,7 +19,7 @@* emit is a no-op and generation is byte-for-byte the un-streamed path.*/-import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { getStage } from '../promptService.js';import { emitStageProgress, finishStageProgress } from './textStageProgress.js';import { getSeries } from './series.js';diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 6e44dca1e6..c11e359c07 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -113,7 +113,7 @@ const DEFAULT_RUN_STAGED_LLM = async () => ({model: 'gpt-4o',});const runStagedLLMMock = vi.fn(DEFAULT_RUN_STAGED_LLM);-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLMMock(...a) }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLMMock(...a) }));vi.mock('../../lib/mediaModels.js', () => ({getDefaultVideoModelId: () => 'ltx-default',diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex 100367240b..3aea666ad7 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -5,7 +5,7 @@ import { exec, spawn } from '../lib/childProcess.js';import { promisify } from 'util';import { getActiveProvider, getProviderById } from './providers.js';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';import { getReservedPorts, getAllApps } from './apps.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { usesPm2, isStandardizable } from './streamingDetect.js';diff --git a/server/lib/promptRunner.js b/server/services/promptRunner.jssimilarity index 99%rename from server/lib/promptRunner.jsrename to server/services/promptRunner.jsindex a3ef54988f..a1db434178 100644--- a/server/lib/promptRunner.js+++ b/server/services/promptRunner.js@@ -26,18 +26,18 @@* stay honest about what the runner actually executed.*/-import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';-import { getActiveProvider, getProviderById, getAllProviders } from '../services/providers.js';+import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from './runner.js';+import { getActiveProvider, getProviderById, getAllProviders } from './providers.js';import { executeTuiRun } from './tuiPromptRunner.js';-import { ServerError } from './errorHandler.js';-import { PROVIDER_TYPES } from './aiToolkit/constants.js';-import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from './aiToolkit/errorDetection.js';-import { isSchemaTypeCategory, resolveProviderBench } from './providerCooldown.js';-import { isGenerationModel } from './localModelHeuristics.js';-import { getAIToolkitInstance } from './aiToolkitState.js';-import { createSingleFlight } from './singleFlight.js';-import { extractJson } from './jsonExtract.js';-import { isCreativeRunSource, withCreativeLatitude } from './creativeLatitude.js';+import { ServerError } from '../lib/errorHandler.js';+import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';+import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiToolkit/errorDetection.js';+import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';+import { isGenerationModel } from '../lib/localModelHeuristics.js';+import { getAIToolkitInstance } from '../lib/aiToolkitState.js';+import { createSingleFlight } from '../lib/singleFlight.js';+import { extractJson } from '../lib/jsonExtract.js';+import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';// The fallback-lifecycle notifiers live in services/autoFixer.js, which// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it@@ -45,7 +45,7 @@ import { isCreativeRunSource, withCreativeLatitude } from './creativeLatitude.js// dragging the CoS stack along on the happy path. Node caches the module after// the first dynamic import, so the cost is one-time.function loadAutoFixer() {- return import('../services/autoFixer.js');+ return import('./autoFixer.js');}export const DEFAULT_TIMEOUT_MS = 300000;diff --git a/server/lib/promptRunner.test.js b/server/services/promptRunner.test.jssimilarity index 99%rename from server/lib/promptRunner.test.jsrename to server/services/promptRunner.test.jsindex 1c0e1cfcc9..5c9cccdc3e 100644--- a/server/lib/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../services/runner.js', () => ({+vi.mock('./runner.js', () => ({createRun: vi.fn(),executeApiRun: vi.fn(),executeCliRun: vi.fn(),@@ -32,7 +32,7 @@ vi.mock('./tuiPromptRunner.js', () => ({// tests can drive the active/by-id lookups directly. `getAllProviders` is// mocked too so the retry-with-fallback path (which enumerates providers to// look up the configured fallback) can be driven directly from tests.-vi.mock('../services/providers.js', () => ({+vi.mock('./providers.js', () => ({getActiveProvider: vi.fn(),getProviderById: vi.fn(),getAllProviders: vi.fn().mockResolvedValue({ activeProvider: null, providers: [] }),@@ -42,7 +42,7 @@ vi.mock('../services/providers.js', () => ({// fallback retry to cancel the deferred investigation task. Mock the export// to a spy so tests can assert it was/wasn't invoked without wiring up the// full task system.-vi.mock('../services/autoFixer.js', () => ({+vi.mock('./autoFixer.js', () => ({noteFallbackStarted: vi.fn(),noteFallbackHandled: vi.fn(),noteFallbackFailed: vi.fn(),@@ -53,17 +53,17 @@ vi.mock('../services/autoFixer.js', () => ({// service being present. By default the mock returns null so the retry// short-circuits and the original error is rethrown — individual tests// override the return value to enable the retry branch.-vi.mock('./aiToolkitState.js', () => ({+vi.mock('../lib/aiToolkitState.js', () => ({getAIToolkitInstance: vi.fn().mockReturnValue(null),}));-const runner = await import('../services/runner.js');+const runner = await import('./runner.js');const tuiRunner = await import('./tuiPromptRunner.js');-const providers = await import('../services/providers.js');-const autoFixer = await import('../services/autoFixer.js');-const toolkitState = await import('./aiToolkitState.js');-const { ERROR_CATEGORIES } = await import('./aiToolkit/errorDetection.js');-const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('./creativeLatitude.js');+const providers = await import('./providers.js');+const autoFixer = await import('./autoFixer.js');+const toolkitState = await import('../lib/aiToolkitState.js');+const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');+const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('../lib/creativeLatitude.js');const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory } = await import('./promptRunner.js');const apiProvider = (extra = {}) => ({diff --git a/server/services/promptSections/appContext.js b/server/services/promptSections/appContext.jsindex b43177ebd2..94035a40a4 100644--- a/server/services/promptSections/appContext.js+++ b/server/services/promptSections/appContext.js@@ -4,7 +4,7 @@import { join } from 'path';import { PATHS, readJSONFile, expandHome } from '../../lib/fileUtils.js';-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../promptRunner.js';import { getActiveProvider } from '../providers.js';import * as jiraService from '../jira.js';import { emitLog } from '../cosEvents.js';diff --git a/server/services/recordMergeAI.js b/server/services/recordMergeAI.jsindex 7d5b7ade34..987d98405f 100644--- a/server/services/recordMergeAI.js+++ b/server/services/recordMergeAI.js@@ -10,7 +10,7 @@import { ServerError } from '../lib/errorHandler.js';import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';import { stripPromptControlChars, buildUniverseStyleContext } from './universeBuilder.js';export const ERR_NO_PROVIDER = 'MERGE_AI_NO_PROVIDER';diff --git a/server/services/recordMergeAI.test.js b/server/services/recordMergeAI.test.jsindex bba4d49f84..21ba15ab0a 100644--- a/server/services/recordMergeAI.test.js+++ b/server/services/recordMergeAI.test.js@@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// Mock the prompt runner so the test never tries to spawn a CLI / API provider.const resolveProviderAndModelMock = vi.fn();const runPromptThroughProviderMock = vi.fn();-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');diff --git a/server/services/roundsAI.js b/server/services/roundsAI.jsindex 61cf2b5bd7..78e9dd1915 100644--- a/server/services/roundsAI.js+++ b/server/services/roundsAI.js@@ -19,7 +19,7 @@* (promptRunner → providers → runner) doesn't load on every plain song read.*/-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';import { extractJson } from '../lib/jsonExtract.js';import { ServerError } from '../lib/errorHandler.js';import {diff --git a/server/services/roundsAI.test.js b/server/services/roundsAI.test.jsindex 07fea23713..840726653a 100644Binary files a/server/services/roundsAI.test.js and b/server/services/roundsAI.test.js differdiff --git a/server/lib/sceneExtractor.js b/server/services/sceneExtractor.jssimilarity index 98%rename from server/lib/sceneExtractor.jsrename to server/services/sceneExtractor.jsindex 45afa7f0f0..6a65417732 100644--- a/server/lib/sceneExtractor.js+++ b/server/services/sceneExtractor.js@@ -19,8 +19,8 @@*/import { runStagedLLM } from './stageRunner.js';-import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from './storyBible.js';-import { normalizeShotType, normalizeScreenDirection } from './shotGrammar.js';+import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from '../lib/storyBible.js';+import { normalizeShotType, normalizeScreenDirection } from '../lib/shotGrammar.js';export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TELEPLAY: 'teleplay' });diff --git a/server/lib/sceneExtractor.test.js b/server/services/sceneExtractor.test.jssimilarity index 100%rename from server/lib/sceneExtractor.test.jsrename to server/services/sceneExtractor.test.jsdiff --git a/server/services/signalScheduler.js b/server/services/signalScheduler.jsindex b7b9bd3511..accb561e4c 100644--- a/server/services/signalScheduler.js+++ b/server/services/signalScheduler.js@@ -17,7 +17,7 @@* key/DB access + user intent.*/-import { createSyncScheduler } from '../lib/createSettingsGatedSyncScheduler.js';+import { createSyncScheduler } from './createSettingsGatedSyncScheduler.js';import { getSignalConfig, runSync } from './signalSync.js';/**diff --git a/server/services/spotifyScheduler.js b/server/services/spotifyScheduler.jsindex 654b4c9fd4..703a1792a7 100644--- a/server/services/spotifyScheduler.js+++ b/server/services/spotifyScheduler.js@@ -18,7 +18,7 @@* intent + a completed OAuth connection.*/-import { createSyncScheduler } from '../lib/createSettingsGatedSyncScheduler.js';+import { createSyncScheduler } from './createSettingsGatedSyncScheduler.js';import { getSpotifyConfig, runSync } from './spotifySync.js';/**diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 262615cc3a..2a2e1cc067 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -42,7 +42,7 @@ import { readdir, rm } from 'fs/promises';import { randomUUID } from 'crypto';import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { executeTuiRun } from '../../lib/tuiPromptRunner.js';+import { executeTuiRun } from '../tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import {diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.jsindex b6578b4e28..cdcbe225db 100644--- a/server/services/sprites/animationTrackWorkflow.test.js+++ b/server/services/sprites/animationTrackWorkflow.test.js@@ -36,7 +36,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const executeTuiRun = vi.fn(() => new Promise(() => {}));-vi.mock('../../lib/tuiPromptRunner.js', () => ({+vi.mock('../tuiPromptRunner.js', () => ({executeTuiRun: (...args) => executeTuiRun(...args),}));diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 96363e713c..6f9aab3c4d 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -25,7 +25,7 @@ import {ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { executeTuiRun } from '../../lib/tuiPromptRunner.js';+import { executeTuiRun } from '../tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { getSettings } from '../settings.js';import { getRecord, updateRecord } from './records.js';diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 20939f0d4b..aca886011d 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -36,7 +36,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {// NOT race the test with a background attach; a happy-path test overrides it// with mockImplementationOnce to simulate grok writing the MP4.const executeTuiRun = vi.fn(() => new Promise(() => {}));-vi.mock('../../lib/tuiPromptRunner.js', () => ({+vi.mock('../tuiPromptRunner.js', () => ({executeTuiRun: (...args) => executeTuiRun(...args),}));diff --git a/server/lib/stageRunner.js b/server/services/stageRunner.jssimilarity index 98%rename from server/lib/stageRunner.jsrename to server/services/stageRunner.jsindex c16a6fbecc..d82b702af7 100644--- a/server/lib/stageRunner.js+++ b/server/services/stageRunner.js@@ -14,17 +14,17 @@* every stage call lands in `data/runs/<runId>/` for replay.*/-import { ServerError } from './errorHandler.js';-import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';+import { ServerError } from '../lib/errorHandler.js';+import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, isLocalEndpoint } from './promptRunner.js';-import { stripCodeFences } from './llmText.js';-import { extractCodexAssistant } from './codexAssistantExtract.js';-import { getActiveProvider, getProviderById } from '../services/providers.js';-import { commandBasename, isCodexProvider } from './providerModels.js';-import { buildPrompt, getStage } from '../services/promptService.js';-import { stagePinsIgnored } from './stagePinPolicy.js';-import { createRun, patchRunMetadata } from '../services/runner.js';-import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';+import { stripCodeFences } from '../lib/llmText.js';+import { extractCodexAssistant } from '../lib/codexAssistantExtract.js';+import { getActiveProvider, getProviderById } from './providers.js';+import { commandBasename, isCodexProvider } from '../lib/providerModels.js';+import { buildPrompt, getStage } from './promptService.js';+import { stagePinsIgnored } from '../lib/stagePinPolicy.js';+import { createRun, patchRunMetadata } from './runner.js';+import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from '../lib/aiToolkit/constants.js';// Stage configs name a model by tier (PromptManager UI). Map each tier name// to the provider's per-tier model field; an unset tier falls through todiff --git a/server/lib/stageRunner.mirror.test.js b/server/services/stageRunner.mirror.test.jssimilarity index 92%rename from server/lib/stageRunner.mirror.test.jsrename to server/services/stageRunner.mirror.test.jsindex a3ca58b309..7e56f36c97 100644--- a/server/lib/stageRunner.mirror.test.js+++ b/server/services/stageRunner.mirror.test.js@@ -1,6 +1,6 @@/*** Mirror parity test for the `KNOWN_MODEL_CONTEXT_WINDOWS` table, which lives- * in both server/lib/stageRunner.js and client/src/utils/providers.js (the+ * in both server/services/stageRunner.js and client/src/utils/providers.js (the* client can't import server modules, so the table is duplicated behind a* "Keep in sync" comment on each side).*@@ -21,7 +21,7 @@ import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';-import { compareDeclaration } from './mirrorParity.js';+import { compareDeclaration } from '../lib/mirrorParity.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -60,7 +60,7 @@ describe('stageRunner↔client providers context-window mirror parity', () => {const { serverDecl, clientDecl, serverNorm, clientNorm } =compareDeclaration(serverSrc, clientSrc, name);- expect(serverDecl, `server/lib/stageRunner.js is missing: ${name}`).not.toBeNull();+ expect(serverDecl, `server/services/stageRunner.js is missing: ${name}`).not.toBeNull();expect(clientDecl, `client/src/utils/providers.js is missing: ${name}`).not.toBeNull();expect(clientNorm,diff --git a/server/lib/stageRunner.test.js b/server/services/stageRunner.test.jssimilarity index 98%rename from server/lib/stageRunner.test.jsrename to server/services/stageRunner.test.jsindex 806db96ec9..3e7735c752 100644--- a/server/lib/stageRunner.test.js+++ b/server/services/stageRunner.test.js@@ -1,16 +1,16 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../services/providers.js', () => ({+vi.mock('./providers.js', () => ({getActiveProvider: vi.fn(),getProviderById: vi.fn(),}));-vi.mock('../services/promptService.js', () => ({+vi.mock('./promptService.js', () => ({buildPrompt: vi.fn().mockResolvedValue('rendered-prompt'),getStage: vi.fn(),}));-vi.mock('../services/runner.js', () => ({+vi.mock('./runner.js', () => ({createRun: vi.fn(async () => ({ runId: 'run-abc12345' })),executeApiRun: vi.fn(),executeCliRun: vi.fn(),@@ -19,11 +19,11 @@ vi.mock('../services/runner.js', () => ({patchRunMetadata: vi.fn(async () => undefined),}));-const providers = await import('../services/providers.js');-const prompts = await import('../services/promptService.js');-const runner = await import('../services/runner.js');-const { buildEffortArgs } = await import('./providerModels.js');-const { CREATIVE_LATITUDE_HEADING } = await import('./creativeLatitude.js');+const providers = await import('./providers.js');+const prompts = await import('./promptService.js');+const runner = await import('./runner.js');+const { buildEffortArgs } = await import('../lib/providerModels.js');+const { CREATIVE_LATITUDE_HEADING } = await import('../lib/creativeLatitude.js');const {runStagedLLM,runInlineLLM,@@ -45,7 +45,7 @@ const {withLocalConcurrencyGate,LOCAL_LLM_MAX_CONCURRENCY,} = await import('./stageRunner.js');-const { withStagePinsIgnored, stagePinsIgnored } = await import('./stagePinPolicy.js');+const { withStagePinsIgnored, stagePinsIgnored } = await import('../lib/stagePinPolicy.js');const apiProvider = (extra = {}) => ({id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 671d964ed5..8cd7dd6b8b 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -40,7 +40,7 @@ import { randomUUID } from 'crypto';import { isStr, trimTo, pickPromptFields, BIBLE_KIND } from '../lib/storyBible.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';-import { runStagedLLM } from '../lib/stageRunner.js';+import { runStagedLLM } from './stageRunner.js';import {STEP_IDS, STEP_STATUSES, isValidStepId,} from '../lib/storyBuilderSteps.js';diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex 7a3673237f..817c212ca8 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -25,7 +25,7 @@ vi.mock('crypto', async () => {vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());-vi.mock('../lib/stageRunner.js', () => ({+vi.mock('./stageRunner.js', () => ({runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),extractJson: (raw) => JSON.parse(raw),}));diff --git a/server/services/systemResources.js b/server/services/systemResources.jsindex 687541b954..8f3d0e5f6d 100644--- a/server/services/systemResources.js+++ b/server/services/systemResources.js@@ -15,7 +15,7 @@ import { z } from 'zod';import { query } from '../lib/db.js';import { PATHS, dirSize } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';import { getDataOverview } from './dataManager.js';import { listHfModelStorage, listLoraStorage } from './mediaModelStorage.js';import * as ollamaManager from './ollamaManager.js';diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.jsindex 0c023faa2d..de51b345fb 100644--- a/server/services/systemResources.test.js+++ b/server/services/systemResources.test.js@@ -14,7 +14,7 @@ vi.mock('../lib/fileUtils.js', () => ({},dirSize: vi.fn(async (path) => path.includes('Downloads') ? 900 : 100),}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'codex' }, selectedModel: 'gpt-example' })),assertProvider: vi.fn(),runPromptThroughProvider: vi.fn(async () => ({@@ -85,7 +85,7 @@ vi.mock('./cos.js', () => ({getStatus: vi.fn(async () => ({ running: true, paused: false, activeAgents: 0, pausedAgents: 0 })),}));-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const fsPromises = await import('fs/promises');const db = await import('../lib/db.js');const fileUtils = await import('../lib/fileUtils.js');diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.jsindex 632b1ae6aa..1a80ab3728 100644--- a/server/services/taskEnhancer.js+++ b/server/services/taskEnhancer.js@@ -9,8 +9,8 @@import { getActiveProvider, getProviderById } from './providers.js';import { getStage, buildPrompt } from './promptService.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';-import { resolveModel } from '../lib/stageRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';+import { resolveModel } from './stageRunner.js';const STAGE_NAME = 'cos-task-enhance';diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.jsindex b06039c16b..3fbf2ef675 100644--- a/server/services/threejsModels/index.js+++ b/server/services/threejsModels/index.js@@ -6,7 +6,7 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../promptRunner.js';import { extractJson } from '../../lib/jsonExtract.js';import {buildThreejsFactorySource,diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.jsindex 7b7c0a86e5..f1bddc1069 100644--- a/server/services/threejsModels/index.test.js+++ b/server/services/threejsModels/index.test.js@@ -8,7 +8,7 @@ vi.mock('../../lib/fileUtils.js', () => ({)),}));-vi.mock('../../lib/promptRunner.js', () => ({+vi.mock('../promptRunner.js', () => ({runPromptThroughProvider: vi.fn(),}));@@ -25,7 +25,7 @@ vi.mock('./db.js', () => ({recoverInterruptedModels: vi.fn(),}));-import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { runPromptThroughProvider } from '../promptRunner.js';import { getProviderById } from '../providers.js';import * as store from './db.js';import { createModel, startGeneration } from './index.js';diff --git a/server/lib/tuiPromptRunner.js b/server/services/tuiPromptRunner.jssimilarity index 98%rename from server/lib/tuiPromptRunner.jsrename to server/services/tuiPromptRunner.jsindex 5e081c15ae..9172d085bc 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -38,16 +38,16 @@import { spawn as ptySpawn } from 'node-pty';import { join, resolve } from 'path';-import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';-import { createStreamingAnsiStripper, stripAnsi } from './ansiStrip.js';+import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';+import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import {createImmediateFallbackSignalDetector,createTerminalModelErrorDetector,createTerminalRequestTimeoutDetector,-} from './aiToolkit/errorDetection.js';-import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, consumeRunStopRequested, resolveRunCwd } from '../services/runner.js';-import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached, pasteToSession } from '../services/shell.js';-import { isHostShuttingDown } from './hostShutdown.js';+} from '../lib/aiToolkit/errorDetection.js';+import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, consumeRunStopRequested, resolveRunCwd } from './runner.js';+import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached, pasteToSession } from './shell.js';+import { isHostShuttingDown } from '../lib/hostShutdown.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,PASTE_MARKER_POLL_MS,@@ -69,10 +69,10 @@ import {detectMissingTuiBinary,createSelfClearingSignalGate,SUBMIT_KEY,-} from './tuiHandshake.js';-import { buildCliChildEnv } from './cliChildEnv.js';-import { isCodexCommand } from './codex.js';-import { isClaudeCommand } from './providerModels.js';+} from '../lib/tuiHandshake.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { isCodexCommand } from '../lib/codex.js';+import { isClaudeCommand } from '../lib/providerModels.js';// One-shot defaults that don't apply to the long-running agent path:// - hard run cap (5 min vs unbounded for agents)diff --git a/server/lib/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.jssimilarity index 99%rename from server/lib/tuiPromptRunner.test.jsrename to server/services/tuiPromptRunner.test.jsindex cefae78712..69d439f730 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/services/tuiPromptRunner.test.js@@ -58,10 +58,10 @@ const { ptyInstances, ptySpawnMock, runnerMocks, shellMocks, runsTmpDirRef, resprunnerMocks.getRunsPath.mockImplementation(() => runsTmpDirRef.current);vi.mock('node-pty', () => ({ spawn: (...args) => ptySpawnMock(...args) }));-vi.mock('../services/runner.js', () => runnerMocks);-vi.mock('../services/shell.js', () => shellMocks);-vi.mock('./fileUtils.js', async () => {- const actual = await vi.importActual('./fileUtils.js');+vi.mock('./runner.js', () => runnerMocks);+vi.mock('./shell.js', () => shellMocks);+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');// Imported here rather than relied on from the module scope: vi.mock// factories are hoisted above the import list.const { resolve: resolvePath } = await import('path');@@ -103,8 +103,8 @@ vi.mock('./fileUtils.js', async () => {});import { cleanTuiResponse, resolveTuiResponseText, executeTuiRun } from './tuiPromptRunner.js';-import { markHostShuttingDown, resetHostShutdownFlagForTests } from './hostShutdown.js';-import { SELF_CLEARING_RESUBMIT_INTERVAL_MS, SELF_CLEARING_RESUBMIT_ECHO_MS, TUI_INPUT_READY_DEADLINE_MS } from './tuiHandshake.js';+import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';+import { SELF_CLEARING_RESUBMIT_INTERVAL_MS, SELF_CLEARING_RESUBMIT_ECHO_MS, TUI_INPUT_READY_DEADLINE_MS } from '../lib/tuiHandshake.js';const makeFakePty = () => {const fake = {diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.jsindex 8a6206b547..9eea93fc63 100644--- a/server/services/twinEnrichment.js+++ b/server/services/twinEnrichment.js@@ -32,7 +32,7 @@ import { query, ensureSchema } from '../lib/db.js';import { getLocalParts } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { getProviderById } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { runPromptThroughProvider } from './promptRunner.js';const DIR = PATHS.digitalTwin;const TASTE_OBSERVED_FILE = join(DIR, 'taste-observed.json');diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.jsindex 3ce43e39eb..27c7696876 100644--- a/server/services/universeBuilderAutoSort.js+++ b/server/services/universeBuilderAutoSort.js@@ -23,7 +23,7 @@ import {import { VALID_TARGET_KINDS } from './universeBuilderPromote.js';import { ServerError } from '../lib/errorHandler.js';import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';// The 3 real trunks — derived from BIBLE_FIELD via universeBuilderPromote so// adding a new canon kind reaches this resolver automatically.diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.jsindex c2515f99b9..3b0abadfde 100644--- a/server/services/universeBuilderAutoSort.test.js+++ b/server/services/universeBuilderAutoSort.test.js@@ -26,7 +26,7 @@ vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());const resolveProviderAndModelMock = vi.fn();const runPromptThroughProviderMock = vi.fn();-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');diff --git a/server/services/universeBuilderExpand.effort.test.js b/server/services/universeBuilderExpand.effort.test.jsindex 2687a814df..dd3813525c 100644--- a/server/services/universeBuilderExpand.effort.test.js+++ b/server/services/universeBuilderExpand.effort.test.js@@ -5,7 +5,7 @@ const { resolveProviderAndModelMock, runPromptThroughProviderMock } = vi.hoistedrunPromptThroughProviderMock: vi.fn(),}));-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: vi.fn(),resolveProviderAndModel: (...args) => resolveProviderAndModelMock(...args),runPromptThroughProvider: (...args) => runPromptThroughProviderMock(...args),diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex 3e5e5dfa70..77f244f352 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -37,7 +37,7 @@ import {assertProvider,resolveProviderAndModel,runPromptThroughProvider,-} from "../lib/promptRunner.js";+} from "./promptRunner.js";const LABEL_MAX = 80;const NARRATIVE_REPAIR_MAX_ATTEMPTS = 3;diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.jsindex c3304a9837..0f74d355e8 100644--- a/server/services/universeBuilderPromote.js+++ b/server/services/universeBuilderPromote.js@@ -22,7 +22,7 @@ import {} from '../lib/storyBible.js';import { ServerError } from '../lib/errorHandler.js';import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';-import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';// Inverse of BIBLE_FIELD: trunk-name (canon array key) → singular BIBLE_KIND.// Derived from the source-of-truth map so the two can't drift. `other` isdiff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.jsindex a1022e887b..79af4fd71b 100644--- a/server/services/universeBuilderPromote.test.js+++ b/server/services/universeBuilderPromote.test.js@@ -40,7 +40,7 @@ vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());// contract.const resolveProviderAndModelMock = vi.fn();const runPromptThroughProviderMock = vi.fn();-vi.mock('../lib/promptRunner.js', () => ({+vi.mock('./promptRunner.js', () => ({assertProvider: (provider, { message, code, status = 503 } = {}) => {if (provider) return;const err = new Error(message || 'No AI provider available');diff --git a/server/services/universeBuilderRefine.image.test.js b/server/services/universeBuilderRefine.image.test.jsindex 945b6e46f0..b5583b5d5f 100644--- a/server/services/universeBuilderRefine.image.test.js+++ b/server/services/universeBuilderRefine.image.test.js@@ -6,7 +6,7 @@ vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});-vi.mock('../lib/promptRunner.js', async (importActual) => {+vi.mock('./promptRunner.js', async (importActual) => {const actual = await importActual();return {...actual,@@ -16,7 +16,7 @@ vi.mock('../lib/promptRunner.js', async (importActual) => {});const aiProvider = await import('./aiProvider.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const { refineWorldPrompts } = await import('./universeBuilderRefine.js');const apiProvider = { id: 'ollama', type: 'api', enabled: true, defaultModel: 'qwen-vl' };diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.jsindex 7f18c5171c..f68dfd89b1 100644--- a/server/services/universeBuilderRefine.js+++ b/server/services/universeBuilderRefine.js@@ -13,7 +13,7 @@import { ServerError } from "../lib/errorHandler.js";import { findBalancedBlocks, tryParseWithRepair } from "../lib/jsonExtract.js";-import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "../lib/promptRunner.js";+import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "./promptRunner.js";import { resolveAPIProvider } from './aiProvider.js';import {renderCategoriesForPrompt as renderCategoriesShared,diff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex 0b030f03b6..1a53df6efc 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -5,12 +5,12 @@// series.cast → references into universe entities.import { getUniverse, updateUniverse, listUniverses, joinInfluenceList } from './universeBuilder.js';-import { extractBible } from '../lib/bibleExtractor.js';+import { extractBible } from './bibleExtractor.js';import {BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, BIBLE_LIMITS, mergeExtractedBible,listSheetPointers, applySheetPointerToCharacter, isSeriesScopedCanonEntry,} from '../lib/storyBible.js';-import { runStagedLLM } from '../lib/stageRunner.js';+import { runStagedLLM } from './stageRunner.js';import { runPromptRefine } from './pipeline/refineHelpers.js';import { ServerError } from '../lib/errorHandler.js';import { shortId } from '../lib/fileUtils.js';diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.jsindex 1e2d88a4a6..02582ee253 100644--- a/server/services/universeCanon.test.js+++ b/server/services/universeCanon.test.js@@ -37,12 +37,12 @@ vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());// out to live AI providers. Stub them to return deterministic shapes so we// can test lock semantics without spinning up a model.const extractBibleMock = vi.fn();-vi.mock('../lib/bibleExtractor.js', () => ({+vi.mock('./bibleExtractor.js', () => ({extractBible: (...args) => extractBibleMock(...args),}));const runStagedLLMMock = vi.fn();-vi.mock('../lib/stageRunner.js', () => ({+vi.mock('./stageRunner.js', () => ({runStagedLLM: (...args) => runStagedLLMMock(...args),}));diff --git a/server/services/universeStyleReference.js b/server/services/universeStyleReference.jsindex 5d159c1fd9..169fbcfe46 100644--- a/server/services/universeStyleReference.js+++ b/server/services/universeStyleReference.js@@ -9,7 +9,7 @@import { randomUUID } from 'crypto';import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';import { ServerError } from '../lib/errorHandler.js';-import { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider } from '../lib/promptRunner.js';+import { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';import { trimTo } from '../lib/storyBible.js';import {sanitizeInfluences,diff --git a/server/services/universeStyleReference.test.js b/server/services/universeStyleReference.test.jsindex bfd7f900cf..adfcfb0380 100644--- a/server/services/universeStyleReference.test.js+++ b/server/services/universeStyleReference.test.js@@ -4,13 +4,13 @@ vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});-vi.mock('../lib/promptRunner.js', async (importActual) => {+vi.mock('./promptRunner.js', async (importActual) => {const actual = await importActual();return { ...actual, runPromptThroughProvider: vi.fn() };});const aiProvider = await import('./aiProvider.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const {analyzeUniverseStyleReference,buildStyleReferenceDiff,diff --git a/server/services/universeVisionDescribe.js b/server/services/universeVisionDescribe.jsindex a73d22b1f0..0faba9faa9 100644--- a/server/services/universeVisionDescribe.js+++ b/server/services/universeVisionDescribe.js@@ -19,7 +19,7 @@*/import { resolveAPIProvider, stripCodeFences } from './aiProvider.js';-import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';+import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from './promptRunner.js';import { ServerError } from '../lib/errorHandler.js';import { getUniverse } from './universeBuilder.js';import { BIBLE_FIELD } from '../lib/storyBible.js';diff --git a/server/services/universeVisionDescribe.test.js b/server/services/universeVisionDescribe.test.jsindex 1c49eecad7..eb0db4e128 100644--- a/server/services/universeVisionDescribe.test.js+++ b/server/services/universeVisionDescribe.test.js@@ -9,7 +9,7 @@ vi.mock('./aiProvider.js', async (importActual) => {// runPromptThroughProvider is the LLM boundary — mock it. assertProvider is// real (it's the typed-throw helper we want exercised end to end).-vi.mock('../lib/promptRunner.js', async (importActual) => {+vi.mock('./promptRunner.js', async (importActual) => {const actual = await importActual();return { ...actual, runPromptThroughProvider: vi.fn() };});@@ -22,7 +22,7 @@ vi.mock('./universeBuilder.js', async (importActual) => {});const aiProvider = await import('./aiProvider.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const universeBuilder = await import('./universeBuilder.js');const {describeEntityFromImages, correctEntityFromImage, VISION_KINDS, VISION_MAX_IMAGES, __testing,diff --git a/server/services/universeVisionExpand.js b/server/services/universeVisionExpand.jsindex e10ee6b30d..15be3f4c16 100644--- a/server/services/universeVisionExpand.js+++ b/server/services/universeVisionExpand.js@@ -31,7 +31,7 @@ import { getUniverse } from './universeBuilder.js';import { applyExpansion, STRING_FIELDS, LIST_FIELDS } from './universeCharacterExpand.js';import { bibleFieldIsBlank } from '../lib/universeBibleCompleteness.js';import { resolveAPIProvider, parseLLMJSON } from './aiProvider.js';-import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';+import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from './promptRunner.js';import { ServerError } from '../lib/errorHandler.js';import { shortId } from '../lib/fileUtils.js';diff --git a/server/services/universeVisionExpand.test.js b/server/services/universeVisionExpand.test.jsindex b0550d2297..76a6853427 100644--- a/server/services/universeVisionExpand.test.js+++ b/server/services/universeVisionExpand.test.js@@ -9,7 +9,7 @@ vi.mock('./aiProvider.js', async (importActual) => {// runPromptThroughProvider is the LLM boundary — mock it. assertProvider stays// real (the typed-throw helper we want exercised).-vi.mock('../lib/promptRunner.js', async (importActual) => {+vi.mock('./promptRunner.js', async (importActual) => {const actual = await importActual();return { ...actual, runPromptThroughProvider: vi.fn() };});@@ -22,7 +22,7 @@ vi.mock('./universeBuilder.js', async (importActual) => {});const aiProvider = await import('./aiProvider.js');-const promptRunner = await import('../lib/promptRunner.js');+const promptRunner = await import('./promptRunner.js');const universeBuilder = await import('./universeBuilder.js');const {expandEntityFromImages, buildVisionExpandPrompt, VISION_EXPAND_MAX_IMAGES, __testing,diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex 9280640a1d..c7b38d7fd8 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -9,9 +9,9 @@ import { readFile, readdir, rm } from 'fs/promises';import { PATHS, atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { stripCodeFences } from '../aiProvider.js';-import { runStagedLLM } from '../../lib/stageRunner.js';-import { extractBible } from '../../lib/bibleExtractor.js';-import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';+import { runStagedLLM } from '../stageRunner.js';+import { extractBible } from '../bibleExtractor.js';+import { extractScenes, SOURCE_KIND } from '../sceneExtractor.js';import { BIBLE_KIND } from '../../lib/storyBible.js';import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { CUT_TYPES } from '../../lib/editorial/cutApplier.js';diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.jsindex e4e0feb86a..ab0575c2c7 100644--- a/server/services/writersRoom/evaluator.test.js+++ b/server/services/writersRoom/evaluator.test.js@@ -5,9 +5,9 @@ import { describe, it, expect, vi } from 'vitest';// pure KIND_META map + the `cuts`/`revise` SHAPERS, which depend on nothing but// stripCodeFences (aiProvider) and CUT_TYPES (cutApplier, real).vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: vi.fn() }));-vi.mock('../../lib/bibleExtractor.js', () => ({ extractBible: vi.fn() }));-vi.mock('../../lib/sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: vi.fn() }));+vi.mock('../bibleExtractor.js', () => ({ extractBible: vi.fn() }));+vi.mock('../sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));vi.mock('../../lib/storyBible.js', () => ({ BIBLE_KIND: { CHARACTER: 'character', PLACE: 'place', OBJECT: 'object' } }));vi.mock('./local.js', () => ({ getWorkWithBody: vi.fn(), ensureWorkMediaCollection: vi.fn() }));vi.mock('../mediaCollections.js', () => ({ addItem: vi.fn(), ERR_DUPLICATE: 'DUP' }));diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.jsindex ab51a85e26..f56403f1f6 100644--- a/server/services/writersRoom/liveDirector.js+++ b/server/services/writersRoom/liveDirector.js@@ -14,7 +14,7 @@*/import { ServerError } from '../../lib/errorHandler.js';-import { runStagedLLM } from '../../lib/stageRunner.js';+import { runStagedLLM } from '../stageRunner.js';import {getWork, resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, utcDayKey,linkToCreativeDirector, renderWorkVoiceGuide,diff --git a/server/services/writersRoom/liveDirector.test.js b/server/services/writersRoom/liveDirector.test.jsindex 7e0525a62e..b1dabe75f9 100644--- a/server/services/writersRoom/liveDirector.test.js+++ b/server/services/writersRoom/liveDirector.test.js@@ -13,7 +13,7 @@ vi.mock('../../lib/fileUtils.js', async () => {// Stub the staged-LLM runner so the suggest path doesn't reach a real provider.const runStagedLLM = vi.fn();-vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));// Mock the Creative Director store + video-model helper so the CD-bridge send// path is a focused unit test of the orchestration (create → setTreatment →diff --git a/server/services/youtubeScheduler.js b/server/services/youtubeScheduler.jsindex 317d3a9ac7..a62cd6cff8 100644--- a/server/services/youtubeScheduler.js+++ b/server/services/youtubeScheduler.js@@ -18,7 +18,7 @@* user intent + a signed-in browser profile.*/-import { createSyncScheduler } from '../lib/createSettingsGatedSyncScheduler.js';+import { createSyncScheduler } from './createSettingsGatedSyncScheduler.js';import { getYoutubeConfig, runSync } from './youtubeSync.js';/**