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([issue-8149]): run tasks on the model or tier they name, never an inferred one

[._.]/ Adam Eivy09e13ed5a829
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index cbf37e3a1c..b6faab9881 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -851,7 +851,7 @@ export default function LearningTab() {
Misroutes Detected
</h4>
<p className="text-xs text-gray-400 mb-3">
- These task type + model tier combinations have &lt;40% success with 3+ attempts. The system will auto-adjust routing.
+ These task type + model tier combinations have &lt;40% success with 3+ attempts. Routing never changes on its own — pin a model or tier on the task or schedule to act on this.
</p>
<div className="space-y-1">
{routing.misroutes.map((m, idx) => (
@@ -922,8 +922,15 @@ export default function LearningTab() {
entry.tiers.map((tier, tIdx) => (
<tr key={`${entry.taskType}-${tier.tier}`} className="border-t border-port-border">
{tIdx === 0 ? (
- <td className="p-3 text-gray-300 truncate max-w-[200px]" rowSpan={entry.tiers.length}>
- {entry.taskType}
+ <td className="p-3 text-gray-300 max-w-[200px] align-top" rowSpan={entry.tiers.length}>
+ <div className="truncate">{entry.taskType}</div>
+ {entry.suggestion && (
+ <div className="text-xs text-gray-500 mt-1" title={entry.suggestion.reason || undefined}>
+ {entry.suggestion.tier && <>Suggests <span className="text-port-accent">{entry.suggestion.tier}</span></>}
+ {entry.suggestion.tier && entry.suggestion.avoidTiers.length > 0 && ' · '}
+ {entry.suggestion.avoidTiers.length > 0 && <>avoid <span className="text-orange-400">{entry.suggestion.avoidTiers.join(', ')}</span></>}
+ </div>
+ )}
</td>
) : null}
<td className="p-3 text-orange-400">{tier.tier}</td>
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index a1a0078a1f..d4f2ca31ad 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -54,6 +54,14 @@ const argList = (text) => (text ? text.split(' ').filter(Boolean) : []);
const rangeMessage = (label, { min, max }, unit = '') =>
`${label} must be between ${formatCount(min)} and ${formatCount(max)}${unit ? ` ${unit}` : ''}`;
+// The four optional capability-tier overrides, in picker order (#8149).
+const TIER_FIELDS = [
+ { key: 'lightModel', label: 'Light (fast)', dot: 'bg-port-success', placeholder: 'haiku' },
+ { key: 'mediumModel', label: 'Medium (balanced)', dot: 'bg-port-warning', placeholder: 'sonnet' },
+ { key: 'heavyModel', label: 'Heavy (powerful)', dot: 'bg-port-error', placeholder: 'opus' },
+ { key: 'ultraModel', label: 'Ultra (frontier)', dot: 'bg-port-error', placeholder: 'Fable or Astra model ID' },
+];
+
export default function ProviderForm({ provider, daemonReadiness = null, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {}, hardwareCompatibilityByBackend: {} }, runnerAllowedCommands = null }) {
const [formData, setFormData] = useState({
name: provider?.name || '',
@@ -234,11 +242,14 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
// providers, whose ladder is keyed on `ollamaBacked`. Merge the live edits
// over the stored record instead, so edits to command/endpoint/envVars count
// immediately while the markers survive.
- // Shared option list for the Default Model + Light/Medium/Heavy tier selects,
- // so the sentinel option can't be added to some and missed on others.
- const modelSelectOptions = (
+ // Shared option list for the Default Model + tier selects, so the sentinel
+ // option can't be added to some and missed on others. Only the empty row's
+ // meaning differs: no Default Model is "None", while an empty tier INHERITS
+ // the Default Model (resolveProviderModelTier) — so a preset only sets the
+ // tiers it wants on a different model (#8149).
+ const modelSelectOptions = (emptyLabel = 'None') => (
<>
- <option value="">None</option>
+ <option value="">{emptyLabel}</option>
{configuredDefault && (
<option value={configuredDefault}>Use the CLI&apos;s configured default</option>
)}
@@ -1044,7 +1055,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
onChange={(e) => setFormData(prev => ({ ...prev, defaultModel: e.target.value }))}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
>
- {modelSelectOptions}
+ {modelSelectOptions()}
</select>
) : (
<input
@@ -1075,100 +1086,36 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
{/* Model Tiers */}
<div className="border-t border-port-border pt-4 mt-4">
- <h4 className="text-sm font-medium text-gray-300 mb-3">Model Tiers</h4>
+ <h4 className="text-sm font-medium text-gray-300 mb-3">Model Tier Overrides</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <FormField labelClassName="block text-xs text-gray-400 mb-1" label={<>
- <span className="inline-block w-2 h-2 rounded-full bg-port-success mr-1"></span>
- Light (fast)
- </>}>
- {availableModels.length > 0 ? (
- <select
- value={formData.lightModel}
- onChange={(e) => setFormData(prev => ({ ...prev, lightModel: e.target.value }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- >
- {modelSelectOptions}
- </select>
- ) : (
- <input
- type="text"
- value={formData.lightModel}
- onChange={(e) => setFormData(prev => ({ ...prev, lightModel: e.target.value }))}
- placeholder="haiku"
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- />
- )}
- </FormField>
- <FormField labelClassName="block text-xs text-gray-400 mb-1" label={<>
- <span className="inline-block w-2 h-2 rounded-full bg-port-warning mr-1"></span>
- Medium (balanced)
- </>}>
- {availableModels.length > 0 ? (
- <select
- value={formData.mediumModel}
- onChange={(e) => setFormData(prev => ({ ...prev, mediumModel: e.target.value }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- >
- {modelSelectOptions}
- </select>
- ) : (
- <input
- type="text"
- value={formData.mediumModel}
- onChange={(e) => setFormData(prev => ({ ...prev, mediumModel: e.target.value }))}
- placeholder="sonnet"
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- />
- )}
- </FormField>
- <FormField labelClassName="block text-xs text-gray-400 mb-1" label={<>
- <span className="inline-block w-2 h-2 rounded-full bg-port-error mr-1"></span>
- Heavy (powerful)
- </>}>
- {availableModels.length > 0 ? (
- <select
- value={formData.heavyModel}
- onChange={(e) => setFormData(prev => ({ ...prev, heavyModel: e.target.value }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- >
- {modelSelectOptions}
- </select>
- ) : (
- <input
- type="text"
- value={formData.heavyModel}
- onChange={(e) => setFormData(prev => ({ ...prev, heavyModel: e.target.value }))}
- placeholder="opus"
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- />
- )}
- </FormField>
- <FormField labelClassName="block text-xs text-gray-400 mb-1" label={<>
- <span className="inline-block w-2 h-2 rounded-full bg-port-error mr-1"></span>
- Ultra (frontier)
- </>}>
- {availableModels.length > 0 ? (
- <select
- value={formData.ultraModel}
- onChange={(e) => setFormData(prev => ({ ...prev, ultraModel: e.target.value }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- >
- {modelSelectOptions}
- </select>
- ) : (
- <input
- type="text"
- value={formData.ultraModel}
- onChange={(e) => setFormData(prev => ({ ...prev, ultraModel: e.target.value }))}
- placeholder="Fable or Astra model ID"
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
- />
- )}
- </FormField>
+ {TIER_FIELDS.map(({ key, label, dot, placeholder }) => (
+ <FormField key={key} labelClassName="block text-xs text-gray-400 mb-1" label={<>
+ <span className={`inline-block w-2 h-2 rounded-full ${dot} mr-1`}></span>
+ {label}
+ </>}>
+ {availableModels.length > 0 ? (
+ <select
+ value={formData[key]}
+ onChange={(e) => setFormData(prev => ({ ...prev, [key]: e.target.value }))}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
+ >
+ {modelSelectOptions(key === 'ultraModel' ? 'Inherit Heavy' : 'Inherit Default Model')}
+ </select>
+ ) : (
+ <input
+ type="text"
+ value={formData[key]}
+ onChange={(e) => setFormData(prev => ({ ...prev, [key]: e.target.value }))}
+ placeholder={placeholder}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
+ />
+ )}
+ </FormField>
+ ))}
</div>
<p className="text-xs text-gray-500 mt-2">
{availableModels.length > 0
- ? 'Capability mappings for tasks and prompt stages. Ultra is explicit opt-in and falls back to Heavy when unset.'
+ ? 'Optional. A task, role, or prompt stage that names a tier runs on its model here; a blank tier uses the Default Model (Ultra uses Heavy first). Nothing picks a tier automatically.'
: 'Save provider, then use Test or Refresh to fetch available models'}
</p>
</div>
diff --git a/client/src/components/writers-room/StagePromptModelPicker.jsx b/client/src/components/writers-room/StagePromptModelPicker.jsx
index a716761663..91639e81e1 100644
--- a/client/src/components/writers-room/StagePromptModelPicker.jsx
+++ b/client/src/components/writers-room/StagePromptModelPicker.jsx
@@ -13,6 +13,7 @@ import {
} from '../../utils/formatters';
import { getPrompt, savePrompt } from '../../services/apiPrompts';
import { getProviders } from '../../services/apiProviders';
+import { STAGE_MODEL_TIER_OPTIONS, canonicalStageModelTier } from '../../lib/stageModelTiers';
/**
* Inline picker for a prompt stage's provider+model. Mirrors the Tier/Specific
@@ -138,15 +139,13 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
{!isSpecific ? (
<select
aria-label="Model"
- value={stage.model || 'default'}
+ value={canonicalStageModelTier(stage.model) || 'default'}
onChange={(e) => persist({ provider: null, model: e.target.value })}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"
>
- <option value="default">Default — use the active provider's default model</option>
- <option value="quick">Quick — provider's light/fast model</option>
- <option value="coding">Coding — provider's medium model</option>
- <option value="heavy">Heavy — provider's heavy model</option>
- <option value="ultra">Ultra — provider's frontier model</option>
+ {STAGE_MODEL_TIER_OPTIONS.map(({ value, label, hint }) => (
+ <option key={value} value={value}>{label} — {hint}</option>
+ ))}
</select>
) : (
<ProviderModelSelector
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e45c81c85b..1b36954e36 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -231,6 +231,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `estimationTolerance.js` | `estimationToleranceText(tolerancePct)` → the one line an estimation drill shows to say how precise to be, e.g. "Within 10% counts — 2 significant figures is close enough". Converts the grading band into significant figures (scale-free: rounding to `n` of them is worst-case `0.5 x 10^(1-n)` off, so the smallest `n` that fits the band IS the precision required), because a percentage of an answer you have not worked out yet is not actionable mid-drill. Reads the band through `resolveEstimationTolerancePct` (`server/lib/postScoring.js`), the same resolver both graders use, so the copy can never claim a band the ✓/✗ did not apply. Rendered by `components/meatspace/post/EstimationPrecision.jsx`. Pure, DOM-free. |
| `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |
| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly, systemStageKeys })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)` is the searchable string. The system-stage list is NOT mirrored here — `GET /api/prompts` ships it as `systemStages` from `server/lib/promptSystemStages.js` and the page threads it in as `systemStageKeys` (#3314). Pure — no React, no I/O. |
+| `stageModelTiers.js` | Re-export of `server/lib/stageModelTiers.js` — the prompt-stage tier vocabulary (`STAGE_MODEL_TIER_OPTIONS` rows for every stage model select, `canonicalStageModelTier` so a legacy stored `quick`/`coding` still selects Light/Medium, `isStageModelTier`). |
| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. |
| `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |
| `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order — it does NOT render a `manifest` group: each runtime atlas's sidecar manifest is folded onto its atlas row as `row.manifest`, and other behind-the-scenes JSON is omitted. `runtimeVersionDir(path)` / `isRuntimeVersionPath(path)` / `isRuntimeSidecarManifest(path)` expose the `runtime/vN` grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like `AssetInspector` reuse one definition instead of re-regexing. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index e0d9d0c7e7..270d12bc86 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -185,6 +185,7 @@ export * from './postRotation.js';
export * from './seriesReviewProgress.js';
export * from './powersBreakdown.js';
export * from './promptStageGroups.js';
+export * from './stageModelTiers.js';
export * from './referenceAnalysis.js';
export * from './roundDraft.js';
export * from './scoreNotation.js';
diff --git a/client/src/lib/stageModelTiers.js b/client/src/lib/stageModelTiers.js
new file mode 100644
index 0000000000..8ab2ba6bb2
--- /dev/null
+++ b/client/src/lib/stageModelTiers.js
@@ -0,0 +1,7 @@
+export {
+ STAGE_MODEL_TIERS,
+ STAGE_MODEL_TIER_OPTIONS,
+ LEGACY_STAGE_MODEL_TIERS,
+ canonicalStageModelTier,
+ isStageModelTier,
+} from '../../../server/lib/stageModelTiers.js';
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 7bfe431322..f05f2791e4 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -27,6 +27,7 @@ import {
import { getProviders } from '../services/apiProviders';
import Pill from '../components/ui/Pill';
import { buildStageGroups, stageGroupKeyFor } from '../lib/promptStageGroups';
+import { STAGE_MODEL_TIER_OPTIONS, canonicalStageModelTier } from '../lib/stageModelTiers';
const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];
@@ -898,15 +899,13 @@ export default function PromptManager() {
{!stageConfig.provider ? (
<select
aria-label="Model tier"
- value={stageConfig.model || 'default'}
+ value={canonicalStageModelTier(stageConfig.model) || 'default'}
onChange={(e) => setStageConfig({ ...stageConfig, model: e.target.value })}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
>
- <option value="default">Default</option>
- <option value="quick">Quick</option>
- <option value="coding">Coding</option>
- <option value="heavy">Heavy</option>
- <option value="ultra">Ultra</option>
+ {STAGE_MODEL_TIER_OPTIONS.map(({ value, label }) => (
+ <option key={value} value={value}>{label}</option>
+ ))}
</select>
) : (
<ProviderModelSelector
@@ -1350,15 +1349,13 @@ export default function PromptManager() {
{!newStageForm.provider ? (
<select
aria-label="Model tier"
- value={newStageForm.model}
+ value={canonicalStageModelTier(newStageForm.model) || 'default'}
onChange={(e) => setNewStageForm({ ...newStageForm, model: e.target.value })}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
>
- <option value="default">Default</option>
- <option value="quick">Quick</option>
- <option value="coding">Coding</option>
- <option value="heavy">Heavy</option>
- <option value="ultra">Ultra</option>
+ {STAGE_MODEL_TIER_OPTIONS.map(({ value, label }) => (
+ <option key={value} value={value}>{label}</option>
+ ))}
</select>
) : (
<ProviderModelSelector
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index cc504e7236..400f1249c9 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -66,14 +66,14 @@
"writers-room-continue": {
"name": "Writers Room — Live Continuation",
"description": "Live Creative Director feedback: from the prose around the cursor, propose 2–4 short optional continuation beats, prose snippets, or dialogue lines the writer can accept. Drives the opt-in live-mode side panel in the editor.",
- "model": "quick",
+ "model": "light",
"returnsJson": true,
"variables": []
},
"writers-room-cd-bridge": {
"name": "Writers Room — Creative Director Bridge",
"description": "From the prose around the cursor, propose a short Creative Director treatment — a logline, synopsis, overall visual treatment (styleSpec), and 2–6 filmable scenes (intent + visual prompt + duration). The writer reviews it and sends it into a new Creative Director project. Drives the opt-in live-mode side panel in the editor.",
- "model": "quick",
+ "model": "light",
"returnsJson": true,
"variables": []
},
diff --git a/docs/MODEL_TIERS.md b/docs/MODEL_TIERS.md
index 399ac3a5b5..54af1c8946 100644
--- a/docs/MODEL_TIERS.md
+++ b/docs/MODEL_TIERS.md
@@ -9,10 +9,15 @@ preset's editor, and a tier name resolves on whichever preset a task names. Astr
and Fable are examples of Ultra choices; use a model supported by the selected
preset's service and plan.
-CoS selects Light/Heavy from task heuristics and can learn tier preferences from
-outcomes. Explicit thinking levels have their own routing precedence. Prompt
-stages resolve Quick to Light, Coding to Medium, and Heavy to Heavy; they also
-accept the canonical Light, Medium, and Ultra names. Prompt Manager exposes Ultra.
+A tier is an explicit request, never an automatic one. CoS runs a task on the tier
+or model the task, role, or stage names, and otherwise on the preset's Default
+Model — it does not pick a tier from the task description, priority, context size,
+or learning history. The CoS Learning view still reports per-tier success rates
+per task type as advice: act on it by pinning a tier on the task or schedule.
+Prompt stages use the same four names (Light, Medium, Heavy, Ultra) or Default;
+the legacy stage spellings Quick and Coding still resolve to Light and Medium.
+An unset tier on a preset inherits its Default Model, so a preset only needs the
+tiers it wants to map to a different model.
Dispatch labels communicate capability to planning/claim agents; they are guidance,
not permission to enable providers or spend on a new service.
@@ -24,8 +29,8 @@ remain appropriate for model-specific evaluations or compatibility requirements.
The tier resolves on the selected provider, including provider fallback.
Model capability and reasoning effort are independent: Ultra does not imply
-maximum effort. Existing task heuristics, thinking levels, learning escalation,
-provider defaults, and scheduled jobs do not automatically upgrade to Ultra.
+maximum effort. Provider defaults and scheduled jobs never upgrade to Ultra on
+their own.
An unset Ultra mapping falls back to Heavy, then the provider default. Existing
installs receive an optional Ultra field; migration offers Fable additively on standard Claude catalogs, selects Astra/Fable
when advertised by the provider, and preserves all explicit Ultra pins.
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 022a6261bf..5a8a420acb 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -62,15 +62,12 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai
## Model Selection Rules
-The `selectModelForTask` function routes tasks to appropriate model tiers:
+`selectModelForTask` runs a task on exactly what it was configured with:
-| Tier | Trigger | Example Tasks |
-|------|---------|---------------|
-| **heavy** | Critical priority, visual analysis, complex reasoning | Architect, refactor, security audit, long context |
-| **medium** | Standard development tasks, default | Most coding tasks, bug fixes, feature implementation |
-| **light** | Documentation-only tasks | Update README, write docs, format text |
+1. **An explicit model or tier** — the task's `metadata.model` (or an orchestration role's `model`). A tier (`light`/`medium`/`heavy`/`ultra`) resolves on the provider that actually runs the task, including a fallback provider.
+2. **Otherwise the provider's Default Model.**
-**Important**: Light model (haiku) is NEVER used for coding tasks. Tasks containing keywords like `fix`, `bug`, `implement`, `test`, `feature`, `api`, `component`, etc. are automatically routed to medium tier or higher.
+Nothing picks a tier automatically — not the description, priority, context size, or learning history (#8149). The Learning tab reports each task type's per-tier success rate and any tier its history suggests; pin that tier on the task or schedule to act on it. See [MODEL_TIERS.md](../MODEL_TIERS.md).
## Configuration
diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.md
index eff7959ced..172c0d9ec2 100644
--- a/docs/features/cos-enhancement.md
+++ b/docs/features/cos-enhancement.md
@@ -2,7 +2,7 @@
> **Status:** This M35 milestone spec shipped, except the Phase 5 agent-architecture services (`agentGateway.js`, `errorRecovery.js`, `agentRunCache.js`, `contextUpgrader.js`) and `sessionDelta.js`, which were never built under those names. Their rows below are marked "(not built)" and kept for historical legibility.
-Comprehensive upgrade from reactive task executor to proactive autonomous agent with hybrid memory, missions, local model integration, and dynamic thinking levels.
+Comprehensive upgrade from reactive task executor to proactive autonomous agent with hybrid memory, missions, and local model integration.
## Architecture
@@ -22,7 +22,7 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
| `server/services/missions.js` | Long-term goal and mission management (removed, #6826 — nothing in production ever created a mission; superseded by the Goals system) |
| `server/services/lmStudioManager.js` | LM Studio model discovery and health |
| `server/services/localThinking.js` | Local model completions |
-| `server/services/thinkingLevels.js` | Dynamic model selection |
+| `server/services/thinkingLevels.js` | Dynamic model selection (removed, #8149 — tier/model choice is explicit; see [MODEL_TIERS.md](../MODEL_TIERS.md)) |
| `server/services/contextUpgrader.js` | Complexity analysis for model upgrade (not built) |
## Features
@@ -48,12 +48,11 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
- Memory classification using local models
- Embeddings via local LM Studio
-### Phase 4: Dynamic Model Selection
+### Phase 4: Dynamic Model Selection (removed)
-- Thinking levels: off, minimal, low, medium, high, xhigh
-- Level resolution hierarchy: task → hooks → agent → provider
-- Context upgrader with complexity analysis
-- COS self-evolution with automatic model changes
+Priority/description-driven thinking levels and automatic tier changes were
+removed in #8149: a task runs on the model or tier it names, else the provider
+default. See [MODEL_TIERS.md](../MODEL_TIERS.md).
### Phase 5: Agent Architecture
@@ -70,17 +69,6 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
| standard | 2 | Normal development tasks |
| background | 3 | Self-improvement, documentation |
-## Thinking Levels
-
-| Level | Description | Model Tier |
-|-------|-------------|------------|
-| off | No extended thinking | light |
-| minimal | Brief analysis | light |
-| low | Standard analysis | medium |
-| medium | Thorough analysis | medium |
-| high | Deep analysis | heavy |
-| xhigh | Maximum analysis | heavy |
-
## Error Recovery Strategies
| Strategy | When Used |
@@ -188,7 +176,6 @@ opening line. Off by default.
|-----------|--------|
| `server/lib/bm25.test.js` | BM25 Algorithm |
| `server/services/toolStateMachine.test.js` | Tool State Machine |
-| `server/services/thinkingLevels.test.js` | Thinking Levels |
| `server/services/executionLanes.test.js` | Execution Lanes |
| `server/services/errorRecovery.test.js` | Error Recovery (not built) |
| `server/services/agentRunCache.test.js` | Agent Run Cache (not built) |
diff --git a/scripts/migrations/409-canonical-stage-model-tiers.js b/scripts/migrations/409-canonical-stage-model-tiers.js
new file mode 100644
index 0000000000..ddab760c45
--- /dev/null
+++ b/scripts/migrations/409-canonical-stage-model-tiers.js
@@ -0,0 +1,58 @@
+/**
+ * Rewrite legacy stage tier spellings to the one tier vocabulary (#8149).
+ *
+ * Prompt stages named the provider's light and medium models `quick` and
+ * `coding`, while everything else (MODEL_TIERS, task metadata, orchestration
+ * roles, dispatch labels) says `light` and `medium`. The Prompt Manager and the
+ * Writers Room stage picker now write only the canonical names, so a stored
+ * `quick`/`coding` would render as an unselected option. This rewrites the
+ * stage `model` and `judgeModel` fields in `data/prompts/stage-config.json`.
+ *
+ * Safe for mixed-version peers: every stageRunner that ships a `light`/`medium`
+ * alias (all of them since the tier map existed) resolves the new spelling, and
+ * the current stageRunner still reads the legacy spelling. Idempotent, and a
+ * missing file (fresh install before setup-data) is a no-op.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileCore.js';
+
+const STAGE_CONFIG_PATH = join('data', 'prompts', 'stage-config.json');
+const LEGACY_TIERS = Object.freeze({ quick: 'light', coding: 'medium' });
+const TIER_FIELDS = Object.freeze(['model', 'judgeModel']);
+
+export default {
+ async up({ rootDir }) {
+ const fullPath = join(rootDir, STAGE_CONFIG_PATH);
+ const raw = await readFile(fullPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return { stages: 0 };
+ let config;
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ throw new Error(`${STAGE_CONFIG_PATH} is not valid JSON (${err.message}) — repair it and re-run migrations`);
+ }
+ const stages = config?.stages;
+ if (!stages || typeof stages !== 'object' || Array.isArray(stages)) return { stages: 0 };
+
+ let changed = 0;
+ for (const stage of Object.values(stages)) {
+ if (!stage || typeof stage !== 'object') continue;
+ let touched = false;
+ for (const field of TIER_FIELDS) {
+ const canonical = LEGACY_TIERS[stage[field]];
+ if (canonical) {
+ stage[field] = canonical;
+ touched = true;
+ }
+ }
+ if (touched) changed += 1;
+ }
+ if (changed) await atomicWrite(fullPath, `${JSON.stringify(config, null, 2)}\n`);
+ return { stages: changed };
+ },
+};
diff --git a/scripts/migrations/409-canonical-stage-model-tiers.test.js b/scripts/migrations/409-canonical-stage-model-tiers.test.js
new file mode 100644
index 0000000000..b367f889e9
--- /dev/null
+++ b/scripts/migrations/409-canonical-stage-model-tiers.test.js
@@ -0,0 +1,50 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './409-canonical-stage-model-tiers.js';
+
+describe('migration 409 — canonical stage model tiers', () => {
+ let rootDir;
+ let configPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-409-'));
+ mkdirSync(join(rootDir, 'data', 'prompts'), { recursive: true });
+ configPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('rewrites quick/coding on model and judgeModel, leaving pins and other tiers alone, idempotently', async () => {
+ writeFileSync(configPath, JSON.stringify({
+ stages: {
+ a: { name: 'A', model: 'quick', judgeModel: 'coding', variables: [] },
+ b: { name: 'B', model: 'heavy' },
+ c: { name: 'C', provider: 'lmstudio', model: 'coding-model-7b' },
+ d: { name: 'D', model: 'default', judgeModel: 'quick' },
+ },
+ }));
+
+ expect(await migration.up({ rootDir })).toEqual({ stages: 2 });
+ const { stages } = JSON.parse(readFileSync(configPath, 'utf8'));
+ expect(stages.a).toEqual({ name: 'A', model: 'light', judgeModel: 'medium', variables: [] });
+ expect(stages.b.model).toBe('heavy');
+ expect(stages.c.model).toBe('coding-model-7b');
+ expect(stages.d).toEqual({ name: 'D', model: 'default', judgeModel: 'light' });
+
+ const afterFirst = readFileSync(configPath, 'utf8');
+ expect(await migration.up({ rootDir })).toEqual({ stages: 0 });
+ expect(readFileSync(configPath, 'utf8')).toBe(afterFirst);
+ });
+
+ it('is a no-op when the stage config does not exist yet', async () => {
+ expect(await migration.up({ rootDir })).toEqual({ stages: 0 });
+ });
+
+ it('refuses to guess at a corrupt stage config', async () => {
+ writeFileSync(configPath, '{ not json');
+ await expect(migration.up({ rootDir })).rejects.toThrow(/not valid JSON/);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index f83bd5c945..ab06421525 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -201,6 +201,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). |
| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. |
| `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |
+| `stageModelTiers.js` | The prompt-stage `model`/`judgeModel` tier vocabulary (#8149): `STAGE_MODEL_TIERS` (`default` + the shared MODEL_TIERS), `STAGE_MODEL_TIER_OPTIONS` (the picker rows every stage model select renders), `LEGACY_STAGE_MODEL_TIERS` (`quick`→light, `coding`→medium, still readable from older peers/backups), `canonicalStageModelTier`, `isStageModelTier` (tier vs model-id pin). Pure — the client re-exports it. |
| `stagePinPolicy.js` | Run-scoped "ignore per-stage LLM pins" switch (AsyncLocalStorage) — `withStagePinsIgnored(ignore, fn)` marks an async subtree, `stagePinsIgnored()` reads it, and `services/stageRunner.js#effectiveStage` enumerates which stage-config fields it strips. Backs Series Autopilot's "use one provider/model for every stage" option. |
| `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. |
@@ -644,7 +645,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate), `boundedByJsonChars` (longest prefix of a list whose JSON encoding fits a character budget — the shared prompt-catalog truncation loop). |
| `openapiSpec.js` | Builds two OpenAPI 3.0.3 documents: the Settings-controlled exposed public surface and the complete internal HTTP inventory. Detailed operations reuse canonical Zod contracts; generated operations are visibly labeled rather than claiming unmodeled schemas. |
| `openapiDowngrade.js` | `OPENAPI_VERSION` plus `toOpenApi30Schema` / `toOpenApi30Operation`, which rewrite Zod's draft-2020-12 output (null unions, numeric exclusive bounds, `const`, tuples, `propertyNames`) into the OpenAPI 3.0.3 dialect. Apply ONLY at the OpenAPI document boundary — the AsyncAPI payloads, CoS provider tool definitions, and tool resource read the same schemas as plain JSON Schema, where these rewrites silently widen bounds and drop null branches. |
-| `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` (an unsupported rung is an error, never a silent downgrade). |
+| `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` / `resolveStepEffort` (spec rung → role default → run effort; an unsupported rung is an error, never a silent downgrade). |
| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. |
| `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |
| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 14b2540956..fc9e019ae2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -268,6 +268,7 @@ export * from './openAiChatStream.js';
// mediaModels.js — namespace it so the barrel surface is unambiguous.
export * as runners from './runners.js';
export * from './stagePinPolicy.js';
+export * from './stageModelTiers.js';
export * from './tuiHandshake.js';
export * from './tuiShellLaunch.js';
export * from './tuiUsageScrape.js';
diff --git a/server/lib/orchestrationProfile.js b/server/lib/orchestrationProfile.js
index f0907871d0..01fbd7f178 100644
--- a/server/lib/orchestrationProfile.js
+++ b/server/lib/orchestrationProfile.js
@@ -182,3 +182,33 @@ export function parseReasoningDirective(text) {
return { rung };
}
+/**
+ * Resolve the reasoning effort for ONE DELEGATED STEP of an orchestrated run
+ * (#5992), rather than one effort for the whole run.
+ *
+ * Precedence: the `REASONING: <rung>` directive the architect wrote into this
+ * step's spec → the role's configured default from the orchestration profile →
+ * the run-level effort already resolved for the task.
+ *
+ * NEVER rounds. An unsupported rung returns `{ error }` so the caller can refuse
+ * the spec: silently substituting the nearest supported level would run the step
+ * at an effort nobody chose while still reporting success — and the architect
+ * naming a rung deliberately is the entire point of the per-step contract.
+ *
+ * @param {object} options
+ * @param {string} [options.spec] - the delegated step's spec text
+ * @param {object} [options.task] - the task carrying the orchestration profile
+ * @param {string} [options.role] - the role executing this step
+ * @param {string|null} [options.runEffort] - the run-level effort already resolved
+ * @returns {{ effort: string|null, source: string }|{ error: string }}
+ */
+export function resolveStepEffort({ spec = '', task = null, role = PRIMARY_ORCHESTRATION_ROLE, runEffort = null } = {}) {
+ const directive = parseReasoningDirective(spec);
+ if (directive?.error) return { error: directive.error };
+ if (directive?.rung) return { effort: directive.rung, source: 'spec' };
+
+ const roleDefault = roleAssignment(task, role)?.effort;
+ if (roleDefault) return { effort: roleDefault, source: 'role' };
+
+ return { effort: runEffort || null, source: runEffort ? 'run' : 'default' };
+}
diff --git a/server/lib/orchestrationProfile.test.js b/server/lib/orchestrationProfile.test.js
index feb610a8e5..321bb5c4da 100644
--- a/server/lib/orchestrationProfile.test.js
+++ b/server/lib/orchestrationProfile.test.js
@@ -6,6 +6,7 @@ import {
normalizeOrchestrationMode,
normalizeOrchestrationProfile,
parseReasoningDirective,
+ resolveStepEffort,
roleAssignment,
} from './orchestrationProfile.js';
@@ -83,3 +84,43 @@ describe('role vocabulary', () => {
expect([...ORCHESTRATION_ROLES]).toEqual(['architect', 'implementer', 'reviewer']);
});
});
+
+describe('resolveStepEffort — per-delegated-step reasoning (#5992)', () => {
+ it('prefers the rung the architect wrote into the spec over the role default', () => {
+ expect(resolveStepEffort({
+ spec: 'OBJECTIVE: ship it\nREASONING: xhigh',
+ task: orchestrated({ implementer: { effort: 'low' } }),
+ role: 'implementer',
+ runEffort: 'medium',
+ })).toEqual({ effort: 'xhigh', source: 'spec' });
+ });
+
+ it('falls back to the role default, then the run effort, then nothing', () => {
+ const task = orchestrated({ implementer: { effort: 'low' } });
+ expect(resolveStepEffort({ task, role: 'implementer', runEffort: 'medium' }))
+ .toEqual({ effort: 'low', source: 'role' });
+ expect(resolveStepEffort({ task, role: 'reviewer', runEffort: 'medium' }))
+ .toEqual({ effort: 'medium', source: 'run' });
+ expect(resolveStepEffort({ task, role: 'reviewer' }))
+ .toEqual({ effort: null, source: 'default' });
+ });
+
+ it('errors on an unsupported rung rather than downgrading it to a supported one', () => {
+ const result = resolveStepEffort({
+ spec: 'REASONING: galaxy-brain',
+ task: orchestrated({ implementer: { effort: 'low' } }),
+ role: 'implementer',
+ runEffort: 'medium',
+ });
+ expect(result.error).toContain('galaxy-brain');
+ expect(result.effort).toBeUndefined();
+ });
+
+ it('ignores a profile the task has not switched into orchestrated mode', () => {
+ expect(resolveStepEffort({
+ task: { metadata: { orchestrationProfile: { implementer: { effort: 'low' } } } },
+ role: 'implementer',
+ runEffort: 'medium',
+ })).toEqual({ effort: 'medium', source: 'run' });
+ });
+});
diff --git a/server/lib/stageModelTiers.js b/server/lib/stageModelTiers.js
new file mode 100644
index 0000000000..e0a4b47013
--- /dev/null
+++ b/server/lib/stageModelTiers.js
@@ -0,0 +1,37 @@
+/**
+ * The model-tier vocabulary a prompt stage's `model` / `judgeModel` field uses
+ * (#8149). A stage names either an exact model id (a pin) or one of these tiers,
+ * which resolves on whichever provider runs the stage.
+ *
+ * The tiers are the shared MODEL_TIERS (the same names task metadata,
+ * orchestration roles and dispatch labels use) plus `default` — "no tier, use
+ * the provider's default model". `quick`/`coding` are the legacy stage
+ * spellings of light/medium: migration 409 rewrites stored configs and the
+ * pickers write only canonical names, but a config synced from an older peer or
+ * restored from a backup can still carry them, so they stay readable forever.
+ */
+
+import { MODEL_TIERS } from './aiToolkit/constants.js';
+
+export const STAGE_MODEL_TIERS = Object.freeze(['default', ...Object.values(MODEL_TIERS)]);
+
+export const LEGACY_STAGE_MODEL_TIERS = Object.freeze({ quick: 'light', coding: 'medium' });
+
+/** Picker options, in the order every stage model select shows them. */
+export const STAGE_MODEL_TIER_OPTIONS = Object.freeze([
+ { value: 'default', label: 'Default', hint: "the active provider's default model" },
+ { value: 'light', label: 'Light', hint: "provider's light/fast model" },
+ { value: 'medium', label: 'Medium', hint: "provider's medium model" },
+ { value: 'heavy', label: 'Heavy', hint: "provider's heavy model" },
+ { value: 'ultra', label: 'Ultra', hint: "provider's frontier model" },
+].map(Object.freeze));
+
+/** The canonical tier for a stored stage value; anything else passes through. */
+export function canonicalStageModelTier(value) {
+ return LEGACY_STAGE_MODEL_TIERS[value] || value;
+}
+
+/** True for a tier name (canonical or legacy) — false for a model id pin. */
+export function isStageModelTier(value) {
+ return typeof value === 'string' && STAGE_MODEL_TIERS.includes(canonicalStageModelTier(value));
+}
diff --git a/server/services/agentModelSelection.js b/server/services/agentModelSelection.js
index 3f40092afb..9d699ebcce 100644
--- a/server/services/agentModelSelection.js
+++ b/server/services/agentModelSelection.js
@@ -1,62 +1,28 @@
/**
* Agent Model Selection
*
- * Handles task type key extraction and optimal model selection based on
- * task complexity, thinking levels, and historical performance data.
+ * Resolves the model a task runs on from what the user EXPLICITLY asked for —
+ * a model id or a capability tier on the task (or on an orchestration role) —
+ * and otherwise the provider's own default. Nothing here picks a tier on the
+ * user's behalf (#8149): the description-regex heuristics, the priority-driven
+ * thinking-level mapping, and the learning store's tier substitution all used
+ * to, which let a task configured for "default model" silently run on a
+ * lighter model (#8148). The learning store's per-tier success rates are still
+ * recorded and shown in the CoS Learning view as advice; they never apply here.
*/
import { MODEL_TIERS, resolveProviderModelTier } from '../lib/aiToolkit/constants.js';
-import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';
-import { suggestModelTier } from './taskLearning.js';
-// Imported from the store submodule (not the mocked barrel) so the spawn-time key
-// mirrors the exact same classification the completion records under.
-import { classifyUntypedTask } from './taskLearning/store.js';
-import { taskContextBlock } from '../lib/cosTaskPrompt.js';
import { ORCHESTRATION_ROLES, roleAssignment } from '../lib/orchestrationProfile.js';
-/**
- * Extract task type key for learning lookup.
- *
- * Mirrors the domain `extractTaskType`/`classifyUntypedTask` record in the
- * learning store so the spawn-time routing lookup keys off the SAME bucket the
- * completion will later be recorded under (issue #2333). The fallback delegates
- * to `classifyUntypedTask` — inferring a concrete domain (or the sandboxed
- * `external/untyped` bucket) instead of the old blind `'unknown'`, which would
- * miss the recorded domain and defeat the learning lookup on every untyped task.
- */
-export function extractTaskTypeKey(task) {
- if (task?.metadata?.analysisType) {
- return `self-improve:${task.metadata.analysisType}`;
- }
- if (task?.metadata?.reviewType === 'idle') {
- return 'idle-review';
- }
- const desc = (task?.description || '').toLowerCase();
- if (desc.includes('[self-improvement]')) {
- const typeMatch = desc.match(/\[self-improvement\]\s*(\w+)/i);
- if (typeMatch) return `self-improve:${typeMatch[1]}`;
- }
- if (task?.taskType === 'user') return 'user-task';
- return classifyUntypedTask(task);
-}
+const isModelTier = (value) => Object.values(MODEL_TIERS).includes(value);
-/**
- * Select optimal model for a task based on complexity analysis and historical performance.
- * User can override by specifying Model: and/or Provider: in task metadata.
- *
- * Enhanced with:
- * - Thinking levels hierarchy (task → agent → provider)
- * - Learning-based model suggestions from historical success rates
- * - Automatic upgrades when task type has <60% success rate
- */
/**
* Select the model for ONE ROLE of an orchestrated run (#5992).
*
* An orchestration profile pins architect / implementer / reviewer separately so
* the planning pass can run on a strong model while the mechanical editing runs
- * on a cheap one. A role that pins a model wins outright — it is a user choice,
- * exactly like `metadata.model`, and the complexity heuristics and learning
- * store below have no role dimension to reason about it with.
+ * on a cheap one. A role that pins a model (id or tier) wins outright — it is a
+ * user choice, exactly like `metadata.model`.
*
* Everything else falls through to `selectModelForTask`, so a `direct` task, an
* unpinned role, or an unknown role all resolve exactly as they did before this
@@ -65,13 +31,12 @@ export function extractTaskTypeKey(task) {
* @param {object} task
* @param {string} role - one of ORCHESTRATION_ROLES
* @param {object} provider - resolved provider config
- * @param {object} [agent]
* @returns {Promise<object>} the same selection shape `selectModelForTask` returns
*/
-export async function selectModelForRole(task, role, provider, agent = {}) {
+export async function selectModelForRole(task, role, provider) {
const assignment = ORCHESTRATION_ROLES.includes(role) ? roleAssignment(task, role) : null;
if (assignment?.model) {
- const isTier = Object.values(MODEL_TIERS).includes(assignment.model);
+ const isTier = isModelTier(assignment.model);
console.log(`🎼 Orchestrated ${role} model: ${assignment.model}`);
return {
model: isTier ? resolveProviderModelTier(provider, assignment.model) : assignment.model,
@@ -82,162 +47,26 @@ export async function selectModelForRole(task, role, provider, agent = {}) {
...(assignment.effort ? { orchestrationEffort: assignment.effort } : {}),
};
}
- const selection = await selectModelForTask(task, provider, agent);
+ const selection = await selectModelForTask(task, provider);
return assignment ? { ...selection, orchestrationRole: role, ...(assignment.effort ? { orchestrationEffort: assignment.effort } : {}) } : selection;
}
-export async function selectModelForTask(task, provider, agent = {}) {
- const desc = (task.description || '').toLowerCase();
- // Prompt payload + human note (#4153) — complexity scales with everything the
- // agent is handed, and a legacy `metadata.context`-as-prompt still counts.
- const context = taskContextBlock(task) || '';
- const contextLen = context.length;
- const priority = task.priority || 'MEDIUM';
-
- // Check for user-specified model preference (highest priority)
+/**
+ * Select the model for a task: an explicit `metadata.model` (a tier resolves on
+ * THIS provider, so a fallback provider re-resolves it), else the provider's
+ * `defaultModel`. Async so callers keep one await shape with the role variant.
+ */
+export async function selectModelForTask(task, provider) {
const userModel = task.metadata?.model;
- const userProvider = task.metadata?.provider;
-
if (userModel) {
- const isTier = Object.values(MODEL_TIERS).includes(userModel);
+ const isTier = isModelTier(userModel);
console.log(`👤 User specified model: ${userModel}`);
return {
model: isTier ? resolveProviderModelTier(provider, userModel) : userModel,
tier: isTier ? userModel : 'user-specified',
reason: 'user-preference',
- userProvider: userProvider || null
+ userProvider: task.metadata?.provider || null
};
}
-
- // Check thinking level hierarchy (task → agent → provider)
- const thinkingResult = resolveThinkingLevel(task, agent, provider);
- if (thinkingResult.resolvedFrom !== 'default') {
- const modelFromLevel = getModelForLevel(thinkingResult.level, provider);
- if (modelFromLevel) {
- const isLocal = isLocalPreferred(thinkingResult.level);
- console.log(`🧠 Thinking level: ${thinkingResult.level} → ${modelFromLevel} (from ${thinkingResult.resolvedFrom}${isLocal ? ', local-preferred' : ''})`);
- return {
- model: modelFromLevel,
- tier: thinkingResult.level,
- reason: `thinking-level-${thinkingResult.resolvedFrom}`,
- thinkingLevel: thinkingResult.level,
- localPreferred: isLocal
- };
- }
- }
-
- // Image/visual analysis → would route to gemini if available
- if (/image|screenshot|visual|photo|picture/.test(desc)) {
- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };
- }
-
- // Critical priority → always use opus/heavy
- if (priority === 'CRITICAL') {
- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'critical-priority' };
- }
-
- // Complex reasoning tasks → opus/heavy
- if (/architect|refactor|design|complex|optimize|security|audit|review.*code|performance/.test(desc)) {
- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'complex-task' };
- }
-
- // Long context → needs more capable model
- if (contextLen > 500) {
- return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };
- }
-
- // Detect coding/development tasks - these should NEVER use light model.
- // Intentionally inclusive: if a task mentions any coding-related term (even in
- // broader context like "bug report template"), we err on the side of using
- // a stronger model since misclassifying a coding task is more costly than
- // over-allocating resources for a documentation task.
- const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);
-
- // Simple/quick tasks → haiku/light (ONLY for non-coding tasks)
- // Light model is reserved for documentation, text updates, and formatting only
- if (!isCodingTask && /fix typo|update text|update docs|edit readme|update readme|write docs|documentation only|format text/.test(desc)) {
- return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'documentation-task' };
- }
-
- // Check historical performance for this task type and select optimal model tier
- const taskTypeKey = extractTaskTypeKey(task);
- const learningSuggestion = await suggestModelTier(taskTypeKey).catch(() => null);
-
- if (learningSuggestion) {
- const { suggested, avoidTiers = [], reason: learningReason, failureSignal } = learningSuggestion;
- // Provider/model attribution from the enriched failure signatures (#2329):
- // names WHICH provider/model recently failed for this task type so the
- // routing decision is legible, not just "avoid tier X".
- const failureNote = failureSignal
- ? ` [recent failures: ${failureSignal.failures}× ${failureSignal.tier}${failureSignal.provider ? ` via ${failureSignal.provider}${failureSignal.model ? `/${failureSignal.model}` : ''}` : ''}]`
- : '';
-
- // Map tier names to provider model keys
- const tierToModel = {
- heavy: provider.heavyModel,
- medium: provider.mediumModel || provider.defaultModel,
- default: provider.defaultModel,
- light: provider.lightModel
- };
-
- // The learning store also records thinking-level tier names (minimal/low/
- // high/xhigh) that aren't in tierToModel — resolve those through
- // getModelForLevel so a proven thinking-level suggestion is honored
- // instead of silently falling through to the provider default.
- //
- // EXCEPT the local-preferred levels (minimal/low): getModelForLevel maps
- // them to the cross-provider 'lmstudio' sentinel, but this path keeps the
- // active provider as-is (the localPreferred flag isn't wired to switch
- // providers). Handing resolveAgentProviderAndModel a sentinel a cloud
- // provider can't run makes it fall back to the default model while still
- // recording the local tier — polluting routing accuracy. So treat the
- // sentinel as unresolvable here: such a suggestion falls through to the
- // provider default with an accurate tier, exactly as before this change.
- const LOCAL_SENTINEL_MODELS = new Set(['lmstudio']);
- const resolveTierModel = (tier) => {
- const model = tierToModel[tier] ?? getModelForLevel(tier, provider);
- return model && !LOCAL_SENTINEL_MODELS.has(model) ? model : null;
- };
-
- // If we have a specific tier suggestion, use it
- const suggestedModel = suggested ? resolveTierModel(suggested) : null;
- if (suggestedModel) {
- console.log(`📊 Learning-based selection: ${taskTypeKey} → ${suggested} (${learningReason})${failureNote}`);
- return {
- model: suggestedModel,
- tier: suggested,
- reason: 'learning-suggested',
- // Stated here, at the moment this module substitutes a tier the task
- // never asked for, rather than left for a downstream caller to infer
- // by matching this `reason` string — a fragile proxy a future third
- // learning-tier reason could silently bypass (#8148).
- isLearningTierOverride: true,
- learningReason,
- avoidedTiers: avoidTiers.length > 0 ? avoidTiers : undefined
- };
- }
-
- // If no specific suggestion but we have tiers to avoid, pick the best available tier
- if (avoidTiers.length > 0) {
- // Try tiers in order of preference: heavy → medium → default → light
- // Skip any that are in avoidTiers
- const tierPreference = ['heavy', 'medium', 'default', 'light'];
- for (const tier of tierPreference) {
- if (!avoidTiers.includes(tier) && tierToModel[tier]) {
- console.log(`📊 Learning-based avoidance: ${taskTypeKey} → ${tier} (avoiding ${avoidTiers.join(', ')})${failureNote}`);
- return {
- model: tierToModel[tier],
- tier,
- reason: 'learning-avoid-bad-tier',
- isLearningTierOverride: true,
- learningReason,
- avoidedTiers: avoidTiers
- };
- }
- }
- }
- }
-
- // Standard tasks → use provider's default model
- return { model: provider.defaultModel, tier: 'default', reason: 'standard-task' };
+ return { model: provider.defaultModel, tier: 'default', reason: 'provider-default' };
}
diff --git a/server/services/agentModelSelection.test.js b/server/services/agentModelSelection.test.js
index 8b16417a34..1e84db4378 100644
--- a/server/services/agentModelSelection.test.js
+++ b/server/services/agentModelSelection.test.js
@@ -1,14 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-// Mock the learning store so we control what suggestModelTier returns; keep
-// thinkingLevels real so getModelForLevel/isLocalPreferred resolution is exercised.
+// The learning store is mocked only to prove selection never consults it: a
+// proven `medium` suggestion used to swap a "default model" task onto the
+// provider's lighter mediumModel with no trace (#8148).
vi.mock('./taskLearning.js', () => ({
suggestModelTier: vi.fn()
}));
-import { selectModelForRole, selectModelForTask, extractTaskTypeKey } from './agentModelSelection.js';
+import { selectModelForRole, selectModelForTask } from './agentModelSelection.js';
import { suggestModelTier } from './taskLearning.js';
-import { EXTERNAL_UNTYPED_TASK_TYPE } from './taskLearning/store.js';
const PROVIDER = {
defaultModel: 'default-model',
@@ -17,95 +17,51 @@ const PROVIDER = {
lightModel: 'light-model'
};
-// A description that matches none of the heuristic branches (image/critical/
-// complex/long-context/documentation), with no priority or thinking metadata
-// so resolveThinkingLevel resolves "from default" and selection falls through
-// to the learning path rather than the thinking-level early return.
const benignTask = { description: 'organize the weekly digest', taskType: 'user' };
-describe('selectModelForTask — learning-suggested tier resolution', () => {
+describe('selectModelForTask — no implicit tier routing (#8149)', () => {
beforeEach(() => vi.clearAllMocks());
- it('honors a literal-tier suggestion via the static map', async () => {
- suggestModelTier.mockResolvedValue({ suggested: 'light', reason: 'r' });
- const result = await selectModelForTask(benignTask, PROVIDER);
- expect(result.model).toBe('light-model');
- expect(result.tier).toBe('light');
- expect(result.reason).toBe('learning-suggested');
- // Stated here at decision time (#8148) so a downstream caller can flag a
- // silent downgrade off the provider default without re-deriving it from
- // matching the `reason` string.
- expect(result.isLearningTierOverride).toBe(true);
- });
-
- it('resolves a thinking-level suggestion (high) through getModelForLevel instead of dropping to default', async () => {
- suggestModelTier.mockResolvedValue({ suggested: 'high', reason: 'r' });
- const result = await selectModelForTask(benignTask, PROVIDER);
- // high → provider-heavy
- expect(result.model).toBe('heavy-model');
- expect(result.tier).toBe('high');
- expect(result.reason).toBe('learning-suggested');
- expect(result.isLearningTierOverride).toBe(true);
- });
-
- it('does NOT honor a local-preferred thinking-level suggestion under a cloud provider — falls through with an accurate tier', async () => {
- // minimal/low map to the cross-provider 'lmstudio' sentinel; honoring it here
- // would mis-record the local tier while the run actually uses the default.
- suggestModelTier.mockResolvedValue({ suggested: 'minimal', reason: 'r' });
- const result = await selectModelForTask(benignTask, PROVIDER);
- expect(result.tier).toBe('default');
- expect(result.reason).toBe('standard-task');
- expect(result.isLearningTierOverride).toBeUndefined();
- });
-
- it('falls through to default when the suggested tier resolves to no model', async () => {
- // user-specified is not a thinking level → getModelForLevel returns null, no static map entry.
- suggestModelTier.mockResolvedValue({ suggested: 'user-specified', reason: 'r' });
- const result = await selectModelForTask(benignTask, PROVIDER);
- expect(result.tier).toBe('default');
- expect(result.reason).toBe('standard-task');
- expect(result.isLearningTierOverride).toBeUndefined();
+ it('runs an unpinned task on the provider default even when learning would suggest another tier', async () => {
+ suggestModelTier.mockResolvedValue({ suggested: 'medium', reason: 'proven' });
+ const result = await selectModelForTask({ ...benignTask, metadata: { analysisType: 'claim-issue' } }, PROVIDER);
+ expect(result).toEqual({ model: 'default-model', tier: 'default', reason: 'provider-default' });
+ expect(suggestModelTier).not.toHaveBeenCalled();
});
- it('also marks isLearningTierOverride when avoiding a bad tier rather than following a specific suggestion', async () => {
- suggestModelTier.mockResolvedValue({ suggested: null, avoidTiers: ['heavy'], reason: 'r' });
- const result = await selectModelForTask(benignTask, PROVIDER);
- expect(result.model).toBe('medium-model');
- expect(result.tier).toBe('medium');
- expect(result.reason).toBe('learning-avoid-bad-tier');
- expect(result.isLearningTierOverride).toBe(true);
+ it('ignores description, priority and context size — none of them pick a tier', async () => {
+ const tasks = [
+ { description: 'architect and refactor the security audit screenshot', priority: 'CRITICAL' },
+ { description: 'fix typo in readme', priority: 'LOW' },
+ { description: 'simple task', metadata: { context: 'x'.repeat(5000) } },
+ ];
+ for (const task of tasks) {
+ expect(await selectModelForTask(task, PROVIDER)).toMatchObject({ model: 'default-model', tier: 'default' });
+ }
});
-});
-describe('extractTaskTypeKey — spawn-time key mirror (issue #2333)', () => {
- it('keeps the existing explicit-branch keys', () => {
- expect(extractTaskTypeKey({ metadata: { analysisType: 'ui-bugs' } })).toBe('self-improve:ui-bugs');
- expect(extractTaskTypeKey({ metadata: { reviewType: 'idle' } })).toBe('idle-review');
- expect(extractTaskTypeKey({ description: '[self-improvement] security audit' })).toBe('self-improve:security');
- expect(extractTaskTypeKey({ taskType: 'user' })).toBe('user-task');
+ it('resolves an explicit tier on the given provider, with Ultra falling back to heavy', async () => {
+ const task = { description: 'plan', metadata: { model: 'ultra' } };
+ expect(await selectModelForTask(task, { ...PROVIDER, ultraModel: 'frontier-model' }))
+ .toMatchObject({ model: 'frontier-model', tier: 'ultra' });
+ expect(await selectModelForTask(task, PROVIDER)).toMatchObject({ model: 'heavy-model', tier: 'ultra' });
+ expect(await selectModelForTask({ ...task, metadata: { model: 'light' } }, { defaultModel: 'only-default' }))
+ .toMatchObject({ model: 'only-default', tier: 'light' });
});
- it('delegates the fallback to classifyUntypedTask instead of the old blind "unknown"', () => {
- // A description with no explicit branch match but a classifier keyword →
- // the concrete recorded domain, not 'unknown'.
- expect(extractTaskTypeKey({ description: 'fix the crashing login flow' })).toBe('auto-fix');
- // Nothing classifiable → the sandboxed fallback bucket the store records.
- expect(extractTaskTypeKey({ description: 'organize the weekly digest' })).toBe(EXTERNAL_UNTYPED_TASK_TYPE);
- // Never the legacy 'unknown' sink.
- expect(extractTaskTypeKey({})).not.toBe('unknown');
+ it('passes an explicit model id through as a user pin with its provider', async () => {
+ expect(await selectModelForTask({ description: 'x', metadata: { model: 'exact-model', provider: 'codex' } }, PROVIDER))
+ .toEqual({ model: 'exact-model', tier: 'user-specified', reason: 'user-preference', userProvider: 'codex' });
});
});
describe('selectModelForRole — orchestration profiles (#5992)', () => {
- beforeEach(() => vi.clearAllMocks());
-
const orchestratedTask = (profile) => ({
...benignTask,
metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: profile },
});
- it('honors the role model pin over the complexity heuristics', async () => {
- suggestModelTier.mockResolvedValue(null);
+ it('honors the role model pin', async () => {
const result = await selectModelForRole(
orchestratedTask({ implementer: { model: 'cheap-model', provider: 'codex' } }),
'implementer',
@@ -115,7 +71,6 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
expect(result.tier).toBe('user-specified');
expect(result.reason).toBe('orchestration-role-implementer');
expect(result.userProvider).toBe('codex');
- expect(suggestModelTier).not.toHaveBeenCalled();
});
it('resolves role capability independently from reasoning effort', async () => {
@@ -127,7 +82,6 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
});
it('falls through to selectModelForTask for a role the profile does not pin', async () => {
- suggestModelTier.mockResolvedValue(null);
const task = orchestratedTask({ architect: { model: 'opus' } });
const direct = await selectModelForTask(task, PROVIDER);
const role = await selectModelForRole(task, 'reviewer', PROVIDER);
@@ -137,7 +91,6 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
});
it('carries a role effort default forward even when only the model falls through', async () => {
- suggestModelTier.mockResolvedValue(null);
const result = await selectModelForRole(
orchestratedTask({ reviewer: { effort: 'low' } }),
'reviewer',
@@ -149,7 +102,6 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
});
it('is byte-identical to selectModelForTask on a direct-mode task, profile or not', async () => {
- suggestModelTier.mockResolvedValue(null);
const task = {
...benignTask,
metadata: { orchestrationProfile: { architect: { model: 'opus' } } },
@@ -159,7 +111,6 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
});
it('ignores an unknown role rather than treating it as unpinned config', async () => {
- suggestModelTier.mockResolvedValue(null);
const result = await selectModelForRole(
orchestratedTask({ architect: { model: 'opus' } }),
'saboteur',
@@ -169,14 +120,3 @@ describe('selectModelForRole — orchestration profiles (#5992)', () => {
expect(result.orchestrationRole).toBeUndefined();
});
});
-
-describe('explicit capability tiers', () => {
- it('resolves Ultra on the selected provider and falls back on legacy providers', async () => {
- const task = { description: 'plan', metadata: { model: 'ultra' } };
- expect(await selectModelForTask(task, { ...PROVIDER, ultraModel: 'frontier-model' }))
- .toMatchObject({ model: 'frontier-model', tier: 'ultra' });
- expect(await selectModelForTask(task, PROVIDER)).toMatchObject({ model: 'heavy-model', tier: 'ultra' });
- expect(await selectModelForTask({ ...task, metadata: { model: 'exact-model' } }, PROVIDER))
- .toMatchObject({ model: 'exact-model', tier: 'user-specified' });
- });
-});
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index 1c66b80ff3..2c890e5695 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -329,7 +329,7 @@ async function resolveOrdinaryProviderAndModel(task) {
};
}
- // Select optimal model for this task (async to allow learning-based suggestions).
+ // Resolve the task's model: its explicit pin or tier, else the provider default.
// Routed through the ARCHITECT role so an orchestrated task's planning model
// wins here; with no profile this is `selectModelForTask` unchanged.
const modelSelection = await selectModelForRole(task, PRIMARY_ORCHESTRATION_ROLE, provider);
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 003d37e2c6..9a9c887a41 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -142,12 +142,6 @@ vi.mock('./toolStateMachine.js', () => ({
getStats: vi.fn()
}));
-vi.mock('./thinkingLevels.js', () => ({
- resolveThinkingLevel: vi.fn(),
- getModelForLevel: vi.fn(),
- isLocalPreferred: vi.fn(() => false)
-}));
-
vi.mock('./executionLanes.js', () => ({
determineLane: vi.fn(),
acquire: vi.fn(() => ({ success: true })),
diff --git a/server/services/promptSections/orchestrationDoctrine.js b/server/services/promptSections/orchestrationDoctrine.js
index b8ab018909..9471659105 100644
--- a/server/services/promptSections/orchestrationDoctrine.js
+++ b/server/services/promptSections/orchestrationDoctrine.js
@@ -10,7 +10,7 @@
* The section is the whole delivery mechanism for the per-step reasoning rung:
* PortOS cannot intercept an agent's own sub-agent dispatch, so the contract is
* stated here and the architect writes `REASONING: <rung>` into each spec, which
- * `thinkingLevels.resolveStepEffort` then reads back without rounding.
+ * `orchestrationProfile.resolveStepEffort` then reads back without rounding.
*
* Renders '' for every `direct`-mode task, which is every task by default.
*/
diff --git a/server/services/stageRunner.js b/server/services/stageRunner.js
index 6b2c5fdf83..f24948d64d 100644
--- a/server/services/stageRunner.js
+++ b/server/services/stageRunner.js
@@ -38,23 +38,9 @@ import { clampToRuntimeContextWindow } from '../lib/aiToolkit/internal/ollamaBac
// ambient `OLLAMA_CONTEXT_LENGTH` PortOS launches the daemon with (#7472).
import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';
import { createRun, patchRunMetadata } from './runner.js';
+import { canonicalStageModelTier, isStageModelTier } from '../lib/stageModelTiers.js';
import { resolveProviderModelTier, MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from '../lib/aiToolkit/constants.js';
-// Stage configs name a model by tier (PromptManager UI). Map each tier name
-// to the provider's per-tier model field; an unset tier falls through to
-// `defaultModel`.
-const TIER_TO_MODEL_KEY = Object.freeze({
- default: 'defaultModel',
- quick: 'lightModel',
- coding: 'mediumModel',
- heavy: 'heavyModel',
- ultra: 'ultraModel',
- light: 'lightModel',
- medium: 'mediumModel',
-});
-
-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
@@ -67,7 +53,7 @@ const ROUTING_PIN_FIELDS = Object.freeze(['provider', 'effort', 'judgeProvider',
// 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 `model` TIER (default/light/medium/heavy/ultra) — 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.
@@ -80,7 +66,7 @@ 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;
+ if (stripped.model && !isStageModelTier(stripped.model)) delete stripped.model;
return stripped;
}
@@ -126,8 +112,8 @@ function normalizeTimeout(raw) {
export function resolveModel(provider, modelHint) {
if (!modelHint) return providerFallbackModel(provider);
- if (isTierName(modelHint)) {
- return resolveProviderModelTier(provider, modelHint) || provider[TIER_TO_MODEL_KEY[modelHint]] || providerFallbackModel(provider);
+ if (isStageModelTier(modelHint)) {
+ return resolveProviderModelTier(provider, canonicalStageModelTier(modelHint)) || providerFallbackModel(provider);
}
return modelHint;
}
@@ -138,8 +124,8 @@ export function resolveModel(provider, modelHint) {
// `stage.provider` is opt-in — almost no stage sets one — so a run-level
// `providerDefault` applies to the common (unpinned) case and only loses to the
// rare deliberate `stage.provider` pin. But nearly every stage in the shipped
-// `stage-config.json` carries a `stage.model` *tier* value (`default`/`quick`/
-// `coding`/`heavy`) — that tier is the model-dimension equivalent of "no
+// `stage-config.json` carries a `stage.model` *tier* value (`default`/`light`/
+// `medium`/`heavy`/`ultra`) — that tier is the model-dimension equivalent of "no
// provider pinned", a default mapping, NOT a deliberate per-stage model choice.
// So a run-level `modelDefault` must OVERRIDE a stage's tier (otherwise
// launching Series Autopilot with a model would be a no-op on ~every stage),
@@ -150,15 +136,15 @@ export function resolveModel(provider, modelHint) {
// 1. modelOverride — hard per-call model id (manual "regenerate with model X")
// 2. explicit stage.model — a deliberate pin (non-tier model id) beats the run default
// 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)
+// 4. stage.model tier — the stage's default tier mapping (default/light/medium/heavy/ultra)
// 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;
- const stageTier = isTierName(stageModel) ? stageModel : null;
+ const stagePin = stageModel && !isStageModelTier(stageModel) ? stageModel : null;
+ const stageTier = isStageModelTier(stageModel) ? stageModel : null;
return options.modelOverride || stagePin || options.modelDefault || stageTier || null;
}
@@ -498,7 +484,7 @@ export function extractJson(text, { promptToStrip } = {}) {
* provider if unavailable (see resolveProviderForStage)
* - modelOverride: explicit model id (hard), beats everything
* - modelDefault: blanket run-level model id (Series Autopilot's run model,
- * #1558). Soft: it OVERRIDES a stage's tier value (default/quick/coding/heavy)
+ * #1558). Soft: it OVERRIDES a stage's tier value (default/light/medium/heavy/ultra)
* but LOSES to a deliberate explicit-model pin (a non-tier model id) and to a
* hard modelOverride. See resolveModelHint for the full precedence — the model
* dimension is deliberately NOT symmetric with providerDefault because nearly
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index 6e85936fe0..54b9d1b050 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -94,6 +94,9 @@ describe('stageRunner — resolveModel', () => {
it('maps tier names to per-tier provider keys, falls back to defaultModel when missing', () => {
const p = { defaultModel: 'd', lightModel: 'l', mediumModel: 'm', heavyModel: 'h' };
+ expect(resolveModel(p, 'light')).toBe('l');
+ expect(resolveModel(p, 'medium')).toBe('m');
+ // Legacy stage spellings stay readable (older peers, backups) — #8149.
expect(resolveModel(p, 'quick')).toBe('l');
expect(resolveModel(p, 'coding')).toBe('m');
expect(resolveModel(p, 'heavy')).toBe('h');
@@ -615,7 +618,7 @@ describe('stageRunner — runStagedLLM model resolution (#1558)', () => {
});
it('lets modelDefault OVERRIDE a stage TIER value (the run model applies to unpinned/tier stages)', async () => {
- // A tier (default/quick/coding/heavy) is NOT a deliberate pin — the run model
+ // A tier (default/light/medium/heavy/ultra) is NOT a deliberate pin — the run model
// must win, else launching autopilot with a model is a no-op on ~every stage.
prompts.getStage.mockReturnValue({ model: 'heavy' });
providers.getActiveProvider.mockResolvedValue(apiProvider({ heavyModel: 'h' }));
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
index 755f2e4a90..91f0267d40 100644
--- a/server/services/subAgentSpawner.test.js
+++ b/server/services/subAgentSpawner.test.js
@@ -1,28 +1,6 @@
// vi.mock() calls are hoisted by Vitest before import evaluation, but are placed
// at the top for clarity and to match the convention in other test files.
-// Mock taskLearning so suggestModelTier returns null → pattern-matching path runs.
-// This matches the behavior of the old inline selectModelForTask copy.
-vi.mock('./taskLearning.js', async (importOriginal) => {
- const actual = await importOriginal();
- return {
- ...actual,
- suggestModelTier: vi.fn().mockResolvedValue(null)
- };
-});
-
-// Mock thinkingLevels so resolveThinkingLevel returns resolvedFrom:'default'
-// (no override), which skips the thinking-level model-selection path.
-vi.mock('./thinkingLevels.js', async (importOriginal) => {
- const actual = await importOriginal();
- return {
- ...actual,
- resolveThinkingLevel: vi.fn().mockReturnValue({ level: 'off', resolvedFrom: 'default' }),
- getModelForLevel: vi.fn().mockReturnValue(null),
- isLocalPreferred: vi.fn().mockReturnValue(false)
- };
-});
-
// ── Listener-guard suite support (see "CoS event listener rejection guards").
// `initSpawner()` wires the real `task:ready` / `agent:terminate` listeners onto
// the shared `cosEvents` emitter; these mocks keep that wiring off the network,
@@ -84,7 +62,6 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vite
import { isTruthyMeta, isFalsyMeta } from './agentState.js';
import { cosEvents } from './cosEvents.js';
import { initSpawner } from './subAgentSpawner.js';
-import { selectModelForTask } from './agentModelSelection.js';
import { applyAppWorktreeDefault } from './cos.js';
/**
@@ -100,201 +77,6 @@ import { applyAppWorktreeDefault } from './cos.js';
* we focus on the decision-making logic that can be unit tested.
*/
-// Test model selection logic using the real exported selectModelForTask
-describe('Model Selection Logic', () => {
- const mockProvider = {
- id: 'anthropic',
- name: 'Anthropic',
- defaultModel: 'claude-3-sonnet',
- lightModel: 'claude-3-haiku',
- mediumModel: 'claude-3-sonnet',
- heavyModel: 'claude-3-opus'
- };
-
- describe('User-specified model', () => {
- it('should use user-specified model when provided', async () => {
- const task = {
- description: 'Simple task',
- metadata: { model: 'custom-model' }
- };
-
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.model).toBe('custom-model');
- expect(result.tier).toBe('user-specified');
- expect(result.reason).toBe('user-preference');
- });
-
- it('should include user provider if specified', async () => {
- const task = {
- description: 'Simple task',
- metadata: { model: 'gpt-4', provider: 'openai' }
- };
-
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.userProvider).toBe('openai');
- });
- });
-
- describe('Visual analysis tasks', () => {
- it('should select heavy model for image analysis', async () => {
- const task = { description: 'Analyze this image for errors' };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.model).toBe('claude-3-opus');
- expect(result.tier).toBe('heavy');
- expect(result.reason).toBe('visual-analysis');
- });
-
- it('should select heavy model for screenshot review', async () => {
- const task = { description: 'Review the screenshot' };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.reason).toBe('visual-analysis');
- });
- });
-
- describe('Priority-based selection', () => {
- it('should select heavy model for CRITICAL priority', async () => {
- const task = { description: 'Fix something', priority: 'CRITICAL' };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.model).toBe('claude-3-opus');
- expect(result.reason).toBe('critical-priority');
- });
-
- it('should not use heavy for HIGH priority alone', async () => {
- const task = { description: 'Update a setting', priority: 'HIGH' };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.reason).not.toBe('critical-priority');
- });
- });
-
- describe('Complex task detection', () => {
- it.each([
- ['architect the new module', 'complex-task'],
- ['refactor the auth system', 'complex-task'],
- ['design a new API', 'complex-task'],
- ['optimize performance', 'complex-task'],
- ['security audit', 'complex-task'],
- ['review code for issues', 'complex-task']
- ])('should select heavy model for: %s', async (description, expectedReason) => {
- const task = { description };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.tier).toBe('heavy');
- expect(result.reason).toBe(expectedReason);
- });
- });
-
- describe('Context length handling', () => {
- it('should select heavy model for long context', async () => {
- const task = {
- description: 'Simple task',
- metadata: { context: 'x'.repeat(501) }
- };
-
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.tier).toBe('heavy');
- expect(result.reason).toBe('long-context');
- });
-
- it('should not use heavy model for short context', async () => {
- const task = {
- description: 'Simple update',
- metadata: { context: 'Short context' }
- };
-
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.reason).not.toBe('long-context');
- });
- });
-
- describe('Documentation tasks', () => {
- // Note: The model selection logic checks for coding keywords first,
- // so we use phrases that don't contain words like 'fix', 'bug', etc.
- // which would be detected as coding tasks
- it.each([
- 'update text in guide',
- 'edit readme with new info',
- 'format text only'
- ])('should select light model for: %s', async (description) => {
- const task = { description };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.model).toBe('claude-3-haiku');
- expect(result.tier).toBe('light');
- expect(result.reason).toBe('documentation-task');
- });
-
- // These phrases contain coding keywords so they get default model
- // Note: 'fix' is a coding keyword so 'fix typo' routes to default tier
- it.each([
- 'fix typo in manual',
- 'fix typo in README',
- 'update docs for feature',
- 'write docs for API'
- ])('should NOT select light model when coding keyword present: %s', async (description) => {
- const task = { description };
- const result = await selectModelForTask(task, mockProvider);
-
- // These contain words like 'fix', 'docs', 'API' which are coding keywords
- expect(result.tier).not.toBe('light');
- });
- });
-
- describe('Coding tasks detection', () => {
- it.each([
- 'fix bug in login',
- 'implement new feature',
- 'develop API endpoint',
- 'refactor the component',
- 'test the function',
- 'debug the error',
- 'patch the issue'
- ])('should NOT select light model for coding task: %s', async (description) => {
- const task = { description };
- const result = await selectModelForTask(task, mockProvider);
-
- expect(result.tier).not.toBe('light');
- });
-
- it('should use default model for standard coding tasks (real agentModelSelection behavior)', async () => {
- const task = { description: 'Add a new helper function' };
- const result = await selectModelForTask(task, mockProvider);
-
- // Real agentModelSelection.js returns tier:'default', not 'medium'
- expect(result.model).toBe('claude-3-sonnet');
- expect(result.tier).toBe('default');
- expect(result.reason).toBe('standard-task');
- });
- });
-
- describe('Default fallbacks', () => {
- it('should fall back to defaultModel if lightModel not available', async () => {
- const providerNoLight = { ...mockProvider, lightModel: null };
- const task = { description: 'update readme' };
-
- const result = await selectModelForTask(task, providerNoLight);
-
- expect(result.model).toBe('claude-3-sonnet');
- });
-
- it('should fall back to defaultModel if heavyModel not available', async () => {
- const providerNoHeavy = { ...mockProvider, heavyModel: null };
- const task = { description: 'analyze this image' };
-
- const result = await selectModelForTask(task, providerNoHeavy);
-
- expect(result.model).toBe('claude-3-sonnet');
- });
- });
-});
-
// Worktree/PR flag resolution + metadata coercion helpers, exercised through
// the real production helpers (isTruthyMeta/isFalsyMeta/applyAppWorktreeDefault).
describe('Worktree & metadata flag helpers', () => {
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 99e35139da..fcfa6be51b 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -807,6 +807,34 @@ describe('TaskLearning - getRoutingAccuracy', () => {
expect(tiers[1].tier).toBe('medium'); // 60%
expect(tiers[2].tier).toBe('light'); // 20%
});
+
+ it('reports the learned tier advice per task type, and omits it where history says nothing', async () => {
+ const data = makeLearningData({
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 20, succeeded: 8, failed: 12,
+ totalDurationMs: 2000000, avgDurationMs: 100000,
+ successRate: 40
+ }
+ },
+ routingAccuracy: {
+ 'self-improve:ui': {
+ light: { succeeded: 1, failed: 9, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ heavy: { succeeded: 7, failed: 3, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ },
+ 'user-task': {
+ medium: { succeeded: 2, failed: 0, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await getRoutingAccuracy();
+ const byType = Object.fromEntries(result.matrix.map((entry) => [entry.taskType, entry]));
+
+ expect(byType['self-improve:ui'].suggestion.avoidTiers).toContain('light');
+ expect(byType['user-task'].suggestion).toBeUndefined();
+ });
});
describe('TaskLearning - suggestModelTier with routing signals', () => {
diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.js
index 82c1f1247b..c73a3c5ffb 100644
--- a/server/services/taskLearning/routing.js
+++ b/server/services/taskLearning/routing.js
@@ -2,7 +2,8 @@
* Task Learning — heuristic routing & scheduling decisions
*
* The "read" side of the learning data that drives runtime decisions:
- * priority multipliers, model-tier suggestions, routing-accuracy matrices,
+ * priority multipliers, advisory model-tier suggestions (reported in the CoS
+ * Learning view, never applied at dispatch — #8149), routing-accuracy matrices,
* adaptive cooldowns, skip/rehabilitation gating, and per-task-type
* confidence tiers. None of these mutate the store except the
* rehabilitation path, which delegates the actual reset to the metrics
@@ -19,12 +20,13 @@ import { computeCorrelationQuality, isCorrelationProven } from './correlationQua
* that both clear the high-success threshold: prefer the cheapest tier that
* still works well.
*
- * The keys here are whatever `selectModelForTask` records as `tier`
- * (agentModelSelection.js → agentLifecycle.js `modelTier`), which is a mixed
- * namespace: the literal tiers (`light`/`default`/`medium`/`heavy`) AND the
- * thinking-level names from thinkingLevels.js (`off`/`minimal`/`low`/`medium`/
- * `high`/`xhigh`, where `minimal`/`low` are local-preferred and therefore the
- * cheapest, and `high`/`xhigh` map to provider-heavy/opus). An unknown name
+ * The keys here are whatever `selectModelForTask` recorded as `tier`
+ * (agentModelSelection.js → agentLifecycle.js `modelTier`). Today that is a
+ * literal tier (`light`/`default`/`medium`/`heavy`/`ultra`) or
+ * `user-specified`, but learning data recorded before #8149 also carries the
+ * retired thinking-level names (`off`/`minimal`/`low`/`medium`/`high`/
+ * `xhigh`, where `minimal`/`low` were local-preferred and therefore the
+ * cheapest, and `high`/`xhigh` mapped to the provider's heavy model). An unknown name
* (e.g. `user-specified`, or a future tier) must NOT be treated as cheap, or
* the "prefer lightest" logic would pick it over a known-light tier — so the
* fallback ranks unknowns as heaviest.
@@ -253,7 +255,11 @@ export async function getTaskTypePriorityMultiplier(taskType) {
/**
* Suggest model tier based on historical performance for a task type
* Enhanced with negative signal awareness: avoids tiers that consistently fail
- * and prefers tiers with proven success for the task type
+ * and prefers tiers with proven success for the task type.
+ *
+ * ADVISORY ONLY (#8149): surfaced per task type by `getRoutingAccuracy` for the
+ * CoS Learning view. Dispatch never reads it — a tier the user did not ask for
+ * silently replaced a task's configured default model (#8148).
*/
export async function suggestModelTier(taskType) {
// Sandboxed fallback (issue #2333): the `external/untyped` bucket aggregates
@@ -476,6 +482,16 @@ export async function getRoutingAccuracy() {
}
misroutes.sort((a, b) => a.successRate - b.successRate);
+ // Advice, not routing: the tier each task type's history recommends, for the
+ // user to pin on the task or schedule if they agree.
+ await Promise.all(matrix.map(async (entry) => {
+ const suggestion = await suggestModelTier(entry.taskType).catch(() => null);
+ const avoidTiers = suggestion?.avoidTiers || [];
+ if (suggestion?.suggested || avoidTiers.length > 0) {
+ entry.suggestion = { tier: suggestion.suggested || null, avoidTiers, reason: suggestion.reason || null };
+ }
+ }));
+
return { matrix, tierOverview, misroutes, totalMisroutes: misroutes.length };
}
diff --git a/server/services/thinkingLevels.js b/server/services/thinkingLevels.js
deleted file mode 100644
index b647aa24e5..0000000000
--- a/server/services/thinkingLevels.js
+++ /dev/null
@@ -1,378 +0,0 @@
-/**
- * Thinking Levels Service
- *
- * Dynamic model selection based on thinking levels.
- * Hierarchy: task → hooks → agent → provider defaults
- */
-
-import { cosEvents } from './cosEvents.js'
-import { PRIMARY_ORCHESTRATION_ROLE, parseReasoningDirective, roleAssignment } from '../lib/orchestrationProfile.js'
-
-// Thinking level definitions
-const THINKING_LEVELS = {
- off: {
- name: 'off',
- model: null,
- maxTokens: 0,
- description: 'No extended thinking, use defaults'
- },
- minimal: {
- name: 'minimal',
- model: 'local-small',
- maxTokens: 256,
- localPreferred: true,
- description: 'Quick local analysis only'
- },
- low: {
- name: 'low',
- model: 'local-medium',
- maxTokens: 1024,
- localPreferred: true,
- description: 'Basic reasoning with local model'
- },
- medium: {
- name: 'medium',
- model: 'provider-default',
- maxTokens: 4096,
- localPreferred: false,
- description: 'Standard cloud model thinking'
- },
- high: {
- name: 'high',
- model: 'provider-heavy',
- maxTokens: 8192,
- localPreferred: false,
- description: 'Advanced reasoning with heavy model'
- },
- xhigh: {
- name: 'xhigh',
- model: 'opus',
- maxTokens: 16384,
- localPreferred: false,
- description: 'Maximum reasoning with provider\'s heaviest model'
- }
-}
-
-// Default thresholds for automatic level selection
-const AUTO_THRESHOLDS = {
- contextLength: {
- minimal: 500,
- low: 1000,
- medium: 3000,
- high: 6000,
- xhigh: 10000
- },
- complexity: {
- minimal: 0.2,
- low: 0.4,
- medium: 0.6,
- high: 0.8,
- xhigh: 0.95
- }
-}
-
-// Task type to default level mapping
-const TASK_TYPE_LEVELS = {
- // Simple tasks
- 'format': 'minimal',
- 'rename': 'minimal',
- 'typo': 'minimal',
- 'comment': 'low',
-
- // Medium tasks
- 'fix-bug': 'medium',
- 'implement': 'medium',
- 'update': 'medium',
-
- // Complex tasks
- 'refactor': 'high',
- 'security': 'high',
- 'optimize': 'high',
- 'architect': 'xhigh',
- 'audit': 'xhigh',
- 'migration': 'xhigh'
-}
-
-// Usage tracking
-const levelUsage = {
- off: 0,
- minimal: 0,
- low: 0,
- medium: 0,
- high: 0,
- xhigh: 0
-}
-
-/**
- * Resolve thinking level for a task
- * Checks hierarchy: task metadata → hooks → agent config → provider defaults
- *
- * @param {Object} task - Task object
- * @param {Object} agent - Agent configuration
- * @param {Object} provider - Provider configuration
- * @returns {Object} - Resolved thinking level configuration
- */
-function resolveThinkingLevel(task, agent = {}, provider = {}) {
- let level = 'medium' // Default
-
- // 1. Check task metadata for explicit level
- if (task?.metadata?.thinkingLevel) {
- level = task.metadata.thinkingLevel
- }
- // 2. Check task priority
- else if (task?.priority) {
- const priority = task.priority.toUpperCase()
- if (priority === 'URGENT' || priority === 'CRITICAL') {
- level = 'high'
- } else if (priority === 'LOW' || priority === 'IDLE') {
- level = 'low'
- }
- }
- // 3. Check task type
- else if (task?.metadata?.taskType) {
- level = TASK_TYPE_LEVELS[task.metadata.taskType] || level
- }
- // 4. Check agent default
- else if (agent?.defaultThinkingLevel) {
- level = agent.defaultThinkingLevel
- }
- // 5. Check provider default
- else if (provider?.defaultThinkingLevel) {
- level = provider.defaultThinkingLevel
- }
-
- // Validate level
- if (!THINKING_LEVELS[level]) {
- level = 'medium'
- }
-
- // Track usage
- levelUsage[level]++
-
- const config = THINKING_LEVELS[level]
-
- cosEvents.emit('thinking:levelResolved', {
- taskId: task?.id,
- level,
- model: config.model,
- source: determineSource(task, agent, provider)
- })
-
- return {
- level,
- ...config,
- resolvedFrom: determineSource(task, agent, provider)
- }
-}
-
-/**
- * Determine where the level was resolved from
- */
-function determineSource(task, agent, provider) {
- if (task?.metadata?.thinkingLevel) return 'task'
- if (task?.priority) return 'priority'
- if (task?.metadata?.taskType) return 'taskType'
- if (agent?.defaultThinkingLevel) return 'agent'
- if (provider?.defaultThinkingLevel) return 'provider'
- return 'default'
-}
-
-/**
- * Suggest thinking level based on task analysis
- * @param {Object} analysis - Task analysis from localThinking
- * @returns {string} - Suggested level
- */
-function suggestLevel(analysis) {
- const complexity = analysis.complexity || 0.5
-
- // Find appropriate level based on complexity
- for (const [level, threshold] of Object.entries(AUTO_THRESHOLDS.complexity).reverse()) {
- if (complexity >= threshold) {
- return level
- }
- }
-
- return 'minimal'
-}
-
-/**
- * Suggest thinking level based on context length
- * @param {number} contextLength - Context length in characters
- * @returns {string} - Suggested level
- */
-function suggestLevelFromContext(contextLength) {
- for (const [level, threshold] of Object.entries(AUTO_THRESHOLDS.contextLength).reverse()) {
- if (contextLength >= threshold) {
- return level
- }
- }
-
- return 'minimal'
-}
-
-/**
- * Get model for a thinking level
- * @param {string} level - Thinking level name
- * @param {Object} provider - Provider config for model mapping
- * @returns {string|null} - Model identifier
- */
-function getModelForLevel(level, provider = {}) {
- const config = THINKING_LEVELS[level]
- if (!config) return null
-
- const modelKey = config.model
-
- switch (modelKey) {
- case null:
- return provider.defaultModel || null
- case 'local-small':
- return 'lmstudio' // Will use LM Studio
- case 'local-medium':
- return 'lmstudio'
- case 'provider-default':
- return provider.defaultModel || null
- case 'provider-heavy':
- return provider.heavyModel || null
- case 'opus':
- return provider.heavyModel || provider.defaultModel || null
- default:
- return modelKey
- }
-}
-
-/**
- * Check if level prefers local execution
- * @param {string} level - Thinking level
- * @returns {boolean} - True if local preferred
- */
-function isLocalPreferred(level) {
- const config = THINKING_LEVELS[level]
- return config?.localPreferred || false
-}
-
-/**
- * Upgrade thinking level by one step
- * @param {string} currentLevel - Current level
- * @returns {string} - Upgraded level
- */
-function upgradeLevel(currentLevel) {
- const levels = Object.keys(THINKING_LEVELS)
- const currentIndex = levels.indexOf(currentLevel)
-
- if (currentIndex === -1) return 'medium'
- if (currentIndex >= levels.length - 1) return currentLevel
-
- return levels[currentIndex + 1]
-}
-
-/**
- * Downgrade thinking level by one step
- * @param {string} currentLevel - Current level
- * @returns {string} - Downgraded level
- */
-function downgradeLevel(currentLevel) {
- const levels = Object.keys(THINKING_LEVELS)
- const currentIndex = levels.indexOf(currentLevel)
-
- if (currentIndex === -1) return 'medium'
- if (currentIndex <= 0) return currentLevel
-
- return levels[currentIndex - 1]
-}
-
-
-/**
- * Resolve the reasoning effort for ONE DELEGATED STEP of an orchestrated run
- * (#5992), rather than one effort for the whole run.
- *
- * Precedence: the `REASONING: <rung>` directive the architect wrote into this
- * step's spec → the role's configured default from the orchestration profile →
- * the run-level effort already resolved for the task.
- *
- * NEVER rounds. An unsupported rung returns `{ error }` so the caller can refuse
- * the spec: silently substituting the nearest supported level would run the step
- * at an effort nobody chose while still reporting success — and the architect
- * naming a rung deliberately is the entire point of the per-step contract.
- *
- * @param {object} options
- * @param {string} [options.spec] - the delegated step's spec text
- * @param {object} [options.task] - the task carrying the orchestration profile
- * @param {string} [options.role] - the role executing this step
- * @param {string|null} [options.runEffort] - the run-level effort already resolved
- * @returns {{ effort: string|null, source: string }|{ error: string }}
- */
-function resolveStepEffort({ spec = '', task = null, role = PRIMARY_ORCHESTRATION_ROLE, runEffort = null } = {}) {
- const directive = parseReasoningDirective(spec)
- if (directive?.error) return { error: directive.error }
- if (directive?.rung) return { effort: directive.rung, source: 'spec' }
-
- const roleDefault = roleAssignment(task, role)?.effort
- if (roleDefault) return { effort: roleDefault, source: 'role' }
-
- return { effort: runEffort || null, source: runEffort ? 'run' : 'default' }
-}
-
-/**
- * Get thinking level statistics
- * @returns {Object} - Usage statistics
- */
-function getStats() {
- const total = Object.values(levelUsage).reduce((a, b) => a + b, 0)
-
- return {
- usage: { ...levelUsage },
- total,
- distribution: Object.entries(levelUsage).reduce((acc, [level, count]) => {
- acc[level] = total > 0 ? ((count / total) * 100).toFixed(1) + '%' : '0%'
- return acc
- }, {}),
- levels: Object.keys(THINKING_LEVELS),
- thresholds: AUTO_THRESHOLDS
- }
-}
-
-/**
- * Reset usage statistics
- */
-function resetStats() {
- for (const level of Object.keys(levelUsage)) {
- levelUsage[level] = 0
- }
-}
-
-/**
- * Update auto thresholds
- * @param {string} thresholdType - 'contextLength' or 'complexity'
- * @param {Object} newThresholds - New threshold values
- */
-function updateThresholds(thresholdType, newThresholds) {
- if (AUTO_THRESHOLDS[thresholdType]) {
- Object.assign(AUTO_THRESHOLDS[thresholdType], newThresholds)
- }
-}
-
-/**
- * Get all thinking levels
- * @returns {Object} - All level configurations
- */
-function getLevels() {
- return { ...THINKING_LEVELS }
-}
-
-export {
- THINKING_LEVELS,
- AUTO_THRESHOLDS,
- TASK_TYPE_LEVELS,
- resolveThinkingLevel,
- resolveStepEffort,
- suggestLevel,
- suggestLevelFromContext,
- getModelForLevel,
- isLocalPreferred,
- upgradeLevel,
- downgradeLevel,
- getStats,
- resetStats,
- updateThresholds,
- getLevels
-}
diff --git a/server/services/thinkingLevels.test.js b/server/services/thinkingLevels.test.js
deleted file mode 100644
index 6c0f6bd970..0000000000
--- a/server/services/thinkingLevels.test.js
+++ /dev/null
@@ -1,390 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import {
- THINKING_LEVELS,
- AUTO_THRESHOLDS,
- TASK_TYPE_LEVELS,
- resolveThinkingLevel,
- resolveStepEffort,
- suggestLevel,
- suggestLevelFromContext,
- getModelForLevel,
- isLocalPreferred,
- upgradeLevel,
- downgradeLevel,
- getStats,
- resetStats,
- getLevels
-} from './thinkingLevels.js';
-
-// Mock the cosEvents
-vi.mock('./cos.js', () => ({
- cosEvents: {
- emit: vi.fn()
- }
-}));
-
-describe('Thinking Levels Service', () => {
- beforeEach(() => {
- resetStats();
- });
-
- describe('THINKING_LEVELS', () => {
- it('should have all required levels', () => {
- expect(THINKING_LEVELS.off).toBeDefined();
- expect(THINKING_LEVELS.minimal).toBeDefined();
- expect(THINKING_LEVELS.low).toBeDefined();
- expect(THINKING_LEVELS.medium).toBeDefined();
- expect(THINKING_LEVELS.high).toBeDefined();
- expect(THINKING_LEVELS.xhigh).toBeDefined();
- });
-
- it('should have increasing maxTokens as level increases', () => {
- expect(THINKING_LEVELS.minimal.maxTokens).toBeLessThan(THINKING_LEVELS.low.maxTokens);
- expect(THINKING_LEVELS.low.maxTokens).toBeLessThan(THINKING_LEVELS.medium.maxTokens);
- expect(THINKING_LEVELS.medium.maxTokens).toBeLessThan(THINKING_LEVELS.high.maxTokens);
- expect(THINKING_LEVELS.high.maxTokens).toBeLessThan(THINKING_LEVELS.xhigh.maxTokens);
- });
-
- it('should mark minimal and low as localPreferred', () => {
- expect(THINKING_LEVELS.minimal.localPreferred).toBe(true);
- expect(THINKING_LEVELS.low.localPreferred).toBe(true);
- expect(THINKING_LEVELS.medium.localPreferred).toBe(false);
- });
- });
-
- describe('AUTO_THRESHOLDS', () => {
- it('should have contextLength thresholds', () => {
- expect(AUTO_THRESHOLDS.contextLength).toBeDefined();
- expect(AUTO_THRESHOLDS.contextLength.minimal).toBeDefined();
- expect(AUTO_THRESHOLDS.contextLength.xhigh).toBeDefined();
- });
-
- it('should have complexity thresholds', () => {
- expect(AUTO_THRESHOLDS.complexity).toBeDefined();
- expect(AUTO_THRESHOLDS.complexity.minimal).toBeLessThan(AUTO_THRESHOLDS.complexity.xhigh);
- });
- });
-
- describe('TASK_TYPE_LEVELS', () => {
- it('should map simple tasks to low levels', () => {
- expect(TASK_TYPE_LEVELS.format).toBe('minimal');
- expect(TASK_TYPE_LEVELS.typo).toBe('minimal');
- });
-
- it('should map complex tasks to high levels', () => {
- expect(TASK_TYPE_LEVELS.architect).toBe('xhigh');
- expect(TASK_TYPE_LEVELS.audit).toBe('xhigh');
- });
- });
-
- describe('resolveThinkingLevel', () => {
- it('should use task metadata thinkingLevel if present', () => {
- const task = { id: 'task-1', metadata: { thinkingLevel: 'high' } };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('high');
- expect(result.resolvedFrom).toBe('task');
- });
-
- it('should use priority for CRITICAL/URGENT tasks', () => {
- const task = { id: 'task-1', priority: 'CRITICAL' };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('high');
- expect(result.resolvedFrom).toBe('priority');
- });
-
- it('should use priority for LOW tasks', () => {
- const task = { id: 'task-1', priority: 'LOW' };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should use taskType mapping', () => {
- const task = { id: 'task-1', metadata: { taskType: 'architect' } };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('xhigh');
- });
-
- it('should use agent default if no task-level config', () => {
- const task = { id: 'task-1' };
- const agent = { defaultThinkingLevel: 'low' };
- const result = resolveThinkingLevel(task, agent);
-
- expect(result.level).toBe('low');
- expect(result.resolvedFrom).toBe('agent');
- });
-
- it('should use provider default as fallback', () => {
- const task = { id: 'task-1' };
- const provider = { defaultThinkingLevel: 'minimal' };
- const result = resolveThinkingLevel(task, {}, provider);
-
- expect(result.level).toBe('minimal');
- expect(result.resolvedFrom).toBe('provider');
- });
-
- it('should default to medium if nothing specified', () => {
- const task = { id: 'task-1' };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('medium');
- expect(result.resolvedFrom).toBe('default');
- });
-
- it('should fallback to medium for invalid levels', () => {
- const task = { id: 'task-1', metadata: { thinkingLevel: 'invalid-level' } };
- const result = resolveThinkingLevel(task);
-
- expect(result.level).toBe('medium');
- });
-
- it('should include level configuration in result', () => {
- const task = { id: 'task-1', metadata: { thinkingLevel: 'high' } };
- const result = resolveThinkingLevel(task);
-
- expect(result.model).toBe('provider-heavy');
- expect(result.maxTokens).toBe(8192);
- });
- });
-
- describe('suggestLevel', () => {
- it('should suggest higher levels for higher complexity', () => {
- const lowComplexity = suggestLevel({ complexity: 0.2 });
- const highComplexity = suggestLevel({ complexity: 0.9 });
-
- expect(['minimal', 'low'].includes(lowComplexity)).toBe(true);
- expect(['high', 'xhigh'].includes(highComplexity)).toBe(true);
- });
-
- it('should return minimal for very low complexity', () => {
- const result = suggestLevel({ complexity: 0.1 });
- expect(result).toBe('minimal');
- });
-
- it('should handle missing complexity', () => {
- const result = suggestLevel({});
- expect(result).toBeDefined();
- });
- });
-
- describe('suggestLevelFromContext', () => {
- it('should suggest minimal for short context', () => {
- const result = suggestLevelFromContext(100);
- expect(result).toBe('minimal');
- });
-
- it('should suggest higher levels for longer context', () => {
- const short = suggestLevelFromContext(500);
- const long = suggestLevelFromContext(10000);
-
- expect(['minimal', 'low'].includes(short)).toBe(true);
- expect(long).toBe('xhigh');
- });
- });
-
- describe('getModelForLevel', () => {
- it('should return lmstudio for local levels', () => {
- expect(getModelForLevel('minimal')).toBe('lmstudio');
- expect(getModelForLevel('low')).toBe('lmstudio');
- });
-
- it('should return provider default for medium', () => {
- const provider = { defaultModel: 'custom-model' };
- expect(getModelForLevel('medium', provider)).toBe('custom-model');
- });
-
- it('should return provider heavy for high', () => {
- const provider = { heavyModel: 'heavy-model' };
- expect(getModelForLevel('high', provider)).toBe('heavy-model');
- });
-
- it('should return provider heavy for xhigh', () => {
- const provider = { heavyModel: 'heavy-model', defaultModel: 'default-model' };
- expect(getModelForLevel('xhigh', provider)).toBe('heavy-model');
- });
-
- it('should fall back to defaultModel for xhigh when heavyModel is absent', () => {
- const provider = { defaultModel: 'default-model' };
- expect(getModelForLevel('xhigh', provider)).toBe('default-model');
- });
-
- it('should return null for xhigh when neither heavyModel nor defaultModel is configured', () => {
- const provider = {};
- expect(getModelForLevel('xhigh', provider)).toBeNull();
- });
-
- it('should return null for invalid level', () => {
- expect(getModelForLevel('invalid')).toBeNull();
- });
-
- it('should return provider default when level is off', () => {
- const provider = { defaultModel: 'default' };
- expect(getModelForLevel('off', provider)).toBe('default');
- });
-
- it('should return null when provider has no model configured', () => {
- const provider = { defaultModel: null };
- expect(getModelForLevel('medium', provider)).toBeNull();
- expect(getModelForLevel('high', provider)).toBeNull();
- expect(getModelForLevel('medium', {})).toBeNull();
- expect(getModelForLevel('high', {})).toBeNull();
- });
- });
-
- describe('isLocalPreferred', () => {
- it('should return true for minimal and low', () => {
- expect(isLocalPreferred('minimal')).toBe(true);
- expect(isLocalPreferred('low')).toBe(true);
- });
-
- it('should return false for medium and above', () => {
- expect(isLocalPreferred('medium')).toBe(false);
- expect(isLocalPreferred('high')).toBe(false);
- expect(isLocalPreferred('xhigh')).toBe(false);
- });
-
- it('should return false for invalid level', () => {
- expect(isLocalPreferred('invalid')).toBe(false);
- });
- });
-
- describe('upgradeLevel', () => {
- it('should upgrade to next level', () => {
- expect(upgradeLevel('minimal')).toBe('low');
- expect(upgradeLevel('low')).toBe('medium');
- expect(upgradeLevel('medium')).toBe('high');
- expect(upgradeLevel('high')).toBe('xhigh');
- });
-
- it('should not upgrade beyond xhigh', () => {
- expect(upgradeLevel('xhigh')).toBe('xhigh');
- });
-
- it('should return medium for invalid level', () => {
- expect(upgradeLevel('invalid')).toBe('medium');
- });
- });
-
- describe('downgradeLevel', () => {
- it('should downgrade to previous level', () => {
- expect(downgradeLevel('xhigh')).toBe('high');
- expect(downgradeLevel('high')).toBe('medium');
- expect(downgradeLevel('medium')).toBe('low');
- expect(downgradeLevel('low')).toBe('minimal');
- });
-
- it('should not downgrade below off', () => {
- expect(downgradeLevel('off')).toBe('off');
- });
-
- it('should return medium for invalid level', () => {
- expect(downgradeLevel('invalid')).toBe('medium');
- });
- });
-
- describe('getStats', () => {
- it('should return usage statistics', () => {
- resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'high' } });
- resolveThinkingLevel({ id: 't2', metadata: { thinkingLevel: 'high' } });
- resolveThinkingLevel({ id: 't3', metadata: { thinkingLevel: 'low' } });
-
- const stats = getStats();
-
- expect(stats.usage.high).toBe(2);
- expect(stats.usage.low).toBe(1);
- expect(stats.total).toBe(3);
- });
-
- it('should calculate distribution percentages', () => {
- resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'medium' } });
- resolveThinkingLevel({ id: 't2', metadata: { thinkingLevel: 'medium' } });
-
- const stats = getStats();
-
- expect(stats.distribution.medium).toBe('100.0%');
- });
-
- it('should return all levels', () => {
- const stats = getStats();
- expect(stats.levels).toContain('off');
- expect(stats.levels).toContain('xhigh');
- });
- });
-
- describe('resetStats', () => {
- it('should reset all usage counters to 0', () => {
- resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'high' } });
- resetStats();
-
- const stats = getStats();
- expect(stats.total).toBe(0);
- expect(stats.usage.high).toBe(0);
- });
- });
-
- describe('getLevels', () => {
- it('should return all level configurations', () => {
- const levels = getLevels();
-
- expect(levels.off).toBeDefined();
- expect(levels.xhigh).toBeDefined();
- expect(Object.keys(levels).length).toBe(6);
- });
-
- it('should return all level configurations', () => {
- const levels = getLevels();
-
- // Verify it returns a new object (shallow copy)
- const levels2 = getLevels();
- expect(levels).not.toBe(levels2); // Different object references
- expect(levels.off).toEqual(levels2.off); // Same content
- });
- });
-});
-
-describe('resolveStepEffort — per-delegated-step reasoning (#5992)', () => {
- const orchestrated = (profile) => ({
- metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: profile },
- });
-
- it('prefers the rung the architect wrote into the spec over the role default', () => {
- expect(resolveStepEffort({
- spec: 'OBJECTIVE: ship it\nREASONING: xhigh',
- task: orchestrated({ implementer: { effort: 'low' } }),
- role: 'implementer',
- runEffort: 'medium',
- })).toEqual({ effort: 'xhigh', source: 'spec' });
- });
-
- it('falls back to the role default, then the run effort, then nothing', () => {
- const task = orchestrated({ implementer: { effort: 'low' } });
- expect(resolveStepEffort({ task, role: 'implementer', runEffort: 'medium' }))
- .toEqual({ effort: 'low', source: 'role' });
- expect(resolveStepEffort({ task, role: 'reviewer', runEffort: 'medium' }))
- .toEqual({ effort: 'medium', source: 'run' });
- expect(resolveStepEffort({ task, role: 'reviewer' }))
- .toEqual({ effort: null, source: 'default' });
- });
-
- it('errors on an unsupported rung rather than downgrading it to a supported one', () => {
- const result = resolveStepEffort({
- spec: 'REASONING: galaxy-brain',
- task: orchestrated({ implementer: { effort: 'low' } }),
- role: 'implementer',
- runEffort: 'medium',
- });
- expect(result.error).toContain('galaxy-brain');
- expect(result.effort).toBeUndefined();
- });
-
- it('ignores a profile the task has not switched into orchestrated mode', () => {
- expect(resolveStepEffort({
- task: { metadata: { orchestrationProfile: { implementer: { effort: 'low' } } } },
- role: 'implementer',
- runEffort: 'medium',
- })).toEqual({ effort: 'medium', source: 'run' });
- });
-});