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
let Series Autopilot force one provider/model across every stage
[._.]/ Adam Eivy11d601a71ed1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2460c62e87..8effb1462e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@- CoS now notices when a scheduled task (the overnight branch-reconcile loop) finishes the same work over and over in short-lived agent runs. It parks a looping coordinator so it stops burning quota, files one GitHub issue to fix the drain, and records per-run duration so the burst is visible as a metric.- Git submodules are now managed per app instead of on one global Dev Tools page. Any managed app whose repo has a `.gitmodules` gets a Submodules tab showing each submodule against its remote, so PortOS's own bundled slashdo is maintained from the PortOS app page alongside its git, processes and update controls. Updating a submodule can now also commit the pointer bump for you: leave "Commit the pointer bump" on and the update stages just that submodule and commits it on the repo's default branch. It refuses to commit — and says why — when the repo is checked out on some other branch, so the bump can't land in the middle of unrelated work. The old `/devtools/submodules` link redirects to PortOS's own tab.- The Usage page can now record what you pay each month for your AI subscriptions (Claude, Codex, Antigravity, Grok) and shows what those plans saved against the estimated API cost. Each plan's price is prorated across whatever report window is selected, so both sides of the comparison cover the same days, and every plan gets its own row: monthly price, cost for this window, the API-rate cost its usage ran up, and the difference. Usage no subscription covers — pay-as-you-go API providers and pre-breakdown legacy rows — is reported separately instead of being credited to a plan.+- Series Autopilot can now run every stage on one provider and model. Picking a provider for a run only ever set a *soft* default, so any stage carrying its own pin on the Prompts page kept its own provider, model or reasoning effort — which meant "run this series on Sol" quietly left script verification (pinned to Codex in the shipped stage config) and every other pinned stage where it was. A new "Use this provider and model for every stage" option under Autopilot → Options overrides those pins for the whole run, including the judge pin, and is saved as a default for future runs. Scheduled runs get the same checkbox next to their provider picker. Stage *tiers* (quick/coding/heavy) still resolve against whichever provider ends up running, and the separate judge and per-stage routes in the same panel still win — the option removes the stage-config pins from the comparison, not your own choices. Leaving it off keeps today's behaviour exactly.## Fixeddiff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 20b22d44c4..c68d144f85 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -65,6 +65,9 @@ const DEFAULT_OBSERVER = false;// Evidence is collected regardless; routing stays opt-in so a series cannot// silently switch models merely because a sample threshold was reached.const DEFAULT_AUTO_SELECT_MODELS = false;+// Force the run's route onto stages pinned on the Prompts page — mirror the+// server default (off).+const DEFAULT_OVERRIDE_STAGE_PINS = false;const AUTOPILOT_LLM_STAGES = [['characterFoundation', 'Character foundation'],['generateArc', 'Generate arc'],@@ -219,6 +222,11 @@ const OPTION_SPECS = {read: readBoolean,persistOnEdit: true,},+ overrideStagePins: {+ defaultValue: DEFAULT_OVERRIDE_STAGE_PINS,+ read: readBoolean,+ persistOnEdit: true,+ },};// A single numeric field for the Options popover (round bounds + the pause@@ -956,7 +964,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate) : null}. Stages pinned in{' '}<Link to="/prompts" className="text-port-accent hover:underline">Prompts</Link>{' '}- keep their own provider/model/effort+ {opt.overrideStagePins ? 'are overridden for this run' : 'keep their own provider/model/effort'}{effectiveEffort ? '.' : (<>; reasoning effort comes from the provider's config on{' '}<Link to="/ai" className="text-port-accent hover:underline">AI Providers</Link>.@@ -987,6 +995,24 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateemptyModelOption={inheritedModel ? `Series default (${inheritedModel})` : 'Default model'}/></div>+ <label className="flex items-center gap-2 text-xs text-gray-300 pt-1">+ <input+ type="checkbox"+ checked={opt.overrideStagePins}+ onChange={(e) => options.edit('overrideStagePins', e.target.checked)}+ />+ Use this provider and model for every stage (ignore Prompts stage pins)+ </label>+ {opt.overrideStagePins ? (+ <p className="text-[11px] text-gray-500 pl-5">+ Stages that pin their own provider, model id, reasoning effort or judge in{' '}+ <Link to="/prompts" className="text-port-accent hover:underline">Prompts</Link>{' '}+ run on this route instead, so the whole pipeline — script verification included — stays on one provider.+ A stage pinned to a local provider to keep manuscript text off the network loses that too.+ Stage <em>tiers</em> (quick / coding / heavy) still apply when you leave the model blank,+ and the judge and per-stage routes below still win where you set them.+ </p>+ ) : null}<label className="flex items-center gap-2 text-xs text-gray-300 pt-1"><inputtype="checkbox"diff --git a/client/src/components/pipeline/SeriesAutopilotSchedule.jsx b/client/src/components/pipeline/SeriesAutopilotSchedule.jsxindex fc006a328a..d29abd6aeb 100644--- a/client/src/components/pipeline/SeriesAutopilotSchedule.jsx+++ b/client/src/components/pipeline/SeriesAutopilotSchedule.jsx@@ -128,6 +128,9 @@ export default function SeriesAutopilotSchedule({ series, providers = [], activeconst setProvider = async (provider) => persist({ ...entry, provider: provider || undefined, model: undefined, effort: undefined });const setModel = async (model) => persist({ ...entry, model: model || undefined });const setEffort = async (effort) => persist({ ...entry, effort: effort || undefined });+ // Stored as a plain boolean; `runOptionsFor` forwards only an explicit `true`,+ // so an unticked schedule still inherits the saved pipelineEditorialChecks default.+ const setOverrideStagePins = async (on) => persist({ ...entry, overrideStagePins: on });const removeSchedule = async () => {await persist(null);@@ -219,6 +222,15 @@ export default function SeriesAutopilotSchedule({ series, providers = [], activeemptyProviderOption={`Use series default (${providerLabel(series?.llm?.provider || activeProviderId)})`}emptyModelOption="Default model"/>+ <label className="flex items-center gap-2 text-xs text-gray-300 pt-1.5">+ <input+ type="checkbox"+ checked={entry?.overrideStagePins === true}+ disabled={saving}+ onChange={(e) => setOverrideStagePins(e.target.checked)}+ />+ Use it for every stage (ignore Prompts stage pins)+ </label></div>{cosMode === 'off' ? (diff --git a/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx b/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsxindex 67df235071..cdf11be909 100644--- a/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx+++ b/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx@@ -57,7 +57,7 @@ it('names the effective provider/model and the cos budget cap in the consent copit('enable toggle is OFF by default and enabling persists enabled:true', async () => {getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));render(<SeriesAutopilotSchedule series={SERIES} {...providerProps()} />);- const toggle = await screen.findByRole('checkbox');+ const toggle = await screen.findByRole('checkbox', { name: /Enable scheduled autopilot/ });expect(toggle).not.toBeChecked();fireEvent.click(toggle);await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalled());@@ -74,7 +74,7 @@ it('preserves OTHER series schedules when saving this one', async () => {{ seriesId: 's1', enabled: false, cron: '0 3 * * *' },]));render(<SeriesAutopilotSchedule series={SERIES} {...providerProps()} />);- const toggle = await screen.findByRole('checkbox');+ const toggle = await screen.findByRole('checkbox', { name: /Enable scheduled autopilot/ });fireEvent.click(toggle);await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalled());const ids = patchSettingsSlice.mock.calls[0][1].schedules.map((s) => s.seriesId);diff --git a/server/lib/README.md b/server/lib/README.mdindex bf80bac9bd..729cf52930 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -106,6 +106,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. || `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. || `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 931918ea90..7d6fb2b7f3 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -143,6 +143,7 @@ export * from './opencodeConfig.js';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 './tuiUsageScrape.js';diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex 67ddf64c96..9eb447dfb9 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -290,6 +290,14 @@ export const pipelineEditorialChecksSettingsSchema = z.object({// this opt-in permits sufficiently sampled recommendations to become the// run's soft provider/model/effort defaults. Explicit run/stage pins win.autoSelectModels: z.boolean().optional(),+ // Series Autopilot: run the whole pipeline on ONE provider/model/effort by+ // ignoring the per-stage pins set on the Prompts page. Defaults OFF (opt-in),+ // and persistable unlike unlockForRun — it re-routes spend but mutates+ // nothing, and an unattended scheduled run is exactly where "always use my+ // one provider" belongs. Optional + additive so older peers fall through to+ // off. See seriesAutopilot/config.js#resolveAutopilotOverrideStagePins and+ // lib/stagePinPolicy.js.+ overrideStagePins: z.boolean().optional(),}).strict();// Cursor-context payload for the CD-bridge suggest route — identical shape todiff --git a/server/lib/stagePinPolicy.js b/server/lib/stagePinPolicy.jsnew file mode 100644index 0000000000..ebf92b5741--- /dev/null+++ b/server/lib/stagePinPolicy.js@@ -0,0 +1,61 @@+/**+ * Run-scoped "ignore per-stage LLM pins" policy.+ *+ * Series Autopilot threads its run provider/model/effort as SOFT defaults+ * (stageRunner's `providerDefault`/`modelDefault`/`effortDefault`) so a+ * deliberate per-stage pin from the Prompts page keeps winning for that stage.+ * That is the right default — but it means "run this whole series on Sol"+ * silently leaves `pipeline-script-verify` (pinned to codex in the shipped+ * stage config) and every other pinned stage on their own provider. Users who+ * want ONE provider/model for an entire run had no way to say so.+ *+ * This module is the switch: `withStagePinsIgnored(true, fn)` marks the whole+ * async subtree of `fn` as "the run's defaults outrank stage pins", and+ * `stagePinsIgnored()` reads it. WHICH fields count as a pin is stageRunner's+ * business, enumerated once in its `effectiveStage` — this module knows only+ * that a run asked for it.+ *+ * Why AsyncLocalStorage rather than another option key: the flag has to reach+ * EVERY leaf LLM call an autopilot run makes, and those calls fan out through a+ * dozen intermediate services (textStages, autoRunner, volumeBeatsRunner,+ * reverseOutline, scriptVerify, editorial checkRunner, arcPlanner, the judges,+ * canon extraction) that each forward a hand-picked subset of option keys under+ * two different naming conventions (`providerDefault` vs `providerIdDefault`) —+ * and some, like `verifyComicScript`, accept only the soft names. Threading one+ * more key through all of them is a dozen edits where a single missed forward+ * is an invisible hole, which is the very failure this feature fixes. An+ * async-context flag has one set site and one read site and cannot be dropped+ * in the middle; it also reaches `resolveStageContext` (prompt budgeting) for+ * free, which no option thread would have.+ *+ * Scope safety: an AsyncLocalStorage store propagates only to async work+ * *created* inside `fn`. A shared queue (the local-LLM concurrency gate) resumes+ * each waiter through a promise the waiter itself created, so it keeps the+ * enqueuer's context — one autopilot run in force mode cannot re-route a+ * concurrent manual stage call.+ *+ * Privacy note: a stage pinned to a local provider so manuscript text never+ * leaves the machine loses that guarantee under this flag, by construction —+ * the user is asking for one provider everywhere. The Autopilot Options copy+ * says so at the checkbox; do not quietly exempt a path here instead.+ */++import { AsyncLocalStorage } from 'node:async_hooks';++const storage = new AsyncLocalStorage();++/**+ * Run `fn` with per-stage provider/model/effort pins ignored (when `ignore` is+ * true). Returns whatever `fn` returns — including its promise, so the whole+ * async subtree stays inside the context. A falsy `ignore` calls `fn` directly+ * so the ordinary path never allocates a context.+ */+export function withStagePinsIgnored(ignore, fn) {+ if (ignore !== true) return fn();+ return storage.run(true, fn);+}++/** True when the current async context asked for stage pins to be ignored. */+export function stagePinsIgnored() {+ return storage.getStore() === true;+}diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.jsindex 171ff0466e..54e06d64bc 100644--- a/server/lib/stageRunner.js+++ b/server/lib/stageRunner.js@@ -22,6 +22,7 @@ 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';@@ -37,6 +38,35 @@ const TIER_TO_MODEL_KEY = Object.freeze({const isTierName = (m) => typeof m === 'string' && m in TIER_TO_MODEL_KEY;+// Every stage-config field that names a ROUTE. `withStagePinsIgnored`+// (lib/stagePinPolicy.js) strips exactly these so a run told to use ONE+// provider/model actually does — see that module for why the switch is an+// async-context flag. Enumerated HERE, once: the resolvers below then need no+// per-pin conditionals, and adding a routing pin to the stage schema means+// adding it to this list and nowhere else.+const ROUTING_PIN_FIELDS = Object.freeze(['provider', 'effort', 'judgeProvider', 'judgeModel']);++// The stage as the resolvers below should see it. Identity unless the current+// run asked to ignore pins, in which case the routing fields above are dropped.+//+// Two fields deliberately SURVIVE:+// - a `model` TIER (default/quick/coding/heavy) — a per-provider mapping, not+// a pin. It already loses to `modelDefault`, and it is the right fallback+// for a run that forced a provider without naming a model. Only an explicit+// model id is dropped.+// - `timeout` — it encodes how long the stage's WORK takes (a whole-manuscript+// editorial pass vs a one-line classification), not which provider runs it.+// Dropping it to the provider default would abort the long stages, not+// rescue them; a timeout genuinely too tight for a forced local model is a+// stage-config edit, not a run option.+export function effectiveStage(stage) {+ if (!stage || !stagePinsIgnored()) return stage;+ const stripped = { ...stage };+ for (const field of ROUTING_PIN_FIELDS) delete stripped[field];+ if (stripped.model && !isTierName(stripped.model)) delete stripped.model;+ return stripped;+}+// First-element fallback when defaultModel is unset on a provider that// exposes a `models` array (some toolkit-configured providers ship a model// list but no explicit default). Without this, API-side runners that require@@ -105,6 +135,9 @@ export function resolveModel(provider, modelHint) {// 3. modelDefault — the run-level soft default (Series Autopilot's run model)// 4. stage.model tier — the stage's default tier mapping (default/quick/coding/heavy)// 5. provider default — resolveModel's own fallback+//+// Takes an `effectiveStage`-masked stage, so step 2 is already gone for a run+// that forced one model across every stage.function resolveModelHint(stage, options = {}) {const stageModel = stage?.model;const stagePin = stageModel && !isTierName(stageModel) ? stageModel : null;@@ -128,6 +161,9 @@ function resolveModelHint(stage, options = {}) {// The result is safe to pass unconditionally: `runPromptThroughProvider` clamps// it to the provider's (and, for Antigravity, the model's) ladder and drops it// entirely for a provider with no effort control.+//+// Takes an `effectiveStage`-masked stage, so step 2 is already gone for a run+// that forced one route across every stage.export function resolveEffortHint(stage, options = {}) {return options.effortOverride || stage?.effort || options.effortDefault || null;}@@ -225,7 +261,7 @@ export function effectiveContextWindow(provider, model) {* to a different (possibly smaller-window) provider is not reflected here.*/export async function resolveStageContext(stageName, options = {}) {- const stage = getStage(stageName);+ const stage = effectiveStage(getStage(stageName));const provider = await resolveProviderForStage(stage, options);const requestedModel = resolveModel(provider, resolveModelHint(stage, options));const model = resolveEffectiveModel(provider, requestedModel);@@ -246,6 +282,11 @@ export async function resolveStageContext(stageName, options = {}) {// if it's unavailable we fall through to the active provider rather than// throwing, because it was never a per-call demand.// 4. The active provider — the system-wide fallback.+//+// Takes an `effectiveStage`-masked stage, so step 2 is already gone for a run+// that forced one provider across every stage. Because the pin is *stripped*+// rather than demoted, such a run also stops throwing STAGE_PROVIDER_UNAVAILABLE+// for a stage pinned to a provider that no longer exists.async function resolveProviderForStage(stage, { providerOverride, providerDefault } = {}) {if (providerOverride) {const pinned = await getProviderById(providerOverride).catch(() => null);@@ -296,6 +337,15 @@ export async function resolveJudgeForStage(stage, options = {}) {// An explicit per-call `providerOverride` is a deliberate "judge with THIS// provider right now" demand — it beats a stage-level judge pin (mirrors how// resolveProviderForStage lets providerOverride beat stage.provider).+ //+ // The stage is masked first because this one is CALLER-supplied (pipelineJudge+ // / foundationJudge / seriesGenerate hand us a writer stage they read+ // themselves) rather than read from `getStage` here. A run that forced one+ // route loses the stage judge pin with it and falls through to the writer+ // resolution below — note that this collapses the writer/judge split for that+ // stage unless the run configured its own judge route, which sets+ // `providerOverride` and short-circuits above.+ stage = effectiveStage(stage);if (!options.providerOverride && stage?.judgeProvider) {const pinned = await getProviderById(stage.judgeProvider).catch(() => null);if (pinned?.enabled) {@@ -432,7 +482,7 @@ export function extractJson(text, { promptToStrip } = {}) {* 'writers-room-evaluate') so /runs is filterable*/export async function runStagedLLM(stageName, variables, options = {}) {- const stage = getStage(stageName);+ const stage = effectiveStage(getStage(stageName));const prompt = await buildPrompt(stageName, variables);return executeStagePrompt({ stage, label: stageName, prompt, options });}@@ -465,6 +515,11 @@ export async function runInlineLLM(prompt, options = {}) {* prompt body is still caller-supplied (no stage template is rendered). With a* falsy `stageName` this is identical to `runInlineLLM` (active/overridden provider).*+ * That routing guarantee is only as strong as the stage pin behind it: a run+ * inside `withStagePinsIgnored` has asked for ONE provider everywhere, so this+ * follows the run's provider rather than the stage's. The Autopilot Options copy+ * warns at the checkbox; see lib/stagePinPolicy.js.+ ** Same options as runStagedLLM (providerOverride / modelOverride /* timeoutOverride / returnsJson / source).*/@@ -472,7 +527,7 @@ export async function runStageScopedInlineLLM(stageName, prompt, options = {}) {if (typeof prompt !== 'string' || !prompt.trim()) {throw new ServerError('runStageScopedInlineLLM requires a non-empty prompt', { status: 400, code: 'INLINE_PROMPT_REQUIRED' });}- const stage = stageName ? getStage(stageName) : null;+ const stage = stageName ? effectiveStage(getStage(stageName)) : null;return executeStagePrompt({ stage, label: options.source || stageName || 'inline-llm', prompt, options });}diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.jsindex 085a0e4b46..19544b8c00 100644--- a/server/lib/stageRunner.test.js+++ b/server/lib/stageRunner.test.js@@ -39,9 +39,11 @@ const {resolveStageContext,resolveJudgeForStage,resolveEffortHint,+ effectiveStage,withLocalConcurrencyGate,LOCAL_LLM_MAX_CONCURRENCY,} = await import('./stageRunner.js');+const { withStagePinsIgnored, stagePinsIgnored } = await import('./stagePinPolicy.js');const apiProvider = (extra = {}) => ({id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,@@ -783,3 +785,108 @@ describe('stageRunner — effort threading into the run (#3641)', () => {expect(buildEffortArgs(effort, { id: 'openai-api', type: 'api' })).toEqual([]);});});++// "Use one provider/model for every stage" (Series Autopilot's overrideStagePins).+// The switch is an async-context flag rather than an option key — these assert+// that flipping it changes exactly the four pin lookups and nothing else, and+// that the flag does not leak outside the wrapped subtree.+describe('stageRunner — withStagePinsIgnored', () => {+ const onComplete = (text) => async ({ onData, onComplete: done }) => { onData(text); done({ success: true }); };++ it('skips stage.provider so the run-level providerDefault wins', async () => {+ prompts.getStage.mockReturnValue({ provider: 'stage-pinned' });+ providers.getProviderById.mockImplementation(async (id) => apiProvider({ id }));+ runner.executeApiRun.mockImplementation(onComplete('ok'));+ const out = await withStagePinsIgnored(true, () =>+ runStagedLLM('s', {}, { providerDefault: 'run-default' }));+ expect(out.providerId).toBe('run-default');+ });++ it('skips a stage.provider pin whose provider is gone instead of throwing', async () => {+ prompts.getStage.mockReturnValue({ provider: 'pinned-but-gone' });+ providers.getProviderById.mockResolvedValue(null);+ providers.getActiveProvider.mockResolvedValue(apiProvider());+ runner.executeApiRun.mockImplementation(onComplete('ok'));+ const out = await withStagePinsIgnored(true, () => runStagedLLM('s', {}));+ expect(out.providerId).toBe('mock-api');+ });++ it('skips an explicit stage.model pin so modelDefault wins', async () => {+ prompts.getStage.mockReturnValue({ model: 'pinned-model-id' });+ providers.getActiveProvider.mockResolvedValue(apiProvider());+ runner.executeApiRun.mockImplementation(onComplete('ok'));+ const out = await withStagePinsIgnored(true, () =>+ runStagedLLM('s', {}, { modelDefault: 'run-model' }));+ expect(out.model).toBe('run-model');+ });++ it('keeps resolving a stage TIER — a tier is a per-provider mapping, not a pin', async () => {+ prompts.getStage.mockReturnValue({ model: 'heavy' });+ providers.getActiveProvider.mockResolvedValue(apiProvider({ heavyModel: 'h' }));+ runner.executeApiRun.mockImplementation(onComplete('ok'));+ const out = await withStagePinsIgnored(true, () => runStagedLLM('s', {}));+ expect(out.model).toBe('h');+ });++ it('drops a stage.effort pin so the run-level effortDefault reaches the runner', async () => {+ prompts.getStage.mockReturnValue({ effort: 'low' });+ providers.getActiveProvider.mockResolvedValue(cliProvider());+ runner.executeCliRun.mockImplementation(async ({ onComplete: done }) => { done({ success: true }); });+ await withStagePinsIgnored(true, () => runStagedLLM('s', {}, { effortDefault: 'high' }));+ expect(runner.executeCliRun.mock.calls[0][0].provider.effort).toBe('high');+ });++ it('skips a stage judge pin so the judge follows the forced writer route', async () => {+ const active = apiProvider({ id: 'run-api', defaultModel: 'run-model' });+ providers.getActiveProvider.mockResolvedValue(active);+ providers.getProviderById.mockImplementation(async (id) => apiProvider({ id, defaultModel: `${id}-m` }));+ const pinned = await resolveJudgeForStage({ judgeProvider: 'judge-cli' });+ expect(pinned.provider.id).toBe('judge-cli');+ const out = await withStagePinsIgnored(true, () => resolveJudgeForStage({ judgeProvider: 'judge-cli' }));+ expect(out.provider.id).toBe('run-api');+ expect(out.model).toBe('run-model');+ });++ it('changes nothing when the flag is off', async () => {+ prompts.getStage.mockReturnValue({ provider: 'stage-pinned' });+ providers.getProviderById.mockImplementation(async (id) => apiProvider({ id }));+ runner.executeApiRun.mockImplementation(onComplete('ok'));+ const off = await withStagePinsIgnored(false, () =>+ runStagedLLM('s', {}, { providerDefault: 'run-default' }));+ expect(off.providerId).toBe('stage-pinned');+ });++ // The pin list itself, since every resolver now reads a masked stage rather+ // than testing pins one at a time — this is the one place that says WHICH+ // fields the switch strips and which deliberately survive.+ it('effectiveStage strips exactly the routing pins, keeping the tier and the timeout', () => {+ const stage = {+ provider: 'p', model: 'pinned-model-id', effort: 'low', judgeProvider: 'jp', judgeModel: 'jm',+ timeout: 60_000, template: 'x',+ };+ expect(effectiveStage(stage)).toBe(stage); // identity outside a forced run+ const masked = withStagePinsIgnored(true, () => effectiveStage(stage));+ expect(masked).toEqual({ timeout: 60_000, template: 'x' });+ expect(stage.provider).toBe('p'); // the caller's stage object is not mutated+ // A tier is a per-provider mapping, not a pin — it survives.+ expect(withStagePinsIgnored(true, () => effectiveStage({ model: 'heavy' }))).toEqual({ model: 'heavy' });+ expect(withStagePinsIgnored(true, () => effectiveStage(null))).toBeNull();+ });++ it('does not reach a concurrent call outside the context (async-context scoping)', async () => {+ let insideSaw;+ let outsideSaw;+ await Promise.all([+ withStagePinsIgnored(true, async () => {+ await new Promise((r) => setTimeout(r, 5));+ insideSaw = stagePinsIgnored();+ }),+ (async () => {+ await new Promise((r) => setTimeout(r, 1));+ outsideSaw = stagePinsIgnored();+ })(),+ ]);+ expect(insideSaw).toBe(true);+ expect(outsideSaw).toBe(false);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 7ff0abb255..e6d08d8a89 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -611,6 +611,10 @@ export const seriesAutopilotScheduleSchema = z.object({// effort-capable CLIs; the runner clamps a level the chosen provider doesn't// offer and drops it for a provider with no effort control.effort: z.preprocess((v) => (v === '' ? undefined : v), z.enum(EFFORT_LEVELS).optional()),+ // Run every stage on the provider/model above, ignoring the per-stage pins+ // from the Prompts page. Absent falls through to the persisted+ // pipelineEditorialChecks setting, then off.+ overrideStagePins: z.boolean().optional(),}).strict();export const seriesAutopilotSettingsSchema = z.object({diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex 1b50cea8c0..d569fc0f45 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -193,6 +193,10 @@ const autopilotStartSchema = z.object({// sampled eligible provider/model/effort for each step and role. Explicit// run choices and exact stage pins still win.autoSelectModels: z.boolean().optional(),+ // Force this run's provider/model/effort onto EVERY stage, ignoring the+ // per-stage pins from the Prompts page (see lib/stagePinPolicy.js). Falls back+ // to the persisted pipelineEditorialChecks.overrideStagePins setting, then off.+ overrideStagePins: z.boolean().optional(),});const modelOutcomeSchema = z.object({diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex f440ada707..fb78c9b51b 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -197,6 +197,7 @@ const sanitizeAutopilotResumeOptions = (raw) => {const stageLlm = sanitizeAutopilotStageLlm(raw.stageLlm);if (stageLlm) out.stageLlm = stageLlm;if (typeof raw.autoSelectModels === 'boolean') out.autoSelectModels = raw.autoSelectModels;+ if (typeof raw.overrideStagePins === 'boolean') out.overrideStagePins = raw.overrideStagePins;return Object.keys(out).length ? out : null;};// Why a bounded-retry gate paused the run. Convergence gates (#1571):diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 88f40533db..3f02fc38c0 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -224,6 +224,7 @@ const autopilot = await import('./seriesAutopilot.js');const arcPlanner = await import('./arcPlanner.js');const { commitSeasonsWithRemap: realCommitSeasonsWithRemap } = await import('./arcPlanner/arcCore.js');const { stageContentOf } = await import('./textStages.js');+const { stagePinsIgnored } = await import('../../lib/stagePinPolicy.js');const { resolveNextStep, requiredScriptStages, scriptStructurallyReady, visualReady, wantsComic } = autopilot;// A comic script string that parseComicScript turns into >=1 page/panel.@@ -965,6 +966,19 @@ describe('resolveAutopilotAutoSelectModels (config gate)', () => {});});+// Persistable (unlike unlockForRun): it re-routes spend but mutates nothing,+// and the scheduler resolves unattended runs from this same settings slice.+describe('resolveAutopilotOverrideStagePins (config gate)', () => {+ it('defaults off, supports a saved default, and lets a run override it', () => {+ expect(autopilot.resolveAutopilotOverrideStagePins({}, null)).toBe(false);+ expect(autopilot.resolveAutopilotOverrideStagePins({}, { pipelineEditorialChecks: { overrideStagePins: true } })).toBe(true);+ expect(autopilot.resolveAutopilotOverrideStagePins(+ { overrideStagePins: false },+ { pipelineEditorialChecks: { overrideStagePins: true } },+ )).toBe(false);+ });+});+describe('resolveNextStep — unlock pre-pass ordering', () => {// A locked arc makes generateArc/resolveVerifyIssues throw and a locked stage// makes text generation skip, so the unlock MUST precede every generation step@@ -1782,6 +1796,39 @@ describe('autopilot conductor', () => {expect(run.startPayload).toMatchObject({ type: 'start', provider: 'codex', model: 'gpt-x' });});+ // `overrideStagePins` reaches stageRunner through an async-context flag rather+ // than an option key, precisely so it survives every delegated hop. Assert it+ // from INSIDE a delegated service — a wrapper that only covered the direct+ // staged calls would pass a check on run.options and still miss the child+ // runners this feature exists to reach.+ it('propagates overrideStagePins into delegated services as an async-context flag', async () => {+ const { seriesId } = await seedComplete();+ let seenInsideDelegate = null;+ arcSpies.verifyArc.mockImplementationOnce(async () => {+ seenInsideDelegate = stagePinsIgnored();+ return { issues: verifyFindings };+ });+ await autopilot.startSeriesAutopilot(seriesId, { providerOverride: 'claude', overrideStagePins: true });+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.options.overrideStagePins).toBe(true);+ expect(seenInsideDelegate).toBe(true);+ // The flag is scoped to the run's own async subtree — it must not linger.+ expect(stagePinsIgnored()).toBe(false);+ });++ it('leaves stage pins in force for an ordinary run', async () => {+ const { seriesId } = await seedComplete();+ let seenInsideDelegate = null;+ arcSpies.verifyArc.mockImplementationOnce(async () => {+ seenInsideDelegate = stagePinsIgnored();+ return { issues: verifyFindings };+ });+ await autopilot.startSeriesAutopilot(seriesId, {});+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.options.overrideStagePins).toBe(false);+ expect(seenInsideDelegate).toBe(false);+ });+it('lets a per-run provider override beat the series-configured provider', async () => {const { seriesId } = await seedComplete();await seriesSvc.updateSeries(seriesId, { llm: { provider: 'codex', model: 'gpt-x' } });@@ -2476,7 +2523,7 @@ describe('autopilot conductor', () => {const series = await seriesSvc.getSeries(seriesId);expect(series.autopilot?.status).toBe('paused');expect(series.autopilot?.resumeOptions).toEqual({- includeVisual: false, fileGaps: true, autoSelectModels: false,+ includeVisual: false, fileGaps: true, autoSelectModels: false, overrideStagePins: false,});});diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.jsindex 7b36a79515..973f70c00d 100644--- a/server/services/pipeline/seriesAutopilot/config.js+++ b/server/services/pipeline/seriesAutopilot/config.js@@ -303,6 +303,21 @@ export function resolveAutopilotAutoSelectModels(options = {}, settings = null)return pickBool(options?.autoSelectModels, pec?.autoSelectModels, DEFAULT_AUTO_SELECT_MODELS);}+// Force this run's route onto EVERY stage — the mechanism, and which stage+// fields it strips, live in lib/stagePinPolicy.js + stageRunner#effectiveStage.+// It changes only WHICH pins are consulted: the per-role and per-stage routes+// the run already resolved (roleLlm) still decide the value.+//+// Defaults OFF and persistable (like autoSelectModels, unlike unlockForRun):+// it re-routes spend but mutates nothing, and "always run everything on my one+// provider" is exactly the preference an unattended scheduled run wants to+// inherit. Per-run option wins, then the persisted setting, then off.+export const DEFAULT_OVERRIDE_STAGE_PINS = false;+export function resolveAutopilotOverrideStagePins(options = {}, settings = null) {+ const pec = settings?.pipelineEditorialChecks || {};+ return pickBool(options?.overrideStagePins, pec?.overrideStagePins, DEFAULT_OVERRIDE_STAGE_PINS);+}+// Which provider/model do this run's LLM calls use? An explicit per-run// `providerOverride`/`modelOverride` wins (the Options picker, or the scheduler// mapping a schedule's provider/model); otherwise the run inherits the series'@@ -314,7 +329,8 @@ export function resolveAutopilotAutoSelectModels(options = {}, settings = null)//// Threaded as SOFT defaults (`providerDefault`/`modelDefault`, see// session.js#providerOverrideOpts), so a deliberate per-stage pin on the Prompts-// page still wins and an unavailable provider falls through instead of throwing.+// page still wins and an unavailable provider falls through instead of throwing+// — unless the run opted into `overrideStagePins` above.export function resolveAutopilotLlm(options = {}, series = null) {const { provider, model } = resolveSeriesLlmOverride(series, {overrideProvider: options?.providerOverride,diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex a5d8b393f6..e2b2ae6856 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -5,6 +5,7 @@*/import { randomUUID } from 'crypto';+import { withStagePinsIgnored } from '../../../lib/stagePinPolicy.js';import { getDomainMode } from '../../../lib/domainAutonomy.js';import { isRunCanceledError } from '../../../lib/aiToolkit/errorDetection.js';import { mergeSeverityWeights, resolveBlockingSet } from '../../../lib/editorial/index.js';@@ -20,7 +21,7 @@ import {resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,resolveAutopilotProduceTeaser, resolveAutopilotRevision, resolveAutopilotLlm,resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove, resolveAutopilotObserver,- resolveAutopilotAutoSelectModels,+ resolveAutopilotAutoSelectModels, resolveAutopilotOverrideStagePins,} from './config.js';import { getModelPerformanceReport } from './modelPerformance.js';import { runSelfImproveDiagnosis } from './selfImprove.js';@@ -129,6 +130,10 @@ export async function startSeriesAutopilot(sId, options = {}) {// signal tap retains frames from the first one.observer: resolveAutopilotObserver(options, settings),autoSelectModels,+ // Force the run's route onto stages that carry their own Prompts-page pin+ // (see config.js). Resolved here with the other gates so the coordinator+ // wrap below, the start frame and a resume all read the same effective flag.+ overrideStagePins: resolveAutopilotOverrideStagePins(options, settings),modelRecommendations: modelPerformance.recommendations || {},modelRoutesExplicit: {creative: creativeRouteExplicit,@@ -239,7 +244,8 @@ export async function startSeriesAutopilot(sId, options = {}) {// Shared `start` frame for both modes. `provider`/`model`/`effort` are the// run's resolved soft defaults — what the panel shows as "this run calls X / Y";- // a stage pinned on the Prompts page still overrides them for that stage.+ // a stage pinned on the Prompts page still overrides them for that stage+ // unless `overrideStagePins` is on, which the frame carries alongside them.const startFrame = (target, extra = {}) => {const judge = runOptions.judgeLlm ? roleLlm(record, 'judge') : null;return {@@ -253,6 +259,7 @@ export async function startSeriesAutopilot(sId, options = {}) {effort: judge.effortOverride ?? null,} : null,autoSelectModels: runOptions.autoSelectModels,+ overrideStagePins: runOptions.overrideStagePins,...extra,};};@@ -315,8 +322,13 @@ export async function startSeriesAutopilot(sId, options = {}) {// `ordinal` (completed-step count) lives outside the try so the catch's// cancellation terminal can report how far the run got, exactly as the// cooperative between-steps cancel does.+ //+ // `withStagePinsIgnored` wraps the WHOLE coordinator so the flag reaches every+ // leaf LLM call this run makes — the direct staged calls, the delegated child+ // runners, the editorial checks, the judges — without threading an option key+ // through a dozen intermediate services. Off (the default) it is a plain call.let ordinal = 0;- (async () => {+ withStagePinsIgnored(runOptions.overrideStagePins, async () => {try {// DRY-RUN: enumerate the plan, no side effects.if (mode === 'dry-run') {@@ -541,7 +553,7 @@ export async function startSeriesAutopilot(sId, options = {}) {record.finished = true;scheduleCleanup(sId, record);}- })();+ });return { runId, alreadyRunning: false, mode };}diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsindex 221982e619..6c76e4483b 100644--- a/server/services/pipeline/seriesAutopilot/session.js+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -137,6 +137,7 @@ export async function persistMarker(seriesId, patch) {...(run.options.judgeLlm ? { judgeLlm: run.options.judgeLlm } : {}),...(run.options.stageLlm ? { stageLlm: run.options.stageLlm } : {}),autoSelectModels: run.options.autoSelectModels === true,+ overrideStagePins: run.options.overrideStagePins === true,}: null;await updateSeries(seriesId, {@@ -228,6 +229,11 @@ export async function notifyPause(record, sId, { reason, pauseKind = null, curre// dimension: `effortDefault` applies only to stages with no `stage.effort` pin,// and the runner clamps it to (or drops it for) whatever provider actually runs.//+// The run's `overrideStagePins` option does NOT change the channels below — the+// values here still come from the per-role/per-stage routes. It only stops+// stageRunner from consulting the stage-config pins that would otherwise+// outrank them (lib/stagePinPolicy.js).+//// Two shapes because the delegated services disagree on field names: the// arc/episode/verify passes take `providerDefault`/`modelDefault`; the child// runners (volumeBeatsRunner, autoRunner) and the `providerId`-style servicesdiff --git a/server/services/seriesAutopilotScheduler.js b/server/services/seriesAutopilotScheduler.jsindex 5f9597ee7c..6de437102c 100644--- a/server/services/seriesAutopilotScheduler.js+++ b/server/services/seriesAutopilotScheduler.js@@ -82,6 +82,10 @@ export function runOptionsFor(entry) {if (entry.provider) opts.providerOverride = entry.provider;if (entry.model) opts.modelOverride = entry.model;if (entry.effort) opts.effortOverride = entry.effort;+ // Only forwarded when the schedule explicitly ticked it — an absent flag must+ // stay absent so the autopilot's persisted-setting fallback still applies+ // (forwarding `false` would pin it off for every scheduled run).+ if (entry.overrideStagePins === true) opts.overrideStagePins = true;return opts;}diff --git a/server/services/seriesAutopilotScheduler.test.js b/server/services/seriesAutopilotScheduler.test.jsindex 702a311f94..9f52ac53ea 100644--- a/server/services/seriesAutopilotScheduler.test.js+++ b/server/services/seriesAutopilotScheduler.test.js@@ -153,6 +153,24 @@ describe('scheduled handler', () => {});});+ it('forwards overrideStagePins only when the schedule ticked it', async () => {+ const on = { seriesId: 's1', enabled: true, cron: '0 3 * * *', provider: 'codex', overrideStagePins: true };+ const handler = await registerAndGetHandler(on);+ getSettings.mockResolvedValue(withSchedules([on]));+ await handler();+ expect(startSeriesAutopilot).toHaveBeenCalledWith('s1', {+ providerOverride: 'codex', overrideStagePins: true,+ });++ // Absent (or explicitly false) must stay OUT of the options so the run still+ // falls through to the persisted pipelineEditorialChecks default.+ startSeriesAutopilot.mockClear();+ const off = { seriesId: 's1', enabled: true, cron: '0 3 * * *', provider: 'codex', overrideStagePins: false };+ getSettings.mockResolvedValue(withSchedules([off]));+ await handler();+ expect(startSeriesAutopilot).toHaveBeenCalledWith('s1', { providerOverride: 'codex' });+ });+it('skips when the schedule was disabled since registration', async () => {const handler = await registerAndGetHandler({ seriesId: 's1', enabled: true, cron: '0 3 * * *' });getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));