Skip to content

feat(#971): model escalation ladder on capability-bound non-convergence - #1012

Merged
admarble merged 11 commits into
mainfrom
feature/971-feat-run-model-escalation-ladder-on-capability-bou
Sep 8, 2026
Merged

admarble merged 11 commits into
mainfrom
feature/971-feat-run-model-escalation-ladder-on-capability-bou

Conversation

@admarble

@admarble admarble commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the model escalation ladder (#971, graph node 11): with run.modelLadder / --model-ladder configured, a phase that stalls with no progress is re-dispatched one rung up through the single shared resolver, sticks there, never skips or overflows, and records what it did. With no ladder, nothing changes.

The routing constraint is the whole point: escalation fires only on the deterministic no-progress signals (LOOP_NO_DIFF, SAME_SHA_NO_PROGRESS). Repeated QA failure at advancing SHAs is divergence-suspect and never escalates — a stronger model would only rediscover the contradiction more expensively.

Design decisions taken from the /spec open questions

OQ Decision
OQ-1 LOOP_NO_DIFF becomes continuable in the ready gate — but only when a ladder is configured, a rung remains, and iterations < maxIterations. Without this, AC-2's gate half is unreachable (there is no "next retry" to escalate). With no ladder the terminal is unchanged.
OQ-2 The run path produces the trigger itself: batch-executor snapshots each quality-loop iteration via an injectable snapshotProgressFn, only when a ladder is configured (AC-D2).
OQ-3 A --models pin that is not a ladder entry never escalates. Treating ladder[0] as "next" after an off-ladder pin would silently downgrade it — the inversion #915 and #971 both reject.
OQ-4 The marker-integrity guard is a pure predicate inside detectCapabilityBoundTrigger (missing/inconsistent marker ⇒ no trigger + a reason). doctor.ts has no phase-marker check to route through, so "reconciled through the doctor path" is restated as "no escalation occurs and the reason is recorded". Reconciliation stays reconcile.ts's job, unwired here.
OQ-5 Ladder entries resolve through resolveRoleToModel; raw strings stay legal. This node lands the schema fields, the pure field-builder, the round-trip test and the env threading (SEQUANT_MODEL_RUNG/_BASE/_ESCALATED/SEQUANT_ESCALATION_TRIGGER); #995 wires the skill prose that prints them.
OQ-6 Ladder applied at the 4th dispatch site. Backfilling #915's effort escalation there is deliberately not done — that would change #915's behaviour under a #971 PR.
OQ-7 run.modelLadder documented in the generated settings-reference table.

AC-5 is enforced structurally, not by convention. Both halves derive from one value: effectiveModelTrigger(lastTrigger, retryIndex) withholds the trigger until retry 2, and that single modelTrigger feeds both escalators — withEscalatedEffort(cfg, phase, isRetry && modelTrigger === null) then withEscalatedModel(cfg, phase, modelTrigger, state). "Effort first" holds because a withheld trigger leaves the effort bump enabled; "never both" holds because an active one disables it.

Post-QA fixes (loop iteration 1)

The first QA pass returned AC_NOT_MET on three findings. All three are fixed here.

1. AC-10: ready-gate escalations were recorded nowhere. ReadyResult.modelEscalations
was populated at both gate dispatch sites and had zero consumers, while #915's
identical effortEscalations channel is consumed in three places. Compounding it,
gate phase results never enter IssueResult.phaseResults (batch-executor.ts:893
returns them straight into the gate), and phaseUsage rows are built only from
phaseResults — so a rung the gate spent had nowhere to ride. Net effect:
sequant ready --model-ladder escalated the model, spent the money, recorded nothing.

Fixed by mirroring #915 exactly: a run-level MetricRun.modelEscalations log merged
from both paths in run-orchestrator.ts, verbose output for the gate path, and a
commands/ready.ts print (the only channel on the standalone gate, which writes no
run metrics at all). This is not the "second array" the scope note rules out —
that note governs the per-execution facts, which remain columns on the phaseUsage
row joined to the tokens that execution spent. This is the run-level log, and it
exists precisely because the gate path has no row to attach to.

2. CHANGELOG entry added under [Unreleased] → Added for the new
--model-ladder flag and run.modelLadder setting.

3. Mutation markers rewritten so they parse. AC-1's contained literal braces
inside a string value — breaking the {[^}]+} anchor, the same nested-brace
failure class AC-D1 exists to guard against — and four others put a -t selector
where classifyMutationMarker expects <file> > <test name>. All eight now
classify valid, and each resolves to exactly one real, passing test.

Also addressed from QA's non-blocking notes: the AC-5 assertion now keys on what
changed this dispatch rather than what is merely present (a sticky rung plus an
effort bump is AC-6 behaving correctly, and the old presence-based filter would
have flagged it), and the pr.escalatedModel → phaseUsage row join now has a
direct test.

One regression this surfaced: adding a required modelEscalations field to
ReadyResult broke two hand-built fixtures in ready.test.ts. Worth noting that
tsc --noEmit passed both before and after — TypeScript cannot prove completeness
across a ...Partial<T> spread, so only the runtime suite caught it.

Two broken verify commands (confirmed, as /spec flagged)

Both were green while asserting nothing. Re-ran on this branch:

  • AC-10's compat command. npx vitest run src/commands/stats.test.ts -t "986 AC-6" → Tests 25 skipped (25), EXIT 0. -t "986 AC-6" is not a substring of any test name. Corrected: -t "AC-6" → 1 passed | 24 skipped. ✅
  • AC-11's grep. grep -rn 'modelLadder' ready-gate.ts config-resolver.ts | grep -v import | wc -l prints one combined count over both files and can never be 0 — config-resolver.ts must mention it. Corrected per-file: grep -c 'modelLadder' src/lib/workflow/ready-gate.ts → 0. ✅ (config-resolver.ts → 7.)

AC verification

AC Status Evidence
AC-1 ✅ -t "971 AC-1" → 17 passed. CLI beats settings; with no ladder the key is absent (not undefined) on both producers, and withEscalatedModel returns the input config by reference (toBe, not just toEqual).
AC-2 ✅ -t "971 AC-2" → 11 passed. Driver-options assertion at the dispatch site on both paths: ready-gate (runReadyGate, real loop) → [undefined, "opus", "fable"]; run path (runIssueWithLogging, real quality loop) → same. Plus end-to-end into query() options.
AC-3 ✅ -t "971 AC-3" → 3 passed. 3 iterations, new SHA each, failing verdicts → model option constant on every dispatch, modelEscalations: [].
AC-5 ✅ -t "971 AC-5" → 5 passed. Retry 1 = effort only, retry 2 = model only, on both paths; the both-changed filter is empty. Includes a regression test that derives the trigger from a no-diff iteration 1 rather than hand-feeding it, and asserts the first effort bump precedes the first model rung.
AC-6 ✅ -t "971 AC-6" → 7 passed. Sticky across trigger-less dispatches, per-phase, index +1 exactly (["opus","fable","fable"]), top rung leaves the model unchanged and sets topOfLadder.
AC-7 ✅ -t "971 AC-7" → 5 passed. Pin sets the starting rung; off-ladder pin returns the config by reference and is explicitly asserted not to become ladder[0]; pin with no ladder never escalates.
AC-8 ✅ -t "971 AC-8" → 8 passed. Missing marker, no commitSHA, wrong phase, unparseable timestamp → no trigger + reason. The guard runs before the signals: a rigged marker suppresses a LOOP_NO_DIFF that would otherwise fire. Restated per OQ-4.
AC-10 ✅ -t "971 AC-10" → 24 passed. Rung/base/escalated/trigger/requestedModel as columns on #986's phaseUsage row for the run path, plus a run-level modelEscalations log so the ready-gate path (which produces no usage row) is auditable too — see the QA-fix note below. Old records still load: stats.test.ts -t "AC-6" ✅.
AC-11 ✅ execution-config-parity.test.ts ready-gate.phase-policy.test.ts -t "971" → 5 passed. grep -c 'modelLadder' ready-gate.ts → 0.
AC-13 ✅ -t "971 AC-13" → 2 passed. No production change needed — claude-code.ts:236 already converts subtype:"success" + is_error:true into success:false (landed with #973). Labelled a regression guard, and mutation-verified below.
AC-D1 ✅ Marker fields survive formatPhaseMarker → parsePhaseMarkers, and an escalated marker does not desync a sibling marker in the same body.
AC-D2 ✅ Unconfigured run calls the snapshot fn 0 times; configured run calls it once per iteration boundary.

Mutation verification

All eight records below were produced by mutating production code, running the
named test, observing the expected failure, and restoring. Every marker parses
as valid against this PR's diff (parseMutationMarkers), and every
failedTest resolves to exactly one real, passing test.

AC Mutation Test that failed Result
AC-1 resolveModelLadder returns an empty-array ladder key instead of omitting the keys model-ladder.test.ts — no-ladder-key assertion 2 failed + parity 1 failed
AC-2 reverted the OQ-1 continuation so LOOP_NO_DIFF is unconditionally terminal model-ladder.test.ts — gate re-dispatches one rung up 1 failed
AC-5 removed the effort-suppression at both gate dispatch sites model-ladder.test.ts — never both changing 1 failed
AC-5 (ordering) made effectiveModelTrigger return the trigger unconditionally, restoring the pre-fix behaviour where retry 1 escalates the model batch-executor.model-ladder.test.ts — effort rung before any model rung 1 failed
AC-10 stopped pushing qaLadder.record into ReadyResult.modelEscalations model-ladder.test.ts — gate carries every rung 1 failed
AC-11 buildPhaseConfig sets the inherited modelLadder to undefined execution-config-parity.test.ts — gate inherits the ladder 5 failed (grep gate also went 0 → 1)
AC-13 replaced the is_error guard in claude-code.ts with a constant false phase-executor.model-ladder.test.ts — #973 shape 1 failed
AC-D1 buildEscalationMarkerFields emits a nested object instead of flat scalars model-ladder.recording.test.ts — round-trip 3 failed
AC-D2 removed the ladderConfigured gate on the per-iteration snapshot batch-executor.model-ladder.test.ts — no snapshot when unconfigured 1 failed

AC-D1 caught a hole in its own test. On the first pass this mutation left
the recording suite green: the fixture was hand-written and laundered through
PhaseMarkerSchema.parse, which silently strips unknown keys, so a nested
payload could never reach formatPhaseMarker. Commit 972d0ff5 rebuilds the
fixture from the builder's raw output and replaces the schema-parse check with
an exact key-set assertion. Re-run after the fix: 3 tests fail.

Exec resume pass (2026-09-08)

Re-verified every gate independently rather than trusting the table above.
Build ✅, lint ✅, all 11 AC selectors ✅, all 9 SEQUANT_MUTATION markers parse
as valid and each failedTest resolves to exactly one real, passing test.

One defect found and fixed in this pass, plus one pre-existing one surfaced but
deliberately left alone.

Fixed — the run-path ladder tests spoofed the launcher's wire protocol.
batch-executor.model-ladder.test.ts drives the real quality loop, which
calls emitProgressLine. That writes SEQUANT_PROGRESS: lines to stderr
whenever SEQUANT_ORCHESTRATOR is set — true whenever the suite runs inside an
orchestrated sequant run phase. The file emitted 80 synthetic lines
labelled {"issue":971,...}. Those lines are not cosmetic: the launcher
prefix-matches them to drive the progress display and to reset the no-progress
watchdog, so a test run inside a live phase would report fabricated progress for
whatever run is actually in flight and suppress a watchdog that should have
fired. Fixed in 24d01210 with vi.stubEnv("SEQUANT_ORCHESTRATOR", ""), the
existing pattern from state-hook.test.ts. Emission is now 0 lines; 8/8 tests
still pass. The other three ladder test files were checked and emit nothing.

Surfaced, not fixed — batch-executor.test.ts has the same ambient-env bug,
and it belongs to #543.
withActivityHook (#543) > returns the input config unchanged when onProgress is undefined asserts toBe(baseConfig), but with
SEQUANT_ORCHESTRATOR set the config gains onActivity / onAutoWait and the
identity check fails:

$ npx vitest run src/lib/workflow/batch-executor.test.ts   # inside an orchestrated phase
  Tests  1 failed | 92 passed (93)
$ env -u SEQUANT_ORCHESTRATOR npx vitest run src/lib/workflow/batch-executor.test.ts
  Tests  93 passed (93)

Pre-existing on main, invisible in CI (which runs with the var unset), and
unrelated to the ladder — it is #543's test reading the ambient environment.
Left untouched on the same reasoning the spec's sibling-site scan used for
#915's missing 4th-site effort escalation: fixing it here would change another
issue's test under a #971 PR. Flagged for a follow-up.

CLI wiring check (#305 class)

New field CLI flag Registered Verified
RunOptions.modelLadder --model-ladder <rungs> run and ready (mirrors --escalate-effort's dual registration) sequant run --help and sequant ready --help both show it
ExecutionConfig.modelLadder / modelLadderRequested / modelEscalation N/A — Internal: resolved/set in-process, never user-facing

Test / build / lint

  • npm run build ✅ · npm run lint ✅ (0 warnings) · npm run lint:skill-calls ✅ (no violations)
  • Targeted suites: 221 passed across the 8 files this change touches.
  • Full unit project: 5080 passed, 1 failed — src/commands/__tests__/prompt-wait.test.ts, a relay timing flake. Confirmed pre-existing: reproduced identically on a clean worktree at base 0f278b40. Unrelated to this change.
  • One further environment artifact worth naming: batch-executor.test.ts's withActivityHook test reads process.env.SEQUANT_ORCHESTRATOR and therefore fails when the suite is run inside a sequant run phase. Green with the var unset; also pre-existing.

Deliberately out of scope (node 14 / #995)

Halts, the SPEC_DIVERGENCE escape hatch, verbose output, README/docs, and the rigged real run. topOfLadder is surfaced on both the record and the marker so #995 can act on it from either path. The verify-failure trigger stays out (OQ-4); semantic finding comparison and downgrades remain rejected.

Closes #971

🤖 Generated with Claude Code

…ows, and phase env

Entire-Checkpoint: 9ec1805f9d30
…ing round-trip

Entire-Checkpoint: dcf611ecc199
…marker payload

Entire-Checkpoint: 58abc53d2668
…latedModel

The comment inside the escalating branch said the dispatch was "not
topOfLadder yet", while the facts built ~25 lines below set
topOfLadder on exactly that dispatch. Both are deliberate and tested
(outcome flag = a trigger could not be honored; recorded facts = the
rung the phase now sits on), but the comment read as describing both.
State which of the two it governs. Comment only, no behavior change.

Entire-Checkpoint: 2ff83a43c286
AC-5 and the issue Design both specify an ordering: "effort escalation
remains the first rung (retry 1 -> effort +1 tier, same model). Model
escalation fires only on a subsequent capability-bound trigger (retry
>= 2 with no-progress stagnation)."

The dispatch sites gated the effort bump on `isRetry && trigger ===
null`, which satisfied AC-5's second half (never both on one iteration)
but violated its first: when iteration 1 produced no diff -- the
ladder's own primary scenario -- retry 1 escalated the model and the
effort rung was never spent at all. Because effort was suppressed by
exactly the trigger class that escalates the model, and AC-3 forbids
escalating on the other class, the two escalators were disjoint by
trigger rather than sequenced as rungs: the composition the issue
describes never occurred on a ladder-configured run, and the expensive
model was reached a full rung early.

Add `effectiveModelTrigger(trigger, retryIndex)` to model-ladder.ts,
which withholds the trigger until retry 2. Both dispatch paths derive
one `modelTrigger` from it and feed it to BOTH escalators, so AC-5's
halves stay structural: "effort first" because a withheld trigger
leaves the effort bump enabled, "never both" because an active one
disables it. Applied at all four dispatch sites; kept in model-ladder.ts
so the run path and ready gate cannot drift (AC-11).

Tests that encoded the old ordering are corrected, and the ready-gate
tests get a 4th iteration so they still cover the loop phase's record
and a second rung rather than stopping at the first.

Adds the regression test the QA gap named: it derives the trigger from
a no-diff iteration 1 instead of hand-feeding it, and asserts the first
effort bump precedes the first model rung. The previous AC-5 unit test
hand-fed the sequence and so assumed the property under test.

Entire-Checkpoint: 1d4af851317b
…ress lines

These tests drive the real quality loop, which calls emitProgressLine. That
writes SEQUANT_PROGRESS: lines to stderr whenever SEQUANT_ORCHESTRATOR is set,
which it is when the suite runs inside an orchestrated `sequant run` phase.
Those lines are the launcher's wire protocol — prefix-matched to drive the
progress display and reset the no-progress watchdog — so 80 synthetic lines for
issue 971 would spoof progress for whatever run is actually in flight.

Scrub the var per the existing pattern in state-hook.test.ts.

Entire-Checkpoint: e35b4b8e150a
@admarble
admarble merged commit 3400a1c into main Sep 8, 2026
6 checks passed
@admarble
admarble deleted the feature/971-feat-run-model-escalation-ladder-on-capability-bou branch September 8, 2026 08:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(run): model escalation ladder on capability-bound non-convergence

1 participant