Bring 60 `pydantic_clai2` functions under the cognitive complexity limit of 15
This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.
Why we make these changes
The cognitive complexity gate from #11117 allows 15 per function. 60 pydantic_clai2 functions scored over that on main, 1,336 points in total: menus, frames, key dispatch, renderers, and the web UI's history and event mapping. This PR brings each of them to 15 or under, with no change in behavior, as part of #10983. It does not close that issue: the 25 runtime and entry-point functions in pydantic_clai2 are the next PR.
Each function took the fix that agent_docs/complexity.md names for its shape:
- Dispatch on type or key (
ItemLog.apply,SessionView.apply,StreamRenderer.on_stream_event,ToolOutput.render,LivePrompt._route,SessionBrowser.handle_key,plugins_command,edit_chain):match, with the cases in the old order. - Part ladders (
history_entries,render_history): one function per message kind, each amatch part:.history_entrieskeeps its state on a data-only_HistoryEntriesContext. - Closure-hosted (
build_model_picker,WebService.projects,url_at): the nested functions became module functions, bound withpartialwhere an API takes a callback. - Presentation: one builder per row, card or frame, such as
SessionBrowser._session_card,_project_row,Splash._rowandLivePrompt._footer. - The rest: guard clauses, and a private method or module function next to its only caller.
New public surface
None. Every new function and method is private.
Verification
- Existing tests and inline snapshots pass unchanged: the 124
tests/clai2/files that reach a changed module, run locally, and again for the filesmainchanged since. No test file, snapshot or cassette changes. The browser tests intests/clai2/browser/run in CI. scripts/check_complexity.pypasses. Every function in the 37 changed files scores 15 or under; the 72 new private functions score 1 to 14.- CI's coverage gate does not measure
pydantic_clai2source ([tool.coverage.run]inpyproject.toml), so the tests above are the proof of reach.
Before and after scores: 1,336 → 655
| Function | File | Before | After |
|---|---|---|---|
SessionBrowser._sessions_frame | ui/menus/session_browser.py | 43 | 11 |
history_entries | builtin_plugins/web/protocol.py | 40 | 8 |
Commands.get_completions | commands.py | 37 | 11 |
_search_clai_docs | clai_docs.py | 32 | 10 |
build_model_picker | ui/menus/model_picker.py | 32 | 10 |
_file_calls | builtin_plugins/web/changes.py | 30 | 11 |
rewind_points | runtime/rewind.py | 30 | 14 |
StreamRenderer.on_stream_event | ui/rendering/rendering.py | 29 | 7 |
_modified_key | ui/prompt/prompt_keys.py | 28 | 3 |
QuestionMenu.choose | builtin_plugins/ask_user_menu.py | 27 | 11 |
WebService.projects | builtin_plugins/web/service.py | 27 | 13 |
_run_model_picker | ui/menus/model_picker.py | 26 | 15 |
Settings.validate_worktree_remove_commands | config/__init__.py | 25 | 7 |
_doc | clai_docs.py | 25 | 12 |
validate_model_options | models/model_options.py | 25 | 13 |
FolderMenu.run | builtin_plugins/coder_folders.py | 24 | 15 |
LivePrompt._route | ui/prompt/live_prompt.py | 24 | 11 |
PromptBuffer.rows | ui/prompt/prompt_buffer.py | 24 | 15 |
SessionBrowser.handle_key | ui/menus/session_browser.py | 24 | 10 |
ToolOutput.render | ui/rendering/tool_output.py | 24 | 7 |
open_add_model_menu | ui/menus/model_menu.py | 24 | 12 |
LivePrompt.frame | ui/prompt/live_prompt.py | 23 | 13 |
_run_menu | ui/menus/accounts_menu.py | 23 | 15 |
model_command | ui/menus/model_picker.py | 23 | 12 |
QuestionMenu.frame | builtin_plugins/ask_user_menu.py | 22 | 13 |
SessionView.apply | builtin_plugins/web/client.py | 22 | 14 |
_heredoc_language | ui/rendering/command_syntax.py | 22 | 6 |
FolderMenu.problem | builtin_plugins/coder_folders.py | 21 | 11 |
ItemLog.apply | builtin_plugins/web/protocol.py | 21 | 13 |
_edit_row | mcp/form.py | 21 | 12 |
_tool_changes | builtin_plugins/web/changes.py | 21 | 10 |
command_segments | ui/rendering/command_syntax.py | 21 | 15 |
render_history | ui/rendering/history.py | 21 | 6 |
confirmed | builtin_plugins/web/workspace_tools.py | 20 | 13 |
edit_chain | ui/menus/chain_menu.py | 20 | 15 |
LivePrompt.accept | ui/prompt/live_prompt.py | 19 | 11 |
ServerForm.toggle_oauth | mcp/form.py | 19 | 9 |
SessionPlugins._command | plugins/loader.py | 19 | 15 |
SessionPlugins.load_all | plugins/loader.py | 19 | 15 |
_parse_user_file | ui/rendering/spinners.py | 19 | 7 |
limit_response_retry_after | models/retry_after.py | 19 | 6 |
project_names | builtin_plugins/web/sidebar.py | 19 | 12 |
Splash.frame | ui/rendering/splash.py | 18 | 3 |
_read_clai_docs | clai_docs.py | 18 | 9 |
locate | builtin_plugins/aoe.py | 18 | 6 |
DirectoryPicker.run | builtin_plugins/coder_folders.py | 17 | 12 |
SessionBrowser._projects_frame | ui/menus/session_browser.py | 17 | 3 |
TranscriptBuffer.write | ui/prompt/prompt_transcript.py | 17 | 6 |
WebService.follow | builtin_plugins/web/service.py | 17 | 8 |
_before | builtin_plugins/web/changes.py | 17 | 12 |
error_message | errors.py | 17 | 15 |
plugins_command | commands.py | 17 | 10 |
spinner_command | ui/menus/spinner_picker.py | 17 | 13 |
HerdrClient._rename | builtin_plugins/herdr_client.py | 16 | 15 |
PromptBuffer.search_key | ui/prompt/prompt_buffer.py | 16 | 11 |
PromptKeys.dispatch | ui/prompt/prompt_keys.py | 16 | 10 |
SessionChannel.observe | builtin_plugins/web/channel.py | 16 | 14 |
_openai_options | models/model_options.py | 16 | 12 |
model_options | models/model_options.py | 16 | 12 |
url_at | ui/prompt/prompt_selection.py | 16 | 15 |
| Total | 1336 | 655 |
What changes for existing users
Nothing.
PR decisions
2026-11-03 · R2 scope re-scored on main 6b3df9a7b · iter -
- Decision: 58 of the 60 listed functions in scope; history_items (2) and build_rewind_menu (1) dropped; their successors history_entries (40) and rewind_points (30) reported to manager, not folded
- Why: dispatch: drop functions already under 15; report sibling sites before folding
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · history_entries folded in, rewind_points reported · iter -
- Decision: history_entries (40, web/protocol.py) is in scope; rewind_points (30, runtime/rewind.py) stays out and goes to the manager
- Why: dispatch: 'Every function in the changed files ends at 15 or under'; protocol.py changes for ItemLog::apply, runtime/rewind.py is not otherwise changed
- Source: https://github.com/pydantic/pydantic-ai/pull/12212
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · rewind_points folded into R2 · iter -
- Decision: rewind_points (runtime/rewind.py, 30) is in scope: 15 or under, behavior unchanged, covering tests unchanged
- Why: David via manager: its logic was R2's build_rewind_menu before #12220 moved it, and no other R-PR owns it
- Source: https://github.com/pydantic/pydantic-ai/pull/12220
- Session: a2fb556e-4bca-4014-814b-87c07b139126
- Supersedes: history_entries folded in, rewind_points reported
2026-11-03 · clai_docs snippet window bug left out · iter -
- Decision: Pre-existing, not fixed here: _snippet (was inline in _search_clai_docs) finds the offset in excerpt.lower() but slices excerpt; str.lower() can lengthen text ('İ'.lower() is 2 chars), shifting the window. Repro: a docs line 'İİİİ saved api keys ...' searched with 'keys' starts the window early by the number of expanded chars
- Why: David via manager: keep it out of R2, record the repro
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · TranscriptBuffer escape-split bug left out · iter -
- Decision: Pre-existing on main, not fixed here: TranscriptBuffer.write (now _trim_pending) recomputes cutoff after truncating an unclosed control over 4096 without re-aligning to escape boundaries. Repro: t = TranscriptBuffer(max_chars=10); t.write('aa\x1b[31m' + 'b'*7 + '\x1b]' + 'z'*5000) leaves t._pending == '31mbbbbbbb', showing literal '31m'
- Why: dispatch: a bug found goes to the manager with its repro, not folded in
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · clai2 source coverage is not gated in CI · iter -
- Decision: Reach proof for this PR is the existing tests passing, not CI's 100% gate: [tool.coverage.run] include omits src/pydantic_clai2 and ci.yml's coverage step reports only tests/clai2/* for clai2
- Why: dispatch assumed 'CI's 100% gate is the reach proof'; verified false for pydantic-clai2 source (pyproject.toml [tool.coverage.run], .github/workflows/ci.yml coverage report step)
- Source: https://github.com/pydantic/pydantic-ai/blob/main/.github/workflows/ci.yml
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · ItemLog.apply ends in assert_never · iter -
- Decision: match over ItemMessage ends in case _: assert_never(message); pyright proves the cases exhaustive
- Why: repo rule: prefer exhaustive match with assert_never in the last branch; the old final else was the SubCall* arm
- Source: https://github.com/pydantic/pydantic-ai/blob/main/agent_docs/complexity.md#dispatch-on-type
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · render_history turns=0 IndexError left out · iter -
- Decision: Pre-existing on main, not fixed here: render_history(messages, turns=0) indexes starts[hidden] with hidden == len(starts) and raises IndexError once history has a turn start. Repro: await render_history([ModelRequest(parts=[UserPromptPart('hi')])], console=c, renderer=r, turns=0). Latent: the one caller (runtime/session_runtime.py) passes the default 10
- Why: dispatch: a bug found goes to the manager with its repro, not folded in
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · first-run test failures were load timeouts · iter -
- Decision: 9 nodes failed in the first serial run (7 MCP server start/connect, 2 subprocess timeouts); all 9 passed on rerun with unchanged code at load ~9
- Why: first run hit load ~22 with 0.1 GB free; none reached an assertion on refactored output; test_edit_restarts_a_running_server runs _edit_json, which this PR does not change
- Source: https://github.com/pydantic/pydantic-ai/tree/clai2-complexity
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 1 of 3 at 4eba5ebd530033916812ef0a4d1e1d02300bba6f · iter -
- Decision: reserved; outcome pending
- Why: tree 13aee8bbb01b705bbada41895195901eb8f17646; scope 7ecaafa56..4eba5ebd5 (full branch); first review; light tier (haiku) per Model tiers
- Source: https://github.com/pydantic/pydantic-ai/tree/clai2-complexity
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 1 of 3 at 4eba5ebd530033916812ef0a4d1e1d02300bba6f · iter -
- Decision: remediated: _CELLS module constant moved into PromptBuffer.rows (single-usage-site rule). Dismissed: (1) drop 'case _: pass' arms: strict pyright fails reportMatchNotExhaustive without them, verified on a probe copy, and each arm is the pre-existing fall-through of the old if/elif chain; (3) rename _HistoryEntriesContext: '*Context' is the data-only context convention of agent_docs/complexity.md part-ladder and OpenAIChatModel._MapModelResponseContext, not confusable with CommandContext; (4) range() in _projects_frame: diverges from rows[start : start + budget - 1] for a negative stop, which a slice counts from the end; enumerate keeps the slice exactly
- Why: tree 13aee8bbb01b705bbada41895195901eb8f17646; scope 7ecaafa56..4eba5ebd5 full branch; reviewer found no behavior change
- Source: https://github.com/pydantic/pydantic-ai/tree/clai2-complexity
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 2 of 3 at 034e7071dec465f5961f2aba8038322a43e4cd53 · iter -
- Decision: reserved; outcome pending
- Why: tree 5629ab29a3110bee125b55d8350c3970b3b3424c; follow-up scope 4eba5ebd5..034e7071d (review 1's _CELLS fix), prior findings to verify; light tier (haiku)
- Source: https://github.com/pydantic/pydantic-ai/tree/clai2-complexity
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 2 of 3 at 034e7071dec465f5961f2aba8038322a43e4cd53 · iter -
- Decision: no in-scope findings: _CELLS fix verified, all three dismissals accepted. Dismissed: move _MOVES, UNDO_KEYS, REDO_KEYS into PromptBuffer.edit: pre-existing on main and untouched by this PR (the _CELLS fix applied to a constant this PR added); rule 409 keeps the change to its purpose
- Why: tree 5629ab29a3110bee125b55d8350c3970b3b3424c; follow-up scope 4eba5ebd5..034e7071d
- Source: https://github.com/pydantic/pydantic-ai/tree/clai2-complexity
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 3 of 3 at 21484d0cc6a01197f1a1891fa2c7c083bbb0289f · iter -
- Decision: reserved; outcome pending
- Why: tree 2e0efed882fb899c84d43a9c69c8a1d605fa38e7; follow-up scope 034e7071d..21484d0cc (douwebot's optional _returned_calls comment); last review in the budget; light tier (haiku)
- Source: https://github.com/pydantic/pydantic-ai/pull/12354#discussion_r4456740472
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pre-push review 3 of 3 at 21484d0cc6a01197f1a1891fa2c7c083bbb0289f · iter -
- Decision: remediated: _returned_calls tests membership in the condition and pops in the body, so the mutation is visible; douwebot's comment verified fixed. Budget exhausted: no fourth review; local checks only
- Why: tree 2e0efed882fb899c84d43a9c69c8a1d605fa38e7; follow-up scope 034e7071d..21484d0cc; pending values are _FileCall, never None, so membership-then-pop equals pop(..., None) is not None
- Source: https://github.com/pydantic/pydantic-ai/pull/12354#discussion_r4456740472
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · second review surface: pydanty:review-lite · iter -
- Decision: David picked pydanty:review-lite for #12354 on head 8266e94fb, after the merge bar was met
- Why: author's choice of the additional review surface (pushing-commits-to-the-repo: 'choose an additional review surface'); recommendation offered was none
- Source: https://github.com/pydantic/pydantic-ai/pull/12354
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · metadata check 1 at 8266e94fb · iter -
- Decision: kept: title drops 'presentation' (validate_model_options, limit_response_retry_after, Settings.validate_worktree_remove_commands, rewind_points are not presentation code); applied after the pydanty run. Dropped: remove chore (added by github-actions[bot]; skill: 'Preserve size, priority, review, and automation labels'); blob-link proving tests (skill scopes that order to 'a feature or behavior change'; no test file changed; matches #12303)
- Why: light-tier metadata subagent from policy-base 5cb3386c4; each correction verified against the cited rule
- Source: https://github.com/pydantic/pydantic-ai/pull/12354
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pydanty finding 2: no openai:gpt-6 pin added · iter -
- Decision: Skip, a deliberate scope boundary: no test case for the family-defaults cell on the Responses flavor in this PR
- Why: David via manager: differential of model_options main vs branch over 903 model ids shows 0 differences (openai:gpt-6 keeps openai_reasoning_mode and the 3-choice context); the cell is unpinned on main too; R2 keeps test files unchanged by design
- Source: https://github.com/pydantic/pydantic-ai/pull/12354#issuecomment-6608985352
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · pydanty review-lite close-out · iter -
- Decision: Finding 1 done by evidence (CI run 41666064349 full clai2 suite green on 8266e94fb); finding 2 skipped as scope boundary; optional 2 answered with the same CI run; reply issuecomment-6610559433, 👍 on the findings comment, left visible as pydanty's newest beacon. Dismissing pydanty's CHANGES_REQUESTED (review 5756226540) with dismiss-addressed-bot-review was denied by the auto-mode classifier; pending a maintainer
- Why: pr-review-feedback close-out; skill: dismiss a fully addressed bot REQUEST_CHANGES with the tracked helper
- Source: https://github.com/pydantic/pydantic-ai/pull/12354#issuecomment-6610559433
- Session: a2fb556e-4bca-4014-814b-87c07b139126
2026-11-03 · metadata check 2 at 8266e94fb · iter -
- Decision: Title and body pass. Dropped: add web-ui and cli (no catalog description scopes either; #12212, #12215, #12218, #12220, #12232, all pkg:clai2 web-UI changes, carry neither; the PR's subject is code structure, named by refactor and pkg:clai2)
- Why: light-tier metadata subagent from policy-base 88672d7b8; each correction verified against the cited rule
- Source: https://github.com/pydantic/pydantic-ai/pull/12354
- Session: a2fb556e-4bca-4014-814b-87c07b139126
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
Summary by cubic
Brings 60 pydantic_clai2 functions under the 15-point cognitive complexity gate, cutting their combined score from 1,336 to 655 with no change in behavior. All new functions are private — there's no new public surface — and the 25 runtime and entry-point functions still over the gate are left to a follow-up PR for #10983.
Refactors
- Dispatch functions now use
matchwith cases in the original order. - Part-processing functions split into one function per message part kind; returned file calls are now collected in a loop, not a mutating comprehension.
- Nested closures became module functions bound with
partialwhere an API takes a callback. - Presentation components use one builder per row, card, or frame; the rest use guard clauses with helpers next to their single caller.
Existing tests, snapshots, and cassettes pass unchanged, and scripts/check_complexity.py reports every changed function at 15 or under.