Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): honor targetFormats in comic gates + gate fallback local runs

[._.]/ Adam Eivy114252d8e4c4
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index b01bee696e..fa442fa92f 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -48,6 +48,62 @@ function loadAutoFixer() {
export const DEFAULT_TIMEOUT_MS = 300000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
+// ── Local-backend concurrency gate ─────────────────────────────────────────
+// A local LLM server (Ollama / LM Studio on localhost) runs inference on one
+// GPU. Firing N stage calls at it concurrently (e.g. the 3 parallel
+// canon-extraction kinds) gains nothing — the backend serializes on the GPU
+// regardless — and, if the backend is configured for parallelism
+// (OLLAMA_NUM_PARALLEL > 1), it loads N model contexts at once and can spike
+// VRAM into an OOM/thrash. Cloud HTTP and CLI/TUI providers have no such
+// constraint. So we cap concurrent IN-FLIGHT calls per LOCAL endpoint and queue
+// the rest (FIFO). Default 1 (serialize); a beefy box can lift it with
+// LOCAL_LLM_MAX_CONCURRENCY. Keyed by endpoint so two distinct local servers
+// still run in parallel with each other.
+//
+// The gate lives HERE (the actual execution layer) rather than at the
+// stageRunner call site so it covers EVERY local execution: the initially
+// selected provider, a proactive createRun swap, AND a runtime fallback that
+// lands on a local backend after a remote/CLI primary fails. Gating only the
+// outer stageRunner call missed the fallback path — a failure storm could still
+// fire N concurrent calls at one local endpoint.
+const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
+export const isLocalEndpoint = (endpoint) =>
+ typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
+
+export const LOCAL_LLM_MAX_CONCURRENCY = Math.max(1, Number(process.env.LOCAL_LLM_MAX_CONCURRENCY) || 1);
+const localEndpointGates = new Map(); // endpoint -> { active: number, queue: (()=>void)[] }
+
+function acquireLocalSlot(endpoint) {
+ let gate = localEndpointGates.get(endpoint);
+ if (!gate) { gate = { active: 0, queue: [] }; localEndpointGates.set(endpoint, gate); }
+ if (gate.active < LOCAL_LLM_MAX_CONCURRENCY) {
+ gate.active += 1;
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => { gate.queue.push(resolve); });
+}
+
+function releaseLocalSlot(endpoint) {
+ const gate = localEndpointGates.get(endpoint);
+ if (!gate) return;
+ const next = gate.queue.shift();
+ if (next) next(); // hand the slot straight to the next waiter (active unchanged)
+ else gate.active = Math.max(0, gate.active - 1);
+}
+
+// Run `fn` under the local-endpoint gate when `provider` is a local API backend;
+// otherwise run it immediately (cloud / CLI / TUI are unconstrained).
+export async function withLocalConcurrencyGate(provider, fn) {
+ const endpoint = provider?.endpoint;
+ if (!(provider?.type === PROVIDER_TYPES.API && isLocalEndpoint(endpoint))) return fn();
+ await acquireLocalSlot(endpoint);
+ try {
+ return await fn();
+ } finally {
+ releaseLocalSlot(endpoint);
+ }
+}
+
// Cooldown per error category — how long the failed provider is marked
// unavailable so subsequent calls skip it and proactively use the fallback.
// USAGE_LIMIT is absent because `markUsageLimit` parses the wait time
@@ -308,7 +364,10 @@ export async function runPromptThroughProvider(args) {
}
try {
- return await executeProviderRunOnce(args);
+ // Gate on the requested provider; a proactive createRun swap to a local
+ // backend is still covered because executeProviderRunOnce dispatches by the
+ // provider it actually runs and the gate is a no-op for non-local providers.
+ return await withLocalConcurrencyGate(args.provider, () => executeProviderRunOnce(args));
} catch (firstError) {
// Only retry when the failure came from the execution layer (annotated
// by safeReject with effectiveProvider). Pre-execution throws —
@@ -370,12 +429,15 @@ export async function runPromptThroughProvider(args) {
// doesn't exist on the fallback.
let fallbackResult;
try {
- fallbackResult = await executeProviderRunOnce({
+ // Gate the fallback too: a remote/CLI primary that fails over to a local
+ // backend must still serialize against that endpoint (the failure-storm
+ // case the outer stageRunner wrap used to miss).
+ fallbackResult = await withLocalConcurrencyGate(fallback, () => executeProviderRunOnce({
...args,
provider: fallback,
model: picked.model ?? undefined,
runId: undefined, // fresh runId so the failed primary's record stays intact
- });
+ }));
} catch (fallbackError) {
// Both failed — release the primary's suppression (the fallback's own
// failure already queued its investigation task) and rethrow.
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index f8951b656c..4c53dee111 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -16,7 +16,7 @@
import { ServerError } from './errorHandler.js';
import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';
-import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS } from './promptRunner.js';
+import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, isLocalEndpoint } from './promptRunner.js';
import { stripCodeFences } from './aiProvider.js';
import { extractCodexAssistant } from './codexAssistantExtract.js';
import { getActiveProvider, getProviderById } from '../services/providers.js';
@@ -122,54 +122,16 @@ export function knownProviderContextWindow(provider) {
return null;
}
-const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
-const isLocalEndpoint = (endpoint) =>
- typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
-
-// ── Local-backend concurrency gate ─────────────────────────────────────────
-// A local LLM server (Ollama / LM Studio on localhost) runs inference on one
-// GPU. Firing N stage calls at it concurrently (e.g. the 3 parallel
-// canon-extraction kinds) gains nothing — the backend serializes on the GPU
-// regardless — and, if the backend is configured for parallelism
-// (OLLAMA_NUM_PARALLEL > 1), it loads N model contexts at once and can spike
-// VRAM into an OOM/thrash. Cloud HTTP and CLI/TUI providers have no such
-// constraint. So we cap concurrent IN-FLIGHT stage calls per LOCAL endpoint and
-// queue the rest (FIFO). Default 1 (serialize); a beefy box can lift it with
-// LOCAL_LLM_MAX_CONCURRENCY. Keyed by endpoint so two distinct local servers
-// still run in parallel with each other.
-export const LOCAL_LLM_MAX_CONCURRENCY = Math.max(1, Number(process.env.LOCAL_LLM_MAX_CONCURRENCY) || 1);
-const localEndpointGates = new Map(); // endpoint -> { active: number, queue: (()=>void)[] }
-
-function acquireLocalSlot(endpoint) {
- let gate = localEndpointGates.get(endpoint);
- if (!gate) { gate = { active: 0, queue: [] }; localEndpointGates.set(endpoint, gate); }
- if (gate.active < LOCAL_LLM_MAX_CONCURRENCY) {
- gate.active += 1;
- return Promise.resolve();
- }
- return new Promise((resolve) => { gate.queue.push(resolve); });
-}
-
-function releaseLocalSlot(endpoint) {
- const gate = localEndpointGates.get(endpoint);
- if (!gate) return;
- const next = gate.queue.shift();
- if (next) next(); // hand the slot straight to the next waiter (active unchanged)
- else gate.active = Math.max(0, gate.active - 1);
-}
-
-// Run `fn` under the local-endpoint gate when `provider` is a local API backend;
-// otherwise run it immediately (cloud / CLI / TUI are unconstrained).
-export async function withLocalConcurrencyGate(provider, fn) {
- const endpoint = provider?.endpoint;
- if (!(provider?.type === 'api' && isLocalEndpoint(endpoint))) return fn();
- await acquireLocalSlot(endpoint);
- try {
- return await fn();
- } finally {
- releaseLocalSlot(endpoint);
- }
-}
+// The local-backend concurrency gate (cap concurrent in-flight calls per local
+// endpoint so N parallel stage calls don't thrash one GPU's VRAM) lives in
+// promptRunner.js — the actual execution layer — so it covers the initially
+// selected provider, a proactive createRun swap, AND a runtime fallback that
+// lands on a local backend. Re-exported here for callers/tests that reference
+// the gate by its historical stageRunner path. `isLocalEndpoint` is shared from
+// the same module so the context-window heuristic below and the gate agree on
+// what "local" means.
+export { withLocalConcurrencyGate, LOCAL_LLM_MAX_CONCURRENCY } from './promptRunner.js';
+export { isLocalEndpoint };
// CLI/TUI providers (Claude Code, Codex, Antigravity) are frontier models;
// non-local API providers are cloud. Local backends (ollama/lmstudio on
@@ -492,10 +454,15 @@ async function executeStagePrompt({ stage, label, prompt, options }) {
// (runId / model / providerId) here so the persisted stage result points
// at the run that actually produced the text — otherwise pipeline history
// / restore links land on a failed record.
- const runResult2 = await withLocalConcurrencyGate(effectiveProvider, () => runPromptThroughProvider({
+ // The local-backend concurrency gate is applied INSIDE runPromptThroughProvider
+ // (around each actual execution — primary, proactive swap, and runtime
+ // fallback), so we do NOT wrap here: a second gate on the same local endpoint
+ // would deadlock against the inner one (outer holds the only slot, inner waits
+ // forever).
+ const runResult2 = await runPromptThroughProvider({
provider: effectiveProvider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,
timeout: effectiveTimeout,
- }));
+ });
const { text } = runResult2;
let finalRunId = runId;
let finalProvider = effectiveProvider;
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index a4871e1721..f623951b99 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -194,6 +194,28 @@ export function isComicTarget(series) {
return (series?.targetFormat || 'comic+tv').includes('comic');
}
+// Does THIS run want the comic format? `isComicTarget` alone keys off the
+// series' declared format, but a per-run `options.targetFormats` restriction can
+// scope a comic+tv series to TV only — in which case the comic-only steps
+// (scriptVerify, visual draft) must NOT run, or a TV-only pass would enter
+// comic-script verification with no comicScript and pause on an unparseable
+// script. Mirrors the restriction logic in requiredScriptStages: an empty/absent
+// restriction (or one that excludes everything the series supports) means "all
+// formats the series wants", so this stays true for the default whole-series run.
+export function wantsComic(series, options = {}) {
+ if (!isComicTarget(series)) return false;
+ const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length
+ ? options.targetFormats
+ : null;
+ if (!restrict) return true;
+ // If the restriction excludes every format the series supports, requiredScriptStages
+ // ignores it (never strand the run) — match that here so the gates agree.
+ const wantComic = restrict.includes('comic');
+ const wantTv = restrict.includes('tv') && (series?.targetFormat || '').includes('tv');
+ if (!wantComic && !wantTv) return true; // restriction is a no-op → whole series
+ return wantComic;
+}
+
// Effective "produce draft visuals?" decision. The `target` option overrides
// the `includeVisual` flag: 'text' forces text-only (no canon gate, no render),
// 'visual' forces visuals, and 'auto' (the default) honors `includeVisual`
@@ -314,8 +336,11 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
}
}
- // STEP 4c — structural script gate (comic targets only).
- if (isComicTarget(series)) {
+ // STEP 4c — structural script gate (comic targets only). Gate on wantsComic,
+ // not bare isComicTarget, so a TV-only run of a comic+tv series doesn't enter
+ // comic-script verification with no comicScript (which would pause on an
+ // unparseable script).
+ if (wantsComic(series, options)) {
for (const issue of ordered) {
if (setHas(runState.scriptChecked, issue.id)) continue;
return { kind: 'scriptVerify', issueId: issue.id, reason: 'comic script not yet structurally verified' };
@@ -348,12 +373,12 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
// canon noun that appears where it'd be drawn must be described (an artist
// can't render a name). Runs once per run; the gate blocks (pauses) on
// undescribed drawn nouns. Only relevant when visuals will be produced.
- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && isComicTarget(series) && !runState.canonVerified) {
+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options) && !runState.canonVerified) {
return { kind: 'canonVerify', reason: 'canon descriptive integrity not yet verified this run' };
}
// STEP 6 — draft visuals (cover + back + all interior pages).
- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && isComicTarget(series)) {
+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {
for (const issue of ordered) {
if (setHas(runState.visualDrafted, issue.id)) continue;
if (visualReady(issue)) continue;
@@ -1017,7 +1042,7 @@ function buildDryRunPlan(series, issues, options) {
if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded });
const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;
if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded });
- if (isComicTarget(series)) plan.push({ kind: 'scriptVerify', count: ordered.length });
+ if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: ordered.length });
const edRounds = Number.isInteger(options?.maxEditorialRounds) ? options.maxEditorialRounds : MAX_EDITORIAL_ROUNDS;
plan.push({ kind: 'editorialReview', count: 1, note: roundsNote(edRounds) });
// maxEditorialRounds === 0 skips the whole editorial gate in execute mode
@@ -1028,7 +1053,7 @@ function buildDryRunPlan(series, issues, options) {
plan.push({ kind: 'editorialChecks', count: 1, note: 'enabled editorial checks (#1284)' });
plan.push({ kind: 'editorialHealthGate', count: 1, note: 'editorial health readiness gate (#1316)' });
}
- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && isComicTarget(series)) {
+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {
plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns' });
const visualNeeded = ordered.filter((i) => !visualReady(i)).length;
if (visualNeeded) plan.push({ kind: 'visualDraft', count: visualNeeded, note: 'cover + back + all pages (draft)' });
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index f9738e7b42..a653853c8a 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -117,7 +117,7 @@ const seriesSvc = await import('./series.js');
const seasonsSvc = await import('./seasons.js');
const issuesSvc = await import('./issues.js');
const autopilot = await import('./seriesAutopilot.js');
-const { resolveNextStep, requiredScriptStages, scriptStructurallyReady, visualReady } = autopilot;
+const { resolveNextStep, requiredScriptStages, scriptStructurallyReady, visualReady, wantsComic } = autopilot;
// A comic script string that parseComicScript turns into >=1 page/panel.
const VALID_SCRIPT = 'PAGE 1\nPANEL 1\nA scene.';
@@ -388,6 +388,29 @@ describe('requiredScriptStages / scriptStructurallyReady', () => {
});
});
+describe('wantsComic (per-run comic gating)', () => {
+ it('honors the series format when no restriction is given', () => {
+ expect(wantsComic({ targetFormat: 'comic+tv' })).toBe(true);
+ expect(wantsComic({ targetFormat: 'comic' })).toBe(true);
+ expect(wantsComic({ targetFormat: 'tv' })).toBe(false);
+ });
+
+ it('is false for a comic+tv series restricted to tv-only (so comic gates do NOT run)', () => {
+ // This is the bug: a ['tv'] run must NOT enter scriptVerify/visual on a
+ // comic+tv series, or it would verify a comic script that was never authored.
+ expect(wantsComic({ targetFormat: 'comic+tv' }, { targetFormats: ['tv'] })).toBe(false);
+ expect(wantsComic({ targetFormat: 'comic+tv' }, { targetFormats: ['comic'] })).toBe(true);
+ expect(wantsComic({ targetFormat: 'comic+tv' }, { targetFormats: ['comic', 'tv'] })).toBe(true);
+ });
+
+ it('treats a restriction the series cannot satisfy as a no-op (matches requiredScriptStages)', () => {
+ // comic-only series asked for tv-only → requiredScriptStages falls back to
+ // comic; wantsComic must agree (still wants comic) so the run isn't stranded.
+ expect(wantsComic({ targetFormat: 'comic' }, { targetFormats: ['tv'] })).toBe(true);
+ expect(wantsComic({ targetFormat: 'comic+tv' }, { targetFormats: [] })).toBe(true);
+ });
+});
+
describe('visualReady', () => {
const cover = { proofImage: { jobId: 'c' } };
const backCover = { proofImage: { jobId: 'b' } };