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

feat: learn autopilot model performance

[._.]/ Adam Eivy78758bc83d32
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c387de14e2..b3a59e2986 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changed
+- **Series Autopilot can learn which models actually work at each step.** AI run history now distinguishes technical completion from a later editorial keep/revert decision and aggregates evidence by orchestration step, creative-versus-judge role, provider, model, and reasoning effort. The new opt-in selector requires multiple quality-reviewed samples, ignores disabled providers and removed models, and remains a soft default beneath explicit run choices and exact prompt-stage pins. The Options panel reports how much attributed and quality-reviewed evidence exists, while local APIs expose the full metrics and allow an operator to correct or backfill a historical outcome. Foundation judges record contract-valid responses separately from true editorial approval, and foundation repairs automatically record accepted versus rolled-back outcomes, so a model that finishes a long run but makes the story worse is not learned as a success.
+
- **Completed CoS agents no longer strand a worktree because of their own completion marker.** The `.agent-done` sentinel is consumed before worktree cleanup, but Git still reported the untracked file as ordinary authored work and the safety gate preserved the otherwise-clean checkout with a high-priority warning. Cleanup now ignores only that runtime marker: sentinel-only trees are removed normally, while any real source change still preserves the worktree and is named in the warning.
- **A failed CoS task now diagnoses itself and comes back on its own.** A failing task used to pile up a queue of approval-gated tasks — the crash filed one, the provider failure filed another, repeated orphaning filed a third — and then, even after the cause was fixed, the original task sat `blocked` until someone un-blocked it by hand (or the 14-day reaper quietly retired it as stale). Both halves of that are now automatic. Every failure-driven investigation is filed through one producer, so they share a single approval policy, a single storm counter, and a single dedup fingerprint: unattended by default, held for you in exactly the two cases where another unattended agent would just repeat itself — the same cause was already investigated in the last 24 hours, or failures are cascading rather than isolated — and the task says which of the two it is. Completing an investigation, whether an agent finished it or you fixed the cause and ticked it off, then automatically retries every task that failure was blocking. Bounded at two automatic retries per task, after which the task stays blocked and says the retry loop gave up rather than still showing the original failure. A task you terminated or paused, one parked awaiting your arbitration, and one waiting on a repository path you have to fix are never revived behind your back.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 9196011fce..9623b9971e 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -11,6 +11,7 @@ import {
startPipelineAutopilot,
cancelPipelineAutopilot,
getPipelineAutopilotStatus,
+ getPipelineAutopilotModelMetrics,
pipelineAutopilotSseUrl,
getPipelineSeriesCanonReadiness,
getPipelineSeries,
@@ -60,6 +61,9 @@ const DEFAULT_SELF_IMPROVE = false;
// fix tasks (worktree + PR + review loop + merge, no human gate) as pipeline
// defects surface. Supersedes the selfImprove terminal diagnosis when both on.
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;
// Threshold input: a [0,10] number (0.5 steps allowed — NOT integer-rounded like
// the round clamps), blank/invalid → the default.
const clampFoundationThreshold = (n, fallback) => {
@@ -191,6 +195,11 @@ const OPTION_SPECS = {
read: readBoolean,
persistOnEdit: true,
},
+ autoSelectModels: {
+ defaultValue: DEFAULT_AUTO_SELECT_MODELS,
+ read: readBoolean,
+ persistOnEdit: true,
+ },
};
// A single numeric field for the Options popover (round bounds + the pause
@@ -494,6 +503,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const [judgeEffortOverride, setJudgeEffortOverride] = useState('');
const [providers, setProviders] = useState([]);
const [activeProviderId, setActiveProviderId] = useState(null);
+ const [modelMetrics, setModelMetrics] = useState(null);
// Provider/model/effort the ACTIVE run reported on its start frame — what the
// live progress line names, so a run started elsewhere (or by the scheduler)
// still says which provider (and how hard it thinks) it is spending on.
@@ -535,6 +545,14 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
return () => { canceled = true; };
}, []);
+ useEffect(() => {
+ let canceled = false;
+ getPipelineAutopilotModelMetrics(seriesId, { silent: true })
+ .then((data) => { if (!canceled) setModelMetrics(data); })
+ .catch(() => null);
+ return () => { canceled = true; };
+ }, [seriesId]);
+
// Disarm the unlock consent whenever the panel switches series. This
// component is reused across `seriesId` changes rather than remounted, so
// without this a box ticked for series A would still be armed — invisibly,
@@ -904,6 +922,15 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
</div>
) : null}
</div>
+ <label className="flex items-center gap-2 text-xs text-gray-300">
+ <input type="checkbox" checked={opt.autoSelectModels} onChange={(e) => options.edit('autoSelectModels', e.target.checked)} />
+ Let autopilot choose models from stage-specific results
+ </label>
+ {opt.autoSelectModels ? (
+ <p className="text-[11px] text-gray-500">
+ Uses separate technical and quality outcomes by step, role, provider, model and effort. A route needs at least {modelMetrics?.minimumQualitySamples ?? 2} quality-reviewed samples; explicit choices above and exact Prompts-stage pins still win. Current history: {modelMetrics?.evidenceRuns ?? 0} attributed run{modelMetrics?.evidenceRuns === 1 ? '' : 's'}, {modelMetrics?.metrics?.reduce((sum, metric) => sum + (metric.qualityEvaluated || 0), 0) ?? 0} quality-reviewed.
+ </p>
+ ) : null}
<label className="flex items-center gap-2 text-xs text-gray-300">
<input type="checkbox" checked={includeVisual} onChange={(e) => setIncludeVisual(e.target.checked)} />
Draft cover + all interior pages (comic targets)
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index ee886a350c..de48f9584e 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -6,6 +6,7 @@ vi.mock('../../services/api', () => ({
startPipelineAutopilot: vi.fn(),
cancelPipelineAutopilot: vi.fn(),
getPipelineAutopilotStatus: vi.fn(),
+ getPipelineAutopilotModelMetrics: vi.fn(),
pipelineAutopilotSseUrl: (id) => `/api/pipeline/series/${id}/autopilot/progress`,
getPipelineSeriesCanonReadiness: vi.fn(),
getPipelineSeries: vi.fn(),
@@ -30,6 +31,7 @@ vi.mock('../../hooks/usePipelineProgress', () => ({
import {
startPipelineAutopilot,
getPipelineAutopilotStatus,
+ getPipelineAutopilotModelMetrics,
getPipelineSeriesCanonReadiness,
getPipelineSeries,
listPipelineIssues,
@@ -52,6 +54,7 @@ beforeEach(() => {
sseLatest = null;
sseFrames = [];
getPipelineAutopilotStatus.mockResolvedValue({ autopilot: null, active: false });
+ getPipelineAutopilotModelMetrics.mockResolvedValue({ evidenceRuns: 0, minimumQualitySamples: 2, metrics: [], recommendations: {} });
getPipelineSeries.mockResolvedValue(null);
listPipelineIssues.mockResolvedValue([]);
startPipelineAutopilot.mockResolvedValue({ runId: 'r1', mode: 'execute', alreadyRunning: false });
@@ -91,6 +94,29 @@ describe('AutopilotPanel', () => {
));
});
+ it('persists and sends evidence-based model selection only after opt-in', async () => {
+ getPipelineAutopilotModelMetrics.mockResolvedValue({
+ evidenceRuns: 6,
+ minimumQualitySamples: 2,
+ metrics: [{ qualityEvaluated: 4 }],
+ recommendations: {},
+ });
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ fireEvent.click(screen.getByRole('button', { name: /options/i }));
+ const toggle = screen.getByLabelText(/choose models from stage-specific results/i);
+ expect(toggle).not.toBeChecked();
+ fireEvent.click(toggle);
+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith(
+ 'pipelineEditorialChecks', { autoSelectModels: true }, { silent: true },
+ ));
+ expect(await screen.findByText(/6 attributed runs, 4 quality-reviewed/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(
+ 's1', { includeVisual: true, fileGaps: false, autoSelectModels: true }, { silent: true },
+ ));
+ });
+
it('sends only edited rounds as overrides AND persists them; untouched gates omitted', async () => {
getSettings.mockResolvedValue({ pipelineEditorialChecks: { maxArcVerifyRounds: 6, maxEditorialRounds: 4 } });
renderPanel({ id: 's1', targetFormat: 'comic' });
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 4fdcbf4139..37e5b1c112 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -989,6 +989,16 @@ export const cancelPipelineAutopilot = (seriesId) =>
export const getPipelineAutopilotStatus = (seriesId, options = {}) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/autopilot/status`, options);
+export const getPipelineAutopilotModelMetrics = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/autopilot/model-metrics`, options);
+
+export const recordPipelineAutopilotModelOutcome = (seriesId, outcome, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/autopilot/model-outcomes`, {
+ method: 'POST',
+ body: JSON.stringify(outcome),
+ ...options,
+ });
+
export const pipelineAutopilotSseUrl = (seriesId) =>
`/api/pipeline/series/${encodeURIComponent(seriesId)}/autopilot/progress`;
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index c9e65636a3..32cb4fd9c9 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -289,7 +289,8 @@ export function createRunnerService(config = {}) {
workspaceName = 'default',
timeout,
source = 'devtools',
- fallbackProviderId = null
+ fallbackProviderId = null,
+ effort = null,
} = options;
if (!providerService) {
@@ -368,6 +369,7 @@ export function createRunnerService(config = {}) {
originalProviderId: usedFallback ? providerId : null,
usedFallback,
model: recordModel,
+ effort,
workspacePath,
workspaceName,
source,
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index abfc48f0a8..67ddf64c96 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -286,6 +286,10 @@ export const pipelineEditorialChecksSettingsSchema = z.object({
// the pipeline improving itself. Optional + additive so older peers fall
// through to off.
observer: z.boolean().optional(),
+ // Evidence-based Series Autopilot routing. Metrics are collected regardless;
+ // 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(),
}).strict();
// Cursor-context payload for the CD-bridge suggest route — identical shape to
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 322d3437f3..ace3b2a4d6 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -1140,6 +1140,7 @@ async function executeProviderRunOnce({
prompt,
source,
workspacePath: effectiveCwd,
+ effort,
});
runId = runResult.runId;
if (runResult.provider && runResult.provider.id !== provider.id) {
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index bcad29fd09..171ff0466e 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -487,6 +487,7 @@ export async function runStageScopedInlineLLM(stageName, prompt, options = {}) {
async function executeStagePrompt({ stage, label, prompt, options }) {
const provider = await resolveProviderForStage(stage, options);
const resolvedModel = resolveModel(provider, resolveModelHint(stage, options));
+ const effectiveEffort = resolveEffortHint(stage, options);
// resolveEffectiveModel gates the override per provider type and, for
// CLI providers with a baked --model/-m flag in args, extracts the
// args-pinned model id so the run record + log line reflect what
@@ -522,6 +523,7 @@ async function executeStagePrompt({ stage, label, prompt, options }) {
model: effectiveModel,
prompt,
source: options.source || 'staged-llm',
+ effort: effectiveEffort,
// createRun.timeout is returned but not persisted into metadata.json
// by the toolkit (only providerId/model/source/etc. are written at
// creation time). We always patch below to record the effective
@@ -544,7 +546,7 @@ async function executeStagePrompt({ stage, label, prompt, options }) {
// also patch provider id/name/model so /runs attribution matches the
// provider that actually ran. Best-effort: attribution, not load-bearing.
const recordedTimeout = effectiveTimeout ?? effectiveProvider.timeout ?? DEFAULT_TIMEOUT_MS;
- const metadataPatch = { timeout: recordedTimeout };
+ const metadataPatch = { timeout: recordedTimeout, effort: effectiveEffort };
if (fellBack) {
metadataPatch.model = effectiveModel;
metadataPatch.providerId = effectiveProvider.id;
@@ -574,7 +576,7 @@ async function executeStagePrompt({ stage, label, prompt, options }) {
// Reasoning effort (#3641). Always passed: the runner clamps it to the
// provider's ladder and omits the flag entirely for a provider with no
// effort control, so no capability check is needed here.
- effort: resolveEffortHint(stage, options),
+ effort: effectiveEffort,
onRunCreated: options.onRunCreated,
onRunSettled: options.onRunSettled,
});
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index fdfd1b9a83..cb7af596cd 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -25,6 +25,10 @@ import { validateRequest, MAX_CONVERGENCE_ROUNDS } from '../../lib/validation.js
import { EFFORT_LEVELS } from '../../lib/providerModels.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import * as autopilot from '../../services/pipeline/seriesAutopilot.js';
+import {
+ getModelPerformanceReport,
+ recordModelOutcome,
+} from '../../services/pipeline/seriesAutopilot/modelPerformance.js';
import { READINESS_GATES } from '../../services/pipeline/editorialScore.js';
import { mapServiceError, providerOverrideShape } from './shared.js';
@@ -170,8 +174,24 @@ const autopilotStartSchema = z.object({
// Supersedes the selfImprove terminal diagnosis when both are on. Falls back
// to the persisted pipelineEditorialChecks.observer setting, then off.
observer: z.boolean().optional(),
+ // Learn from technical + editorial outcomes and use the best sufficiently
+ // sampled eligible provider/model/effort for each step and role. Explicit
+ // run choices and exact stage pins still win.
+ autoSelectModels: z.boolean().optional(),
});
+const modelOutcomeSchema = z.object({
+ runId: z.string().uuid(),
+ role: z.enum(['creative', 'judge']),
+ stage: z.string().trim().min(1).max(80),
+ outcome: z.enum(['accepted', 'rejected', 'valid', 'invalid']),
+ target: z.string().trim().max(120).optional(),
+ scoreBefore: z.number().finite().optional(),
+ scoreAfter: z.number().finite().optional(),
+ weightedBefore: z.number().finite().optional(),
+ weightedAfter: z.number().finite().optional(),
+}).strict();
+
router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {
// 404 before we kick off if the series doesn't exist.
await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
@@ -214,4 +234,21 @@ router.get('/series/:id/autopilot/status', asyncHandler(async (req, res) => {
});
}));
+router.get('/series/:id/autopilot/model-metrics', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await getModelPerformanceReport());
+}));
+
+// Operator correction/backfill tool: a technically successful run can still be
+// rejected by a later quality gate. Recording that distinction is the core of
+// the selector's evidence, and this endpoint lets an operator annotate historic
+// runs or correct a misclassified outcome without editing run files by hand.
+router.post('/series/:id/autopilot/model-outcomes', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(modelOutcomeSchema, req.body ?? {});
+ const recorded = await recordModelOutcome(body.runId, body);
+ if (!recorded) throw new ServerError('AI run not found', { status: 404, code: 'RUN_NOT_FOUND' });
+ res.json({ success: true, runId: body.runId });
+}));
+
export default router;
diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.js
index ae69914efa..2149a94e4d 100644
--- a/server/services/pipeline/reverseOutline.js
+++ b/server/services/pipeline/reverseOutline.js
@@ -233,7 +233,10 @@ async function buildManuscriptCorpus(seriesId) {
* - force — re-segment even when the manuscript hash is unchanged
* - signal — AbortSignal checked before the persist
*/
-export async function generateReverseOutline(seriesId, { providerId, providerIdDefault, model, modelIdDefault, effortIdDefault, force = false, signal } = {}) {
+export async function generateReverseOutline(seriesId, {
+ providerId, providerIdDefault, model, modelIdDefault, effortIdDefault,
+ force = false, signal, onRunCreated, onRunSettled,
+} = {}) {
assertValidSeriesId(seriesId);
const { corpus, byNumber } = await buildManuscriptCorpus(seriesId);
if (!corpus.trim()) return { seriesId, status: 'no-content' };
@@ -276,6 +279,8 @@ export async function generateReverseOutline(seriesId, { providerId, providerIdD
modelDefault: modelIdDefault,
effortDefault: effortIdDefault,
source: 'pipeline-reverse-outline',
+ onRunCreated,
+ onRunSettled,
});
if (signal?.aborted) return { seriesId, status: 'canceled' };
diff --git a/server/services/pipeline/scriptVerify.js b/server/services/pipeline/scriptVerify.js
index e8d670f89b..ec2e909b48 100644
--- a/server/services/pipeline/scriptVerify.js
+++ b/server/services/pipeline/scriptVerify.js
@@ -201,7 +201,9 @@ function mergeVerifyIssues(first, second) {
// the only caller; #1514 renamed the provider field from `providerId` to match
// the soft-default channel, and #1558 did the same for the model — `modelIdDefault`
// replaces the old hard `model` so a pinned stage's own model is no longer beaten.)
-export async function verifyComicScript(issueId, { providerIdDefault, modelIdDefault, effortIdDefault } = {}) {
+export async function verifyComicScript(issueId, {
+ providerIdDefault, modelIdDefault, effortIdDefault, onRunCreated, onRunSettled,
+} = {}) {
const issue = await getIssue(issueId);
const script = (issue.stages?.comicScript?.output || '').trim();
if (!script) return { issues: [], skipped: 'no-comic-script' };
@@ -236,6 +238,8 @@ export async function verifyComicScript(issueId, { providerIdDefault, modelIdDef
modelDefault: modelIdDefault,
effortDefault: effortIdDefault,
source: 'pipeline-script-verify',
+ onRunCreated,
+ onRunSettled,
});
return {
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 5a226b39ae..032a145eaa 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -160,6 +160,7 @@ const sanitizeAutopilotResumeOptions = (raw) => {
if (baseLlm?.effortOverride) out.effortOverride = baseLlm.effortOverride;
const judgeLlm = sanitizeAutopilotLlmRoute(raw.judgeLlm);
if (judgeLlm) out.judgeLlm = judgeLlm;
+ if (typeof raw.autoSelectModels === 'boolean') out.autoSelectModels = raw.autoSelectModels;
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.js b/server/services/pipeline/seriesAutopilot.js
index 09b3ade96a..682011e621 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -80,6 +80,7 @@ export * from './seriesAutopilot/session.js';
export * from './seriesAutopilot/diagnosisCore.js';
export * from './seriesAutopilot/selfImprove.js';
export * from './seriesAutopilot/observer.js';
+export * from './seriesAutopilot/modelPerformance.js';
export * from './seriesAutopilot/childRuns.js';
export * from './seriesAutopilot/editorialSteps.js';
export * from './seriesAutopilot/visualSteps.js';
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 312910efc9..5428b158e0 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -318,6 +318,31 @@ describe('provider/model threading helpers (#1514 provider + #1558 model — bot
providerOverride: 'claude-code-tui', modelOverride: undefined, effortOverride: 'high',
});
});
+
+ it('uses learned stage/role routing only when that role has no explicit run choice', () => {
+ const learned = {
+ currentStep: 'foundationGate',
+ options: {
+ autoSelectModels: true,
+ providerOverride: 'series-default',
+ modelOverride: 'series-model',
+ modelRoutesExplicit: { creative: false, judge: true },
+ modelRecommendations: {
+ foundationGate: {
+ creative: { providerOverride: 'ollama', modelOverride: 'local-14b' },
+ judge: { providerOverride: 'codex', modelOverride: 'judge-model' },
+ },
+ },
+ judgeLlm: { providerOverride: 'manual-judge', modelOverride: 'manual-model' },
+ },
+ };
+ expect(autopilot.__testing.roleLlm(learned, 'creative')).toEqual({
+ providerOverride: 'ollama', modelOverride: 'local-14b', effortOverride: undefined,
+ });
+ expect(autopilot.__testing.roleLlm(learned, 'judge')).toEqual({
+ providerOverride: 'manual-judge', modelOverride: 'manual-model', effortOverride: undefined,
+ });
+ });
});
// The precedence itself is covered by server/lib/seriesLlmOverride.test.js —
@@ -866,6 +891,17 @@ describe('resolveAutopilotUnlockForRun (config gate)', () => {
});
});
+describe('resolveAutopilotAutoSelectModels (config gate)', () => {
+ it('defaults off, supports a saved default, and lets a run override it', () => {
+ expect(autopilot.resolveAutopilotAutoSelectModels({}, null)).toBe(false);
+ expect(autopilot.resolveAutopilotAutoSelectModels({}, { pipelineEditorialChecks: { autoSelectModels: true } })).toBe(true);
+ expect(autopilot.resolveAutopilotAutoSelectModels(
+ { autoSelectModels: false },
+ { pipelineEditorialChecks: { autoSelectModels: 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
@@ -2087,7 +2123,9 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const series = await seriesSvc.getSeries(seriesId);
expect(series.autopilot?.status).toBe('paused');
- expect(series.autopilot?.resumeOptions).toEqual({ includeVisual: false, fileGaps: true });
+ expect(series.autopilot?.resumeOptions).toEqual({
+ includeVisual: false, fileGaps: true, autoSelectModels: false,
+ });
});
it('does not notify on a clean complete (#1615)', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index c1cb23b094..ab9c352bd5 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -28,6 +28,7 @@ import {
regressionPauseReason, sameFinding, isBlockingSetRegression, isIsolatedFixSafe,
} from './convergence.js';
import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';
+import { recordModelOutcome } from './modelPerformance.js';
import { requiredScriptStages, textReady } from './stepResolver.js';
const MAX_PLANNING_GATE_HANDOFFS = 6;
@@ -580,18 +581,29 @@ export async function runFoundationGate(seriesId, record) {
// nothing) returns the cached score with no LLM call — this IS the fast-pass
// that stops an already-clean foundation looping. A real change (any fix, or
// a user edit) flips the pinned hash and re-judges automatically.
+ let judgeRunId = null;
+ const judgeHooks = providerOverrideOpts(record, 'judge');
const snap = await judgeFoundation(seriesId, {
providerDefault: judgeLlm.providerOverride,
modelDefault: judgeLlm.modelOverride,
effortDefault: judgeLlm.effortOverride,
- onRunCreated: providerOverrideOpts(record, 'judge').onRunCreated,
- onRunSettled: providerOverrideOpts(record, 'judge').onRunSettled,
+ onRunCreated: (runId) => {
+ judgeRunId = runId;
+ judgeHooks.onRunCreated(runId);
+ },
+ onRunSettled: judgeHooks.onRunSettled,
});
// A cached (content-hash unchanged) verdict did no LLM work — don't bill it.
if (!snap.cached) await recordDomainUsage('cos', { actions: 1 });
const score = snap.weightedScore ?? 0;
const gate = foundationGateStatus(snap.dimensions, score, threshold);
const weak = foundationFixTarget(snap.dimensions, threshold);
+ if (!snap.cached && judgeRunId) {
+ await recordModelOutcome(judgeRunId, {
+ role: 'judge', stage: 'foundationGate', outcome: 'valid',
+ target: weak?.dimension || 'foundation', scoreAfter: score,
+ }).catch(() => {});
+ }
broadcast(seriesId, {
type: 'foundation:round', round, weightedScore: score, threshold,
dimensionFloor: gate.dimensionFloor, failingDimensions: gate.failingDimensions,
@@ -615,6 +627,11 @@ export async function runFoundationGate(seriesId, record) {
// if it makes another latent dimension judgeable.
const earned = targetImproved || (targetTied && gapChanged && score >= beforeWeighted);
if (!earned) {
+ await Promise.all((pendingRepair.runIds || []).map((runId) => recordModelOutcome(runId, {
+ role: 'creative', stage: 'foundationGate', outcome: 'rejected', target: dimension,
+ scoreBefore: beforeTargetScore, scoreAfter: afterTargetScore,
+ weightedBefore: beforeWeighted, weightedAfter: score,
+ }).catch(() => {})));
const rollback = await restoreFoundationState(seriesId, pendingRepair.snapshot);
const reason = rollback.restored
? `Foundation ${dimension} repair did not improve its target (${beforeTargetScore} → ${afterTargetScore}; weighted ${beforeWeighted} → ${score}), so its edits were reverted to the pre-repair checkpoint.`
@@ -633,6 +650,11 @@ export async function runFoundationGate(seriesId, record) {
discarded: discardedSet(residualFindings(snap.dimensions)),
};
}
+ await Promise.all((pendingRepair.runIds || []).map((runId) => recordModelOutcome(runId, {
+ role: 'creative', stage: 'foundationGate', outcome: 'accepted', target: dimension,
+ scoreBefore: beforeTargetScore, scoreAfter: afterTargetScore,
+ weightedBefore: beforeWeighted, weightedAfter: score,
+ }).catch(() => {})));
pendingRepair = null;
}
if (gate.passes) {
@@ -710,6 +732,8 @@ export async function runFoundationGate(seriesId, record) {
// this throws, so there is no retry left to attempt here.
const repairSnapshot = await snapshotFoundationState(seriesId);
let fix;
+ const repairRunIds = [];
+ const creativeHooks = providerOverrideOpts(record);
try {
fix = await applyFoundationFix(seriesId, weak.dimension, {
finding: snap.dimensions?.[weak.dimension] || {},
@@ -720,8 +744,11 @@ export async function runFoundationGate(seriesId, record) {
judgeEffortDefault: judgeLlm.effortOverride,
...seasonPreserveOpts(record),
effortOverride: creativeLlm.effortOverride,
- onRunCreated: providerOverrideOpts(record).onRunCreated,
- onRunSettled: providerOverrideOpts(record).onRunSettled,
+ onRunCreated: (runId) => {
+ repairRunIds.push(runId);
+ creativeHooks.onRunCreated(runId);
+ },
+ onRunSettled: creativeHooks.onRunSettled,
});
} catch (err) {
const detail = (err?.message || String(err)).slice(0, 300);
@@ -747,6 +774,9 @@ export async function runFoundationGate(seriesId, record) {
// review rather than burning the remaining rounds re-judging an unchanged
// foundation.
if (fix?.applied !== true) {
+ await Promise.all(repairRunIds.map((runId) => recordModelOutcome(runId, {
+ role: 'creative', stage: 'foundationGate', outcome: 'invalid', target: weak.dimension,
+ }).catch(() => {})));
return {
pause: true,
pauseKind: 'inapplicable',
@@ -762,6 +792,7 @@ export async function runFoundationGate(seriesId, record) {
dimension: weak.dimension,
judge: snap,
snapshot: repairSnapshot,
+ runIds: repairRunIds,
};
changed = true;
}
diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.js
index 7983414850..7b36a79515 100644
--- a/server/services/pipeline/seriesAutopilot/config.js
+++ b/server/services/pipeline/seriesAutopilot/config.js
@@ -293,6 +293,16 @@ export function resolveAutopilotObserver(options = {}, settings = null) {
return pickBool(options?.observer, pec?.observer, DEFAULT_OBSERVER);
}
+// Evidence-based provider/model/effort routing. Off by default until the user
+// opts in: run history is still collected while off, but an existing series or
+// stage choice must not silently change merely because enough samples accrued.
+// When enabled, explicit per-run choices and exact stage pins remain stronger.
+export const DEFAULT_AUTO_SELECT_MODELS = false;
+export function resolveAutopilotAutoSelectModels(options = {}, settings = null) {
+ const pec = settings?.pipelineEditorialChecks || {};
+ return pickBool(options?.autoSelectModels, pec?.autoSelectModels, DEFAULT_AUTO_SELECT_MODELS);
+}
+
// 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'
diff --git a/server/services/pipeline/seriesAutopilot/modelPerformance.js b/server/services/pipeline/seriesAutopilot/modelPerformance.js
new file mode 100644
index 0000000000..721eaf359c
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/modelPerformance.js
@@ -0,0 +1,186 @@
+/**
+ * Series Autopilot model-performance learning.
+ *
+ * AI run records already own technical execution telemetry. This module adds
+ * the missing editorial outcome (accepted / rejected / valid assessment), then
+ * aggregates those same records by pipeline step, role, provider, model and
+ * effort. No parallel datastore: deleting a run also deletes its evidence.
+ */
+
+import { getAllProviders } from '../../providers.js';
+import { getRun, listRuns, patchRunMetadata } from '../../runner.js';
+
+const MAX_RUNS = 5_000;
+export const MIN_QUALITY_SAMPLES = 2;
+const POSITIVE_OUTCOMES = new Set(['accepted']);
+const NEGATIVE_OUTCOMES = new Set(['rejected']);
+
+const finiteOrNull = (value) => {
+ if (value === null || value === undefined || value === '') return null;
+ return Number.isFinite(Number(value)) ? Number(value) : null;
+};
+
+const modelId = (model) => {
+ if (typeof model === 'string') return model;
+ if (model && typeof model === 'object') return model.id || model.name || null;
+ return null;
+};
+
+const providerSupportsModel = (provider, model) => {
+ if (!model) return true;
+ const models = Array.isArray(provider?.models) ? provider.models.map(modelId).filter(Boolean) : [];
+ return models.length === 0 || models.includes(model);
+};
+
+const identityKey = ({ pipelineStage, pipelineRole, providerId, model, effort }) =>
+ [pipelineStage, pipelineRole, providerId, model || '', effort || ''].join('\u0000');
+
+export function summarizeModelPerformance(runs = [], providers = []) {
+ const enabled = new Map(
+ (Array.isArray(providers) ? providers : [])
+ .filter((provider) => provider?.enabled !== false)
+ .map((provider) => [provider.id, provider]),
+ );
+ const groups = new Map();
+
+ for (const run of Array.isArray(runs) ? runs : []) {
+ if (run?.autopilotSystem !== 'series' || !run.pipelineStage || !run.pipelineRole || !run.providerId) continue;
+ if (typeof run.success !== 'boolean') continue;
+ const identity = {
+ pipelineStage: run.pipelineStage,
+ pipelineRole: run.pipelineRole,
+ providerId: run.providerId,
+ providerName: run.providerName || run.providerId,
+ model: run.model || null,
+ effort: run.effort || null,
+ };
+ const key = identityKey(identity);
+ const metric = groups.get(key) || {
+ ...identity,
+ attempts: 0,
+ technicalSuccesses: 0,
+ technicalFailures: 0,
+ qualityAccepted: 0,
+ qualityRejected: 0,
+ qualityEvaluated: 0,
+ contractValid: 0,
+ contractInvalid: 0,
+ scoreDeltaTotal: 0,
+ scoreDeltaSamples: 0,
+ durationTotalMs: 0,
+ durationSamples: 0,
+ lastRunAt: null,
+ };
+ metric.attempts += 1;
+ if (run.success === true) metric.technicalSuccesses += 1;
+ else if (run.success === false) metric.technicalFailures += 1;
+ if (run.success === true && POSITIVE_OUTCOMES.has(run.qualityOutcome)) {
+ metric.qualityAccepted += 1;
+ metric.qualityEvaluated += 1;
+ } else if (run.success === true && NEGATIVE_OUTCOMES.has(run.qualityOutcome)) {
+ metric.qualityRejected += 1;
+ metric.qualityEvaluated += 1;
+ }
+ if (run.success === true && run.qualityOutcome === 'valid') metric.contractValid += 1;
+ else if (run.success === true && run.qualityOutcome === 'invalid') metric.contractInvalid += 1;
+ const delta = finiteOrNull(run.qualityScoreDelta);
+ if (delta !== null) {
+ metric.scoreDeltaTotal += delta;
+ metric.scoreDeltaSamples += 1;
+ }
+ const duration = finiteOrNull(run.duration);
+ if (duration !== null && duration >= 0) {
+ metric.durationTotalMs += duration;
+ metric.durationSamples += 1;
+ }
+ if (!metric.lastRunAt || String(run.startTime || '') > metric.lastRunAt) metric.lastRunAt = run.startTime || null;
+ groups.set(key, metric);
+ }
+
+ const metrics = [...groups.values()].map((metric) => {
+ const technicalRate = (metric.technicalSuccesses + 2) / (metric.attempts + 3);
+ const qualityRate = metric.qualityEvaluated > 0
+ ? (metric.qualityAccepted + 1) / (metric.qualityEvaluated + 2)
+ : null;
+ const meanScoreDelta = metric.scoreDeltaSamples > 0
+ ? metric.scoreDeltaTotal / metric.scoreDeltaSamples
+ : null;
+ const meanDurationMs = metric.durationSamples > 0
+ ? metric.durationTotalMs / metric.durationSamples
+ : null;
+ const rankScore = qualityRate === null
+ ? technicalRate * 0.5
+ : qualityRate * 0.75 + technicalRate * 0.25;
+ const provider = enabled.get(metric.providerId);
+ const eligible = !!provider && providerSupportsModel(provider, metric.model);
+ const {
+ scoreDeltaTotal, scoreDeltaSamples, durationTotalMs, durationSamples, ...publicMetric
+ } = metric;
+ return {
+ ...publicMetric,
+ technicalRate,
+ qualityRate,
+ meanScoreDelta,
+ meanDurationMs,
+ rankScore,
+ eligible,
+ };
+ }).sort((a, b) => (
+ b.rankScore - a.rankScore
+ || b.qualityEvaluated - a.qualityEvaluated
+ || b.attempts - a.attempts
+ || (a.meanDurationMs ?? Infinity) - (b.meanDurationMs ?? Infinity)
+ ));
+
+ const recommendations = {};
+ for (const metric of metrics) {
+ if (!metric.eligible || metric.qualityEvaluated < MIN_QUALITY_SAMPLES) continue;
+ recommendations[metric.pipelineStage] ||= {};
+ if (recommendations[metric.pipelineStage][metric.pipelineRole]) continue;
+ recommendations[metric.pipelineStage][metric.pipelineRole] = {
+ providerOverride: metric.providerId,
+ modelOverride: metric.model || undefined,
+ effortOverride: metric.effort || undefined,
+ samples: metric.qualityEvaluated,
+ accepted: metric.qualityAccepted,
+ rejected: metric.qualityRejected,
+ rankScore: metric.rankScore,
+ };
+ }
+
+ return { metrics, recommendations };
+}
+
+export async function getModelPerformanceReport() {
+ const [{ runs }, providerResult] = await Promise.all([
+ listRuns(MAX_RUNS, 0, 'all'),
+ getAllProviders(),
+ ]);
+ const providers = Array.isArray(providerResult?.providers) ? providerResult.providers : [];
+ const report = summarizeModelPerformance(runs, providers);
+ return {
+ ...report,
+ evidenceRuns: report.metrics.reduce((sum, metric) => sum + metric.attempts, 0),
+ minimumQualitySamples: MIN_QUALITY_SAMPLES,
+ };
+}
+
+export async function recordModelOutcome(runId, patch = {}) {
+ if (!runId || !await getRun(runId)) return false;
+ const scoreBefore = finiteOrNull(patch.scoreBefore);
+ const scoreAfter = finiteOrNull(patch.scoreAfter);
+ await patchRunMetadata(runId, {
+ autopilotSystem: 'series',
+ ...(patch.role ? { pipelineRole: patch.role } : {}),
+ ...(patch.stage ? { pipelineStage: patch.stage } : {}),
+ ...(patch.outcome ? { qualityOutcome: patch.outcome } : {}),
+ ...(patch.target ? { qualityTarget: patch.target } : {}),
+ ...(scoreBefore !== null ? { qualityScoreBefore: scoreBefore } : {}),
+ ...(scoreAfter !== null ? { qualityScoreAfter: scoreAfter } : {}),
+ ...(scoreBefore !== null && scoreAfter !== null ? { qualityScoreDelta: scoreAfter - scoreBefore } : {}),
+ ...(patch.weightedBefore !== undefined ? { qualityWeightedBefore: finiteOrNull(patch.weightedBefore) } : {}),
+ ...(patch.weightedAfter !== undefined ? { qualityWeightedAfter: finiteOrNull(patch.weightedAfter) } : {}),
+ qualityEvaluatedAt: new Date().toISOString(),
+ });
+ return true;
+}
diff --git a/server/services/pipeline/seriesAutopilot/modelPerformance.test.js b/server/services/pipeline/seriesAutopilot/modelPerformance.test.js
new file mode 100644
index 0000000000..d28d32f198
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/modelPerformance.test.js
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+import { MIN_QUALITY_SAMPLES, summarizeModelPerformance } from './modelPerformance.js';
+
+const provider = (id, models, enabled = true) => ({ id, name: id, models, enabled });
+const run = (over = {}) => ({
+ autopilotSystem: 'series',
+ pipelineStage: 'foundationGate',
+ pipelineRole: 'creative',
+ providerId: 'cloud',
+ providerName: 'Cloud',
+ model: 'large',
+ effort: 'high',
+ success: true,
+ duration: 1_000,
+ startTime: '2026-01-01T00:00:00.000Z',
+ ...over,
+});
+
+describe('Series Autopilot model performance', () => {
+ it('keeps technical completion separate from quality rejection', () => {
+ const { metrics } = summarizeModelPerformance([
+ run({ qualityOutcome: 'rejected', qualityScoreDelta: -0.2 }),
+ run({ success: false, errorCategory: 'timeout' }),
+ ], [provider('cloud', ['large'])]);
+ expect(metrics[0]).toMatchObject({
+ attempts: 2,
+ technicalSuccesses: 1,
+ technicalFailures: 1,
+ qualityAccepted: 0,
+ qualityRejected: 1,
+ qualityEvaluated: 1,
+ meanScoreDelta: -0.2,
+ });
+ });
+
+ it('does not mistake a parse-valid judge response for editorial approval', () => {
+ const { metrics, recommendations } = summarizeModelPerformance([
+ run({ pipelineRole: 'judge', qualityOutcome: 'valid' }),
+ run({ pipelineRole: 'judge', qualityOutcome: 'valid' }),
+ ], [provider('cloud', ['large'])]);
+ expect(metrics[0]).toMatchObject({ contractValid: 2, qualityEvaluated: 0 });
+ expect(recommendations).toEqual({});
+ });
+
+ it('requires multiple reviewed samples before recommending a route', () => {
+ expect(MIN_QUALITY_SAMPLES).toBe(2);
+ const one = summarizeModelPerformance([
+ run({ qualityOutcome: 'accepted' }),
+ ], [provider('cloud', ['large'])]);
+ expect(one.recommendations).toEqual({});
+
+ const enough = summarizeModelPerformance([
+ run({ qualityOutcome: 'accepted' }),
+ run({ qualityOutcome: 'accepted', startTime: '2026-01-02T00:00:00.000Z' }),
+ ], [provider('cloud', ['large'])]);
+ expect(enough.recommendations.foundationGate.creative).toMatchObject({
+ providerOverride: 'cloud', modelOverride: 'large', effortOverride: 'high', samples: 2,
+ });
+ });
+
+ it('ranks accepted local evidence above repeatedly rejected cloud work', () => {
+ const runs = [
+ run({ qualityOutcome: 'rejected' }),
+ run({ qualityOutcome: 'rejected' }),
+ run({ providerId: 'ollama', providerName: 'Ollama', model: 'local-14b', effort: null, qualityOutcome: 'accepted' }),
+ run({ providerId: 'ollama', providerName: 'Ollama', model: 'local-14b', effort: null, qualityOutcome: 'accepted' }),
+ ];
+ const { recommendations } = summarizeModelPerformance(runs, [
+ provider('cloud', ['large']),
+ provider('ollama', ['local-14b']),
+ ]);
+ expect(recommendations.foundationGate.creative).toMatchObject({
+ providerOverride: 'ollama', modelOverride: 'local-14b', accepted: 2, rejected: 0,
+ });
+ });
+
+ it('never recommends a disabled provider or a removed model', () => {
+ const runs = [run({ qualityOutcome: 'accepted' }), run({ qualityOutcome: 'accepted' })];
+ expect(summarizeModelPerformance(runs, [provider('cloud', ['large'], false)]).recommendations).toEqual({});
+ expect(summarizeModelPerformance(runs, [provider('cloud', ['other'])]).recommendations).toEqual({});
+ });
+});
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index bddcaa6f8b..d2008418a9 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -19,7 +19,9 @@ import {
resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,
resolveAutopilotProduceTeaser, resolveAutopilotRevision, resolveAutopilotLlm,
resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove, resolveAutopilotObserver,
+ resolveAutopilotAutoSelectModels,
} from './config.js';
+import { getModelPerformanceReport } from './modelPerformance.js';
import { runSelfImproveDiagnosis } from './selfImprove.js';
import { observerEnabled, runObserverPass, summarizeObserver } from './observer.js';
import { VISUAL_DRAFT_ENABLED, summarizePlanCost } from './convergence.js';
@@ -63,6 +65,21 @@ export async function startSeriesAutopilot(sId, options = {}) {
// a resume re-reads them fresh. Loading the series here is cheap; a missing
// series (deleted mid-run) falls through to the frozen defaults.
const seriesRecord = await getSeries(sId).catch(() => null);
+ const autoSelectModels = resolveAutopilotAutoSelectModels(options, settings);
+ const modelPerformance = autoSelectModels
+ ? await getModelPerformanceReport().catch((err) => {
+ console.log(`⚠️ autopilot: model-performance read failed: ${err.message}`);
+ return { recommendations: {} };
+ })
+ : { recommendations: {} };
+ const creativeRouteExplicit = !!(
+ options?.providerOverride || options?.modelOverride || options?.effortOverride
+ );
+ const judgeRouteExplicit = !!(
+ options?.judgeLlm?.providerOverride
+ || options?.judgeLlm?.modelOverride
+ || options?.judgeLlm?.effortOverride
+ );
const runOptions = {
...options,
...resolveAutopilotRounds(options, settings),
@@ -84,6 +101,12 @@ export async function startSeriesAutopilot(sId, options = {}) {
// human gate) as pipeline defects surface. Same early resolution so the
// signal tap retains frames from the first one.
observer: resolveAutopilotObserver(options, settings),
+ autoSelectModels,
+ modelRecommendations: modelPerformance.recommendations || {},
+ modelRoutesExplicit: {
+ creative: creativeRouteExplicit,
+ judge: judgeRouteExplicit,
+ },
// Run provider/model: per-run override → the series' own `series.llm` →
// unset (stage pin / active provider downstream). Resolved ONCE here so the
// manual run, a scheduled run and the UI's "this run calls X / Y" copy all
@@ -180,6 +203,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
},
activeChild: null,
activeLlmRunId: null,
+ currentStep: null,
};
runs.set(sId, record);
@@ -198,6 +222,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
model: judge.modelOverride ?? null,
effort: judge.effortOverride ?? null,
} : null,
+ autoSelectModels: runOptions.autoSelectModels,
...extra,
};
};
@@ -369,6 +394,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
}
ordinal += 1;
+ record.currentStep = step.kind;
await persistMarker(sId, { status: 'running', runId, currentStep: step.kind });
broadcast(sId, { type: 'step:start', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal, reason: step.reason });
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index b8a5d7dfb9..83d8bf8b20 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -11,7 +11,7 @@ import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS
import { getSeries, updateSeries } from '../series.js';
import * as volumeBeatsRunner from '../volumeBeatsRunner.js';
import * as autoRunner from '../autoRunner.js';
-import { stopRun } from '../../runner.js';
+import { patchRunMetadata, stopRun } from '../../runner.js';
import { runs, autopilotEvents, noteSignal } from './state.js';
// ---------------------------------------------------------------------------
@@ -114,6 +114,7 @@ export async function persistMarker(seriesId, patch) {
...(run.options.modelOverride ? { modelOverride: run.options.modelOverride } : {}),
...(run.options.effortOverride ? { effortOverride: run.options.effortOverride } : {}),
...(run.options.judgeLlm ? { judgeLlm: run.options.judgeLlm } : {}),
+ autoSelectModels: run.options.autoSelectModels === true,
}
: null;
await updateSeries(seriesId, {
@@ -214,6 +215,17 @@ export async function notifyPause(record, sId, { reason, pauseKind = null, curre
// params untouched for manual route callers.
export const roleLlm = (record, role = 'creative') => {
const base = record?.options || {};
+ const learned = base.autoSelectModels === true
+ && base.modelRoutesExplicit?.[role] !== true
+ ? base.modelRecommendations?.[record?.currentStep]?.[role]
+ : null;
+ if (learned) {
+ return {
+ providerOverride: learned.providerOverride,
+ modelOverride: learned.modelOverride,
+ effortOverride: learned.effortOverride,
+ };
+ }
const route = role === 'judge' && base.judgeLlm && typeof base.judgeLlm === 'object'
? base.judgeLlm
: null;
@@ -238,21 +250,31 @@ export const roleLlm = (record, role = 'creative') => {
};
};
+const runLifecycle = (record, role) => ({
+ onRunCreated: (runId) => {
+ record.activeLlmRunId = runId;
+ patchRunMetadata(runId, {
+ autopilotSystem: 'series',
+ autopilotRunId: record.runId || null,
+ pipelineStage: record.currentStep || 'unknown',
+ pipelineRole: role,
+ }).catch(() => {});
+ // Close the race where Stop lands after createRun but before provider
+ // execution registers its child process.
+ if (record.cancelRequested) stopRun(runId).catch(() => {});
+ },
+ onRunSettled: (runId) => {
+ if (record.activeLlmRunId === runId) record.activeLlmRunId = null;
+ },
+});
+
export const providerOverrideOpts = (record, role = 'creative') => {
const llm = roleLlm(record, role);
return {
providerDefault: llm.providerOverride,
modelDefault: llm.modelOverride,
effortDefault: llm.effortOverride,
- onRunCreated: (runId) => {
- record.activeLlmRunId = runId;
- // Close the race where Stop lands after createRun but before provider
- // execution registers its child process.
- if (record.cancelRequested) stopRun(runId).catch(() => {});
- },
- onRunSettled: (runId) => {
- if (record.activeLlmRunId === runId) record.activeLlmRunId = null;
- },
+ ...runLifecycle(record, role),
};
};
export const providerIdOpts = (record, role = 'creative') => {
@@ -261,6 +283,7 @@ export const providerIdOpts = (record, role = 'creative') => {
providerIdDefault: llm.providerOverride,
modelIdDefault: llm.modelOverride,
effortIdDefault: llm.effortOverride,
+ ...runLifecycle(record, role),
// Multi-candidate draft gate (#2169): bill one cos action per re-roll and stop
// re-rolling when the daily budget is spent. Only ever invoked by
// generateStage's runDraftGate on a judgeable stage with draftAttempts > 1 — a
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 21d5ffd90b..737a621167 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -680,6 +680,8 @@ async function runStageLLMOnce(issueId, stageId, template, ctx, options) {
// per-stage `effort` pin, and the runner clamps/drops it per provider.
effortDefault: options.effortIdDefault,
source: 'pipeline-text-stage',
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
});
} catch (err) {
await updateStage(issueId, stageId, {
diff --git a/server/services/pipeline/volumeBeatsRunner.js b/server/services/pipeline/volumeBeatsRunner.js
index f91feb02c1..ba4e53fd92 100644
--- a/server/services/pipeline/volumeBeatsRunner.js
+++ b/server/services/pipeline/volumeBeatsRunner.js
@@ -135,6 +135,8 @@ export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
// Soft run-level reasoning effort (Series Autopilot, #3641) — same soft
// channel, so a per-stage `effort` pin still wins.
effortIdDefault: options.effortIdDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
});
generated += 1;
broadcast({