feat(#3024): dynamic routing with failure-tier escalation (#3031)

* feat(#3024): dynamic routing with failure-tier escalation

Adds a `dynamic_routing` block to .planning/config.json that lets
the resolver start agents on a cheap tier and escalate one tier up
when the orchestrator detects a soft failure (verification
inconclusive, plan-check FLAG, etc.). Solves the "pay Opus rates as
insurance" anti-pattern by making escalation observed-quality-driven.

Architecture:
- AGENT_DEFAULT_TIERS map (light/standard/heavy) — every agent in
  MODEL_PROFILES declares a default tier; tests assert coverage
  so adding a new agent without updating the map fails CI.
- nextTier(currentTier) helper — light → standard → heavy → heavy
  (heavy stays at heavy; can't go further).
- resolveModelForTier(cwd, agentType, attempt) — new resolver. The
  orchestrator tracks the attempt counter and passes 0 for the
  first spawn, 1+ on escalation. The resolver caps internally at
  max_escalations so the orchestrator can blindly bump the counter.
- Schema validation: dynamic_routing.enabled / escalate_on_failure /
  max_escalations / tier_models.<light|standard|heavy>. Unknown
  tiers and unknown sub-keys rejected at config-set time.
- SDK schema mirror updated to keep CJS/SDK in lockstep (#2653).

Resolution precedence (highest → lowest):
  1. model_overrides[<agent>]              (full IDs accepted)
  2. dynamic_routing.tier_models[<tier>]   (NEW; escalation-aware)
  3. models[<phase_type>]                  (#3023 phase-type map)
  4. model_profile                         (per-agent column)
  5. Runtime default

Backward compatibility: dynamic_routing is disabled by default
(enabled: false or block omitted). resolveModelForTier short-
circuits to resolveModelInternal in that case, so callers can
adopt unconditionally without breaking existing behavior.

This PR delivers the JS-layer infrastructure: schema + tier map +
resolver. Orchestrator adoption (workflow markdown updates that
detect soft failures and call resolveModelForTier with attempt+1)
is incremental follow-up — verifier / plan-checker / integration-
checker each adopt the protocol when ready.

Tests (23 cases, all structural-IR — no stdout grep):
- Schema invariants: AGENT_DEFAULT_TIERS coverage, VALID_AGENT_TIERS
  exact match, every assignment uses a valid tier
- nextTier helper: light→standard→heavy→heavy, null on invalid input
- Disabled mode: no block + enabled:false both no-op (back-compat)
- Enabled mode: attempt=0 returns default tier model, attempt=1
  escalates, beyond max_escalations caps, heavy agents stay heavy,
  default max_escalations=1 when omitted
- Precedence: per-agent override beats dynamic_routing,
  dynamic_routing beats phase-type models
- Validation: every settings key accepted, unknown tiers/sub-keys
  rejected, bare `dynamic_routing` rejected as config-set target

Documentation:
- get-shit-done/references/model-profiles.md — full reference section
- docs/CONFIGURATION.md — full settings table + escalation flow
- docs/USER-GUIDE.md — task-oriented "Cheap-by-default" section
- docs/FEATURES.md — config row cross-link

Verification:
- 23/23 pass on regression test
- 6843/6843 full suite (23 net new from 6820)
- lint-no-source-grep clean (376 test files)
- SDK schema mirror keeps CJS/SDK in sync per #2653 parity test

Closes #3024

* fix(#3024): honor escalate_on_failure:false + 3 CR follow-ups

CodeRabbit on PR #3031 (4 findings — 1 Major + 2 Minor + 1 Nitpick):

1. **Major (inline)** — get-shit-done/bin/lib/core.cjs:1668
   resolveModelForTier ignored dynamic_routing.escalate_on_failure.
   When the user set it to false, escalation should be disabled, but
   the resolver only checked attempt/max_escalations. An orchestrator
   that always passes attempt+1 on retry would silently escalate
   despite the user opting out.
   Fix: gate effectiveAttempt on `dr.escalate_on_failure !== false`
   so false short-circuits every attempt back to the default tier.

2. **Minor (inline)** — docs/CONFIGURATION.md:123-126
   The dynamic_routing rows in the Core Settings table had 4 cells
   instead of 5 (missing the Options column), breaking the table
   structure. Added explicit Options values for enabled / escalate_on_failure
   / max_escalations rows.

3. **Minor (outside-diff)** — references/model-profiles.md:179-195
   "Resolution Logic" sketch was pre-#3024 and didn't include
   dynamic_routing in the precedence ladder. Updated to a 6-step
   block with dynamic_routing at step 3 (between override and
   phase-type).

4. **Nitpick** — tests/feat-3024-dynamic-routing.test.cjs:189+
   Tests used `if (lightAgent) { ... }` guards that silent-pass
   when AGENT_DEFAULT_TIERS drifts. Replaced all 5 conditional
   skips with `assert.ok(lightAgent, '...')` preconditions so a
   tier-mapping change surfaces as a test failure.

Plus: 2 new regression tests for the Major fix:
- escalate_on_failure:false caps every attempt at default tier
- escalate_on_failure:true (explicit) still escalates normally

Verification:
- 25/25 pass on regression test (23 prior + 2 escalate_on_failure)
- 6845/6845 full suite (2 net new)
- lint-no-source-grep clean

* docs(#3024): align precedence + add fence language tags (CR follow-up)

CodeRabbit (3 minor):

1. docs/CONFIGURATION.md:691 — "Per-Phase-Type Models → Resolution
   precedence" was a 4-step block written pre-#3024; readers got
   contradictory rules between the per-phase-type section and the
   later dynamic_routing section. Updated to the same 5-step ladder
   with dynamic_routing at step 2, and noted that dynamic_routing
   is disabled by default so this section's behavior is unchanged
   when the kill-switch is off.

2. docs/CONFIGURATION.md:770 — escalation-flow code fence missing
   language tag (MD040). Added `text`.

3. references/model-profiles.md:184 — resolution-ladder code fence
   missing language tag (MD040). Added `text`.

No code changes; docs only. Verification: regression test still 25/25.

* docs(#3024): clarify precedence prose — five layers, not four (CR nitpick)

CodeRabbit nitpick: the "Per-Phase-Type Models → Resolution
precedence" prose said "The four layers compose..." but the ladder
above lists five (including Runtime default). Also "dynamic_routing
escalates per-attempt above all of them" misreads as suggesting
dynamic_routing wins over model_overrides — actually overrides still
win at step 1.

Reworded top-down so the precedence direction is unambiguous:
  - model_profile = base
  - models = phase-level override
  - dynamic_routing = per-attempt escalation
  - model_overrides = per-agent exception (top)
  - runtime default = fallback

No code changes; docs only.

* docs(#3024): note escalate_on_failure:false in escalation-flow diagram (CR)

CodeRabbit nitpick: the escalation-flow diagram in
docs/CONFIGURATION.md described the soft-failure → respawn →
tier_models[next_tier_up] path, but didn't surface the
`dynamic_routing.escalate_on_failure: false` kill-switch right next
to it. Users reading the flow diagram (which is the canonical place
to understand attempt behavior) wouldn't see that the kill-switch
overrides the soft-failure branch.

Added a one-paragraph note immediately after the flow listing,
before the tier-sequence example, so the kill-switch is visible
exactly where users decide whether escalation will happen.

No code changes; docs only.
This commit is contained in:
Tom Boucher
2026-05-02 14:26:35 -04:00
committed by GitHub
parent d812c66020
commit e1d661ece0
10 changed files with 717 additions and 14 deletions

View File

@@ -90,6 +90,11 @@ const DYNAMIC_KEY_PATTERNS = [
// precedence over phase-type at resolve time.
{ topLevel: 'models', test: (k) => /^models\.(planning|discuss|research|execution|verification|completion)$/.test(k),
description: 'models.<planning|discuss|research|execution|verification|completion>' },
// #3024 — dynamic routing block. Three top-level scalar settings
// plus a tier_models sub-block keyed by light/standard/heavy.
{ topLevel: 'dynamic_routing',
test: (k) => /^dynamic_routing\.(enabled|escalate_on_failure|max_escalations|tier_models\.(light|standard|heavy))$/.test(k),
description: 'dynamic_routing.<enabled|escalate_on_failure|max_escalations|tier_models.<light|standard|heavy>>' },
];
/**

View File

@@ -6,7 +6,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
const { execSync, execFileSync, spawnSync } = require('child_process');
const { MODEL_PROFILES, AGENT_TO_PHASE_TYPE, VALID_PHASE_TYPES } = require('./model-profiles.cjs');
const { MODEL_PROFILES, AGENT_TO_PHASE_TYPE, VALID_PHASE_TYPES, AGENT_DEFAULT_TIERS, VALID_AGENT_TIERS, nextTier } = require('./model-profiles.cjs');
// Compatibility shim: new imports should use planning-workspace.cjs directly.
const {
planningDir,
@@ -506,6 +506,11 @@ function loadConfig(cwd) {
// resolveModelInternal. Defaults to null so configs without it
// behave exactly as today.
models: parsed.models || null,
// #3024 — dynamic routing block. When `enabled: true`, the
// resolveModelForTier() resolver picks tier_models[default_tier]
// for the agent and escalates one tier per attempt up to
// max_escalations. Disabled by default for backward compat.
dynamic_routing: parsed.dynamic_routing || null,
// #2517 — runtime-aware profiles. `runtime` defaults to null (back-compat).
// When null, resolveModelInternal preserves today's Claude-native behavior.
// NOTE: `runtime` and `model_profile_overrides` are intentionally read
@@ -567,6 +572,7 @@ function loadConfig(cwd) {
subagent_timeout: globalDefaults.subagent_timeout ?? defaults.subagent_timeout,
model_overrides: globalDefaults.model_overrides || null,
models: globalDefaults.models || null,
dynamic_routing: globalDefaults.dynamic_routing || null,
agent_skills: globalDefaults.agent_skills || {},
response_language: globalDefaults.response_language || null,
};
@@ -1599,6 +1605,94 @@ function resolveModelInternal(cwd, agentType) {
return alias;
}
/**
* #3024 — Resolve a model for a specific dynamic-routing attempt.
*
* The orchestrator (workflow agent) tracks the attempt counter. On
* the first spawn, it calls with attempt=0. If the orchestrator detects
* a soft failure (verification inconclusive, plan-check FLAG, etc.),
* it re-spawns with attempt=1, which escalates the agent's tier one
* step up. `max_escalations` caps how many escalations are allowed.
*
* Resolution precedence (highest → lowest):
* 1. config.model_overrides[agent] (full IDs accepted)
* 2. dynamic_routing.tier_models[escalated_tier] (when enabled)
* 3. models[phase_type] / model_profile (existing chain via
* resolveModelInternal)
*
* When dynamic_routing is null/disabled, this function is identical
* to resolveModelInternal — orchestrators can call it unconditionally
* without breaking back-compat.
*
* @param {string} cwd - Project directory.
* @param {string} agentType - Agent name (e.g. 'gsd-verifier').
* @param {number} [attempt=0] - 0 for first spawn; 1+ for escalation.
* Capped internally at max_escalations.
* @returns {string} Model alias (opus/sonnet/haiku) or full ID.
*/
function resolveModelForTier(cwd, agentType, attempt) {
const config = loadConfig(cwd);
const attemptN = Number.isInteger(attempt) && attempt > 0 ? attempt : 0;
// Per-agent override always wins — same as resolveModelInternal step 1.
// User-supplied full IDs bypass the entire tier mechanism.
const override = config.model_overrides?.[agentType];
if (override) return override;
const dr = config.dynamic_routing;
// Disabled / missing / non-object → fall back to the existing resolver.
if (!dr || typeof dr !== 'object' || dr.enabled !== true) {
return resolveModelInternal(cwd, agentType);
}
const tierModels = dr.tier_models;
if (!tierModels || typeof tierModels !== 'object') {
// tier_models missing — can't dynamic-route; fall back.
return resolveModelInternal(cwd, agentType);
}
const defaultTier = AGENT_DEFAULT_TIERS[agentType];
if (!defaultTier || !VALID_AGENT_TIERS.has(defaultTier)) {
// Unmapped agent — no default tier; fall back so we don't silently
// pick the wrong model.
return resolveModelInternal(cwd, agentType);
}
// Cap effective escalation at max_escalations (default 1). Beyond
// the cap, the resolver returns the model for the cap level so the
// orchestrator can log "max escalations reached" without burning
// further budget.
//
// CR Major (#3031): `escalate_on_failure: false` is the kill-switch
// for escalation — when false, every attempt resolves to the default
// tier regardless of the attempt counter. Without this guard, an
// orchestrator that blindly bumps the counter on retry would silently
// escalate even though the user opted out.
const maxEscalations = Number.isInteger(dr.max_escalations) && dr.max_escalations >= 0
? dr.max_escalations
: 1;
const escalationEnabled = dr.escalate_on_failure !== false;
const effectiveAttempt = escalationEnabled
? Math.min(attemptN, maxEscalations)
: 0;
// Walk the escalation chain N times from the default tier.
let tier = defaultTier;
for (let i = 0; i < effectiveAttempt; i += 1) {
const next = nextTier(tier);
if (!next || next === tier) break; // already at top
tier = next;
}
const alias = tierModels[tier];
if (typeof alias !== 'string' || alias.length === 0) {
// Misconfigured tier_models — missing slot. Fall back rather
// than emit an empty model id.
return resolveModelInternal(cwd, agentType);
}
return alias;
}
/**
* #2517 — Resolve runtime-specific reasoning_effort for an agent.
* Returns null unless:
@@ -1959,6 +2053,7 @@ module.exports = {
getArchivedPhaseDirs,
getRoadmapPhaseInternal,
resolveModelInternal,
resolveModelForTier,
resolveReasoningEffortInternal,
RUNTIME_PROFILE_MAP,
RUNTIMES_WITH_REASONING_EFFORT,

View File

@@ -83,6 +83,66 @@ const VALID_PHASE_TYPES = new Set([
'planning', 'discuss', 'research', 'execution', 'verification', 'completion',
]);
/**
* #3024 — Per-agent default tier for dynamic routing.
*
* Each agent declares a default routing tier (light/standard/heavy)
* that the dynamic-routing resolver uses to pick from
* `dynamic_routing.tier_models[tier]` on the first attempt. On
* orchestrator-detected soft failure, the resolver escalates to the
* next tier up (capped at `max_escalations`).
*
* Tier semantics:
* - light: cheap/fast — pure mappers/scanners, low-stakes verifiers
* - standard: default workhorse — most researchers/writers/checkers
* - heavy: deep reasoning — planners/debuggers; can't escalate further
*
* Adding a new agent to MODEL_PROFILES requires adding an entry here too;
* tests/feat-3024-dynamic-routing.test.cjs asserts coverage.
*/
const AGENT_DEFAULT_TIERS = {
// Heavy — deep reasoning, planning, hard debugging
'gsd-planner': 'heavy',
'gsd-roadmapper': 'heavy',
'gsd-debugger': 'heavy',
// Standard — default workhorse: research, writing, primary verification
'gsd-executor': 'standard',
'gsd-phase-researcher': 'standard',
'gsd-project-researcher': 'standard',
'gsd-verifier': 'standard',
'gsd-doc-writer': 'standard',
'gsd-ui-researcher': 'standard',
// Light — fast scanners, structural mappers, low-stakes audits
'gsd-codebase-mapper': 'light',
'gsd-pattern-mapper': 'light',
'gsd-research-synthesizer': 'light',
'gsd-plan-checker': 'light',
'gsd-integration-checker': 'light',
'gsd-nyquist-auditor': 'light',
'gsd-ui-checker': 'light',
'gsd-ui-auditor': 'light',
'gsd-doc-verifier': 'light',
};
/**
* The three valid agent tier slots for dynamic routing. Used to
* validate `dynamic_routing.tier_models.<tier>` keys at config-set
* time and the AGENT_DEFAULT_TIERS values at startup.
*/
const VALID_AGENT_TIERS = new Set(['light', 'standard', 'heavy']);
/**
* Tier escalation order: light → standard → heavy.
* `nextTier(currentTier)` returns the tier one step up. `heavy` stays
* at heavy (no tier above). Returns null for invalid input so callers
* can detect mis-config rather than silently degrade.
*/
const _TIER_ESCALATION = { light: 'standard', standard: 'heavy', heavy: 'heavy' };
function nextTier(currentTier) {
if (typeof currentTier !== 'string') return null;
return _TIER_ESCALATION[currentTier] || null;
}
/**
* Formats the agent-to-model mapping as a human-readable table (in string format).
*
@@ -125,6 +185,9 @@ module.exports = {
VALID_PROFILES,
AGENT_TO_PHASE_TYPE,
VALID_PHASE_TYPES,
AGENT_DEFAULT_TIERS,
VALID_AGENT_TIERS,
nextTier,
formatAgentToModelMapAsTable,
getAgentToModelMapForProfile,
};

View File

@@ -133,22 +133,69 @@ If you're using Claude Code with OpenRouter, a local model, or any non-Anthropic
Without `inherit`, GSD's default `balanced` profile spawns specific Anthropic models (`opus`, `sonnet`, `haiku`) for each agent type, which can result in additional API costs through your non-Anthropic provider.
## Dynamic Routing with Failure-Tier Escalation (#3024)
When `dynamic_routing.enabled = true` in `.planning/config.json`, the resolver picks a model from a tier-mapped table based on the agent's *default tier* (light / standard / heavy) and escalates to the next tier up on orchestrator-detected soft failure.
```json
{
"dynamic_routing": {
"enabled": true,
"tier_models": {
"light": "haiku",
"standard": "sonnet",
"heavy": "opus"
},
"escalate_on_failure": true,
"max_escalations": 1
}
}
```
**Agent default tiers** (each agent in `MODEL_PROFILES` declares one):
| Tier | Agents | Use case |
|---|---|---|
| `light` | gsd-codebase-mapper, gsd-pattern-mapper, gsd-research-synthesizer, gsd-plan-checker, gsd-integration-checker, gsd-nyquist-auditor, gsd-ui-checker, gsd-ui-auditor, gsd-doc-verifier | Cheap/fast — pure mappers, scanners, low-stakes audits |
| `standard` | gsd-executor, gsd-phase-researcher, gsd-project-researcher, gsd-verifier, gsd-doc-writer, gsd-ui-researcher | Default workhorse — research, writing, primary verification |
| `heavy` | gsd-planner, gsd-roadmapper, gsd-debugger | Deep reasoning — already at top, can't escalate further |
**Escalation flow** (orchestrator-driven):
1. Orchestrator spawns agent with `attempt: 0` → resolver returns `tier_models[default_tier]`
2. If orchestrator marks the result a soft failure, it re-spawns with `attempt: 1` → resolver returns `tier_models[next_tier_up]`
3. `max_escalations` caps total retries (default 1). Beyond the cap the resolver returns the cap-tier model so the orchestrator can log without burning further budget.
4. Hard failures (exceptions) bypass escalation and surface immediately.
**Precedence with other tier sources** (highest → lowest):
1. `model_overrides[<agent>]` — full ID, always wins
2. `dynamic_routing.tier_models[escalated_tier]` — when `enabled: true`
3. `models[<phase_type>]` — coarse phase-level (#3023)
4. `model_profile` — global tier strategy
When `dynamic_routing.enabled = false` (default), behavior is identical to today.
## Resolution Logic
Orchestrators resolve model before spawning:
Orchestrators resolve model before spawning. The full precedence ladder
is (highest → lowest):
```
```text
1. Read .planning/config.json
2. Check model_overrides for agent-specific override
3. If no override, check models[phase_type] for a phase-type tier
2. Check model_overrides[<agent>] (full IDs accepted; targeted exceptions)
3. If dynamic_routing.enabled, return tier_models[escalated_tier]
(see §Dynamic Routing — escalation steps tier up per attempt counter)
4. If no dynamic_routing match, check models[phase_type] for a phase-type tier
(see §Per-Phase-Type Model Map for the agent → phase-type mapping)
4. If no phase-type slot, look up agent in profile table
5. Pass model parameter to Task call
5. If no phase-type slot, look up agent in profile table
6. Pass model parameter to Task call
```
The same precedence applies to `reasoning_effort` resolution on runtimes
that support it (Codex), so `model` and `reasoning_effort` always derive
from the same tier source — a `models[phase_type]` override flips both.
from the same tier source — a `models[phase_type]` or
`dynamic_routing` override flips both.
## Per-Agent Overrides