Bring 60 `pydantic_clai2` functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+1246-887

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 a match part:. history_entries keeps its state on a data-only _HistoryEntriesContext.
  • Closure-hosted (build_model_picker, WebService.projects, url_at): the nested functions became module functions, bound with partial where an API takes a callback.
  • Presentation: one builder per row, card or frame, such as SessionBrowser._session_card, _project_row, Splash._row and LivePrompt._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 files main changed since. No test file, snapshot or cassette changes. The browser tests in tests/clai2/browser/ run in CI.
  • scripts/check_complexity.py passes. 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_clai2 source ([tool.coverage.run] in pyproject.toml), so the tests above are the proof of reach.
Before and after scores: 1,336 → 655
FunctionFileBeforeAfter
SessionBrowser._sessions_frameui/menus/session_browser.py4311
history_entriesbuiltin_plugins/web/protocol.py408
Commands.get_completionscommands.py3711
_search_clai_docsclai_docs.py3210
build_model_pickerui/menus/model_picker.py3210
_file_callsbuiltin_plugins/web/changes.py3011
rewind_pointsruntime/rewind.py3014
StreamRenderer.on_stream_eventui/rendering/rendering.py297
_modified_keyui/prompt/prompt_keys.py283
QuestionMenu.choosebuiltin_plugins/ask_user_menu.py2711
WebService.projectsbuiltin_plugins/web/service.py2713
_run_model_pickerui/menus/model_picker.py2615
Settings.validate_worktree_remove_commandsconfig/__init__.py257
_docclai_docs.py2512
validate_model_optionsmodels/model_options.py2513
FolderMenu.runbuiltin_plugins/coder_folders.py2415
LivePrompt._routeui/prompt/live_prompt.py2411
PromptBuffer.rowsui/prompt/prompt_buffer.py2415
SessionBrowser.handle_keyui/menus/session_browser.py2410
ToolOutput.renderui/rendering/tool_output.py247
open_add_model_menuui/menus/model_menu.py2412
LivePrompt.frameui/prompt/live_prompt.py2313
_run_menuui/menus/accounts_menu.py2315
model_commandui/menus/model_picker.py2312
QuestionMenu.framebuiltin_plugins/ask_user_menu.py2213
SessionView.applybuiltin_plugins/web/client.py2214
_heredoc_languageui/rendering/command_syntax.py226
FolderMenu.problembuiltin_plugins/coder_folders.py2111
ItemLog.applybuiltin_plugins/web/protocol.py2113
_edit_rowmcp/form.py2112
_tool_changesbuiltin_plugins/web/changes.py2110
command_segmentsui/rendering/command_syntax.py2115
render_historyui/rendering/history.py216
confirmedbuiltin_plugins/web/workspace_tools.py2013
edit_chainui/menus/chain_menu.py2015
LivePrompt.acceptui/prompt/live_prompt.py1911
ServerForm.toggle_oauthmcp/form.py199
SessionPlugins._commandplugins/loader.py1915
SessionPlugins.load_allplugins/loader.py1915
_parse_user_fileui/rendering/spinners.py197
limit_response_retry_aftermodels/retry_after.py196
project_namesbuiltin_plugins/web/sidebar.py1912
Splash.frameui/rendering/splash.py183
_read_clai_docsclai_docs.py189
locatebuiltin_plugins/aoe.py186
DirectoryPicker.runbuiltin_plugins/coder_folders.py1712
SessionBrowser._projects_frameui/menus/session_browser.py173
TranscriptBuffer.writeui/prompt/prompt_transcript.py176
WebService.followbuiltin_plugins/web/service.py178
_beforebuiltin_plugins/web/changes.py1712
error_messageerrors.py1715
plugins_commandcommands.py1710
spinner_commandui/menus/spinner_picker.py1713
HerdrClient._renamebuiltin_plugins/herdr_client.py1615
PromptBuffer.search_keyui/prompt/prompt_buffer.py1611
PromptKeys.dispatchui/prompt/prompt_keys.py1610
SessionChannel.observebuiltin_plugins/web/channel.py1614
_openai_optionsmodels/model_options.py1612
model_optionsmodels/model_options.py1612
url_atui/prompt/prompt_selection.py1615
Total1336655

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 -

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 -

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 -

2026-11-03 · pre-push review 2 of 3 at 034e7071dec465f5961f2aba8038322a43e4cd53 · iter -

2026-11-03 · pre-push review 3 of 3 at 21484d0cc6a01197f1a1891fa2c7c083bbb0289f · iter -

2026-11-03 · pre-push review 3 of 3 at 21484d0cc6a01197f1a1891fa2c7c083bbb0289f · iter -

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 match with 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 partial where 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.